text stringlengths 38 1.54M |
|---|
from collections import namedtuple
import json
# ScrapedData = namedtuple('ScrapedData', 'title code employment_2016 employment_2026 change_number change_percent anual_wage')
# s = ScrapedData(title='Management Occupations', code='11-0000', employment_2016='9,533.1', employment_2026='10,411.5',
# change_number='878.... |
"""
Created on 12:08, May. 23rd, 2021
Author: fassial
Filename: test_inputs.py
"""
# local dep
import stimulus
__all__ = [
"test_poisson_input",
]
## define test func
# define test_poisson_input func
def test_poisson_input():
# get stim
stim, _ = stimulus.inputs.poisson_input(
duration = 100
)... |
#!/usr/bin/python3
"""Island_perimeter in python"""
def island_perimeter(grid):
"""That returns the perimeter of the island described in grid"""
base_actual = 0
base_max = 0
altura = 0
for row in grid:
base_actual = 0
for column in row:
if column == 1:
... |
from multiprocessing import Process, cpu_count, freeze_support, Queue
import numpy as np
from math import ceil, floor
import time
def next(seed):
seed = (seed * 0x5deece66d + 0xb) & ((1 << 48) - 1)
retval = seed >> (48 - 31)
if retval & (1 << 31):
retval -= (1 << 32)
return retval, ... |
from EMAIL import *
from fra import *
from time import gmtime, strftime
import sys
import logging
import time
FILENAME = "MaxaromaNA"
Subject = "MaxAroma_NewArrival"
def main():
url = "http://www.maxaroma.com/"
original = getMaxAroma(url)
# dumpToSave(original)
sendemail("Started " + FILENAME,Subject)
while True:
... |
import subprocess
def executeCommand():
'''
Read a command from a user input, validate it, and execute it
''' |
from astral.adapters.Net import TCPServer,errors
from base_adapter import ClientAdapter
import socket
import threading
import time
class server_adapter(TCPServer):
def __init__(self,gameserver,host="127.0.0.1",port=1919):
TCPServer.__init__(self)
self.gameserver = gameserver
self.... |
# importing dataset
from sklearn.datasets import .... as fetch_olivetti_faces
faces = fetch_olivetti_faces()
img = faces.images
M = 400
N = 4096
img2 = np.array([[0 for i in range(N)] for j in range(M)])
# visage moyen = vm
vm = [0 for i in range(N)]
for a in img:
img2 = a.flatten()
vm = vm + img2
vm1 = vm... |
n=13
L=[ [ 0 for i in range(n) ] for j in range(n) ]
k,l=n-1,int((n+1)/2-1)
if (n%2!=0):
L[k][l]=1
for i in range (1,n**2):
if (L[(k+i)%n][(l+i)%n] == 0):
L[(k+i)%n][(l+i)%n] = i+1
else:
L[(k+i-2)%n][(l+i-1)%n]=i+1
k,l=(k+i-2)%n,(l+i-1)%n
for i in range(n):
... |
from django.contrib import admin
from online_app.models import *
# Register your models here.
admin.site.register(Repo)
admin.site.register(Package) |
#!/usr/bin/python3
import xmlrpc.client
import time
import sys
if len(sys.argv) == 1:
print("USAGE: %s <server>" % sys.argv[0])
sys.exit(0)
s = xmlrpc.client.ServerProxy('http://%s:8000' % sys.argv[1])
pre = time.time()
response = s.ping()
post = time.time()
diff = post - pre
print(pre,response,post,diff)
... |
#!/usr/bin/env python3
import yaml
from jinja2 import Template
from datetime import datetime
from kubernetes import client, config
def main():
kaniko("sidecar", "latest", "git://github.com/kbase/init-sidecar.git")
def kaniko(image, tag, repo):
# Set image name, and consistent timestamp
build_image_name =... |
import os
import csv
import time
import imaplib
import email
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, jsonify
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(DATADIR="data"))
app.config.from_envvar('QVTABLE_SETTINGS', silent=Tr... |
import urllib2
from pyIEM import iemdb
import mx.DateTime
i = iemdb.iemdb()
coop = i['coop']
mesosite = i['mesosite']
stmeta = {}
def parse_lonlat( txt ):
tokens = txt.split()
lat = float(tokens[0]) + ((float(tokens[1]) + float(tokens[2]) / 60.0) / 60.0)
lon = float(tokens[3]) - ((float(tokens[4]) + float(toke... |
#! /usr/bin/python
import sys
scaffoldFile = sys.argv[1]
outputFile = "%s_unique.fasta" %(scaffoldFile)
infileScaffolds = open(scaffoldFile, "r")
outfile = open(outputFile, "w")
fastaDict = {}
key = 0
fastaDict[key] = []
for line in infileScaffolds:
if ">" in line:
joinLine = "".join(fastaDict[key])
fastaDict[... |
# Generated by Django 3.0.3 on 2020-03-21 14:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mywebsite', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='project',
name='desc',
fi... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 18:01:34 2015
@author: Erin
"""
# An implementation of example 2 from MT-DREAM(ZS) original Matlab code. (see Laloy and Vrugt 2012)
# 200 dimensional Gaussian distribution
import numpy as np
import os
from pydream.parameters import FlatParam
from pydream.core import ... |
def count(valuelist):
return_list = []
for a in range(0,len(valuelist)-1):
return_list.append(abs(valuelist[a]-valuelist[a+1]))
return return_list
test_case = int(input())
while(test_case):
input_list = list(input())
reversed_input_list = reversed(input_list)
input_list = [ord(x) for x i... |
import os
import random
import string
import setup_catalog
from google.api_core.client_options import ClientOptions
from google.cloud.retail_v2 import SearchServiceClient, SearchRequest
project_number = "1038874412926"
endpoint = "retail.googleapis.com"
isolation_filter_key = "INTEGRATION_FILTER_KEY"
title_query = "... |
from itertools import product
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C
X = np.array([[0,0],[2,0],[4,0],[6,0],[8,0],[10,0],[... |
import aiohttp_cors
from app.api import profile, roadmaps, skills, spec, vacancies
def setup_routes(app):
"""Добавлена точка входа для приложения."""
cors = aiohttp_cors.setup(app, defaults={
'*': aiohttp_cors.ResourceOptions(
allow_credentials=True,
expose_headers='*',
... |
import hashlib
import random
from string import ascii_uppercase, digits
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from .serializers import TransactionModelSerializer
from .models import Transaction
from rest_fram... |
import gtk
from System import SystemType
current_system = SystemType()
class StatusIcon:
def __init__(self, parent):
self.parent = parent
iconpath = "WWU.gif"
self.statusicon = gtk.StatusIcon()
self.statusicon.set_from_file(iconpath)
self.statusicon.connect("button... |
import requests
import time,random
from bs4 import BeautifulSoup
from urllib import request
def getData(data):
string=""
time,temp,pict,condi,confort,rain,msg=[],[],[],[],[],[],[]
for data_ in data:#取得時間、溫度、天氣狀況、舒適度、降雨機率等資料
time.append(data_.find('th',{'scope':'row'}).text)
temp.append(data... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Time : 2017-08-25 14:33
# Author : MrFiona
# File : summary_optparse.py
# Software: PyCharm Community Edition
"""
模块optparse使用类OptionParser来作为命令行选项的解析器;下面是该类的方法:
1、OptionParser(self, prog=None, usage=None, description=None, epilog=None, option_list=None... |
from __future__ import absolute_import
import re
import json
import requests
from apis.base import BaseAPI, APIException
# Flickr API: https://www.flickr.com/services/api/
class FlickrPhotoAPI(BaseAPI):
url_format = "https://farm{farm}.staticflickr.com/{server}/{id}_{secret}_m.jpg"
per_page = 10
def __in... |
from aiohttp import web
from docker import Client
from .launcher import Launcher
async def create_container_handler(request):
launch_config = request.app['launch_config']
hostname = await request.app['launcher'].launch(**launch_config)
headers = {'Access-Control-Allow-Origin': '*'}
return web.Respons... |
# Generated by Django 3.1.3 on 2020-11-08 16:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20201105_1100'),
]
operations = [
migrations.AddField(
model_name='game',
name='end_date',
... |
# -*- coding: utf-8 -*-
import itertools
import time
from flask import Flask, jsonify, request, render_template
import os
import io
import firebase_admin
from firebase_admin import db
from firebase_admin import credentials, firestore
from google.cloud import storage
from PIL import Image
import requests
from io import... |
__author__ = 'Li Bai'
"""the available data are loaded from nordhavn3_april.csv, and the explanatory variables are weather forecasts
('temperature', 'humidity', 'DNI (Direct normal irradiance)', 'windspeed') and
the output is heat load. Considering the time-frequency domain analysis, 'Day sin',
'Day co... |
import sys
from collections import OrderedDict
import pandas as pd
import numpy as np
import operator as op
import tensorflow as tf
from .common import constructNetwork
from .common import constructNetworkWithoutDropout
from .common import convertDateColsToInt
from .common import arrayToText
from .common import cons... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
class Utils():
def __init__(self):
pass
def get_otsu_threshold(self, image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bitwise_not(gray)
thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY | cv2.TH... |
from django import template
register = template.Library()
from video.models import Video
@register.inclusion_tag('video/tags/lattest_videos.html', takes_context=True)
def lattest_videos(context):
lattest_videos = Video.objects.all().filter( galleries__is_public=True).order_by('created')[:6]
context['lattest_vide... |
import logging
from datetime import datetime
import requests
from common import db_session
from configuration import API_KEY
from .models import TrainActivity
BASE_V2_URL = 'http://realtime.mbta.com/developer/api/v2'
logger = logging.getLogger(__name__)
def format_mbta_request_url(api_key: str):
return '{}/pre... |
# coding: utf-8
"""
The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + ... + 10^(2) = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^(2) = 55^(2) = 3025
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of ... |
# -*- coding:utf-8 -*-
import os
def getPlus(a, b):
k1 = len(str(a))
s1 = str(a)
k2 = len(str(b))
s2 = str(b)
print k1, type(s1), s1, " |--| ", k2, type(s2), s2
p = list()
k = 0
for item_b in s2[::-1]:
index = k
for item_a in s1[::-1]:
num = int(item_a) ... |
from selenium import webdriver
from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time
from password import *
driver = webdriver.Chrome("C:\Chromedriver\chromedriver")
URL = "https://tinder.com/"
driver.get(URL)
drive... |
"""Helper set of functions to read in and parse multiple types of input sources."""
import sys
import os
import datetime
from bs4 import BeautifulSoup
from shapely.geometry.polygon import Polygon
def read(ftype, inDir, inSuffix, startTime, endTime):
"""
Determines the user-specified file type and parses it accordin... |
from django.conf.urls import url
from django.urls import include, path
from fichaArticulo import views as ficha_views
from . import views
urlpatterns = [
path('', include(([path('', ficha_views.fichaArticulo, name='fichaArticulo')],'fichaArticulo'), namespace='ficha')),
path(r'', ficha_views.fichaArticulo, n... |
#
# MIT License
#
# Copyright (c) 2018 Matteo Poggi m.poggi@unibo.it
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, c... |
# encoding: UTF-8
import main
from dal import base_dal
from test_main.constants import *
def test_delete_performance_report():
base_dal.delete_performance_report(YEAR, QUARTER)
if __name__ == '__main__':
main.setup_logging()
test_delete_performance_report()
|
def exercicio4():
print("Programa de calculo de média final")
media1 = int(input("Digite a média do primeiro bimestre: "))
media2 = int(input("Digite a média do segundo bimestre: "))
media3 = int(input("Digite a média do terceiro bimestre: "))
media4 = int(input("Digite a média do quarto bimestre:... |
# Generated by Django 3.1.7 on 2021-03-07 15:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gamma', '0006_merge_20210304_0032'),
]
operations = [
migrations.AddField(
model_name='post',
name='header_image',
... |
import csv
import subprocess
# stdout = subprocess.PIPE, stderr = subprocess.PIPE
subprocess.run(
["abaqus", "cae", "noGUI=./abaqusScript/autoParametric2DnoGUI.py"], shell=True)
print("*********************")
with open('force_output.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
fo... |
# Generated by Django 2.0 on 2018-01-24 07:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Coin',
fields=[
('coin_id', models.CharField(... |
# coding: utf-8
from flask import Flask, render_template
from flask import request
import funpy.app as funpy
app = Flask(__name__) #インスタンス生成
@app.route('/weather',methods=['GET', 'POST'])
def add_numbers():
lat = request.args.get('lat')
lng = request.args.get('lng')
num = funpy.api(lat,lng)
return re... |
import os
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
bucket = os.getenv("INFLUX_BUCKET")
host = os.getenv("INFLUX_HOST")
port = os.getenv("INFLUX_PORT")
org = os.getenv("INFLUX_ORG")
token = os.getenv("INFLUX_TOKEN")
class HiveData(object):
def __i... |
from django.contrib import admin
from .models import Evento
from .models import Professores
from .models import Alunos, Cursos
admin.site.register(Evento)
admin.site.register(Professores)
admin.site.register(Alunos)
admin.site.register(Cursos)
|
"""
Tests Deploy CLI
"""
from subprocess import CalledProcessError, PIPE
from unittest import TestCase
from mock import patch, call
from samcli.lib.samlib.cloudformation_command import execute_command, find_executable
class TestExecuteCommand(TestCase):
def setUp(self):
self.args = ("--arg1", "value1... |
from Calculator import BasicArithmeticOperation0_1 as BAO
# import BasicArithmeticOperation0_1 as BAO
import numpy as np
import time
import matplotlib.pyplot as plt
def trapezium_area(top, base, height):
area = BAO.multi(1 / 2, (BAO.multi(BAO.add(top, base), height)))
return area
def integration_simp(equ, st... |
from django.db import models
from django.utils.text import slugify
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
conten... |
import os
import json
def store_string_xml(xml_results, field_values, field_name):
'''Format values for writing xml output'''
for field_number in range(0, len(field_values)):
field_number_name = str(field_number).zfill(2)
k = field_name + field_number_name
xml_results[k] = field_values... |
from rest_framework.exceptions import APIException
from rest_framework import status
class ConflictError(APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = 'Conflict'
class InternalServiceError(APIException):
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
default_detail = 'I... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import glob
import os.path as osp
import cityscapesscripts.helpers.labels as CSLabels
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
from mmengine.fileio import dump
from mmengine.utils import (Timer, mkdir_or_exist, track_parallel_pr... |
import os
import pathlib
from unittest.mock import Mock
import cv2
import numpy as np
from liveprint.lp import Projector, WhiteBackground
from liveprint.pose import PosesFactory, Poses, Keypoint, TorsoKeyPoints
from liveprint.utils import Apng
class FakePosesFactory(PosesFactory):
def poses(self, image):
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 3 02:40:45 2020
@author: amk170930
"""
import airsim
import numpy as np
import setup_path
import os
from datetime import datetime
import time
class frequencyTest:
# connect to the AirSim simulator
client = airsim.CarClient()
client.confirmConnection()
cl... |
#!/usr/bin/env python3
# NOTE: NEEDS SYNCHRONIZATION FOR MULTITHREADING
import random
import string
from enum import Enum, auto
from abc import ABC,abstractmethod
from typing import (
Dict,
List,
Optional,
Tuple
)
def _random_id() -> str:
ascii = string.ascii_lowercase
return "".join(random... |
class Solution:
def romanToInt(self, s: str) -> int:
dictionary = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
my_sum = 0
... |
import numpy as np
from sklearn.linear_model import LogisticRegression
hours = np.array([0.5, 0.75, 1, 1.25, 1.5, 1.75, 1.75, 2, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 4, 4.25, 4.5, 8, 4.75, 5, 5.5]).reshape(-1, 1)
approved = np.array([0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1])
lr = LogisticRegression... |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 164