text
stringlengths
8
6.05M
#encoding utf8 dp = [] dp[0] = 0 print(dp)
from setuptools import setup, find_packages import os setup(name='cyberhead', version='1.0', url='https://github.com/TheCyberHead', license='MIT', author='CyberHead LLC', author_email='info@cyberhead.com', entry_points={"console_scripts": ["cyberhead = cyberhead.wrapper:c...
a = '12345' b = int(a) print(b) print(type(b)) c = int(a, base=8) print(c) d = int(a, base=6) # print(d) # 偏函数,构造一个新函数 import functools int2 = functools.partial(int, base=2) f = int2('1001') print(f)
# Wind Turbine Allocation Game # import libraries import pygame as pg import random from settings import * from sprites import * from windspeed import * import time from os import path ###### Game Idea ######## # Regions # - Implement 2-4 regions / on-shore and off-shore locations # - Implement slots where...
import argparse import numpy as np import tensorflow as tf import os import CNN_recurrent import helper os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # use CPU for RPM to ensure the determinism config = tf.ConfigProto(allow_soft_placement=True, device_count={'GPU': 0}) sess = tf.Session(config=config) parser = argparse.A...
from app.views import all_pages, show_page def setup_routes(app): app.router.add_get('/api/v1/list_pages', all_pages) app.router.add_get('/api/v1/page/{page_id}', show_page)
import logging import os import json from backend import LookupHotelInviumPlaces API_KEY = os.environ.get('API_KEY') LOGGING_LEVEL = os.environ.get('LOGGING_LEVEL') def handler(event, context): if LOGGING_LEVEL == 'DEBUG': logging.getLogger().setLevel(logging.DEBUG) else: logging.getLogger().s...
class Circle: name = 'Circle' def __init__(self, color, size): self.color = color self.size = size class Triangle: name = 'Triangle' def __init__(self, color, size): self.color = color self.size = size class Rectangle: name = 'Rectangle' def __init__(self, ...
import unittest from katas.kyu_8.squash_the_bugs import find_longest class SquashTheBugsTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(find_longest( 'The quick white fox jumped around the massive dog' ), 7 ) def test_equals_2(self): self....
def solution(s): # 이 문제의 관건은 빈 공백문자에 있고 split()과 split(' ')의 차이를 알아야함 # split(' ') 공백을 살려서 받아와서 이걸 써야함 # 따로 리스트를 만들어 주는게 너무 오래 걸릴 수 있음 # answer = ' '.join([i.capitalize() for i in s.split(' ')]) sub = s.split(' ') cap = [] for i in sub: cap.append(i.capitalize()) answer = ' '.joi...
import logging import numpy as np from parser.argument_parser import training_arguments_parser from parser import configs from parser.constants import RNN_EXPT_DIRECTORY, ACTION_CHANNEL_LABELS_PATH from parser.model import Model from parser import utils class ActionChannelModel(Model): """Model for predicting Ac...
""" Contains business logic tasks for this order of the task factory. Each task should be wrapped inside a task closure that accepts a **kargs parameter used for task initialization. """ def make_task_dict(): """ Returns a task dictionary containing all tasks in this module. """ task_dict = {} task...
# Generate a land/sea mask for the MRED domain import netCDF3 import mm5_class import mx.DateTime mm5 = mm5_class.mm5('TERRAIN_DOMAIN1') land = mm5.get_field('landmask', 0) # 1,143,208 data = land['values'] lats = mm5.get_field('latitdot',0)['values'] lons = mm5.get_field('longidot',0)['values'] nc = netCDF3.Datas...
from django.urls import path from django.views.generic import TemplateView from . import views urlpatterns = [ path('hello/', views.hello, name='hello'), path('morning/', views.morning, name='morning'), path('article/<id>/', views.view_article, name='article'), path('articles/<month>/<year>/', views....
#!/usr/bin/env python import math import sys #power=int(sys.argv[1]) power=4 summ=0 for i in range(1,11): an= math.pow(i,power) summ+= an print "%2d %5d %5d"%(i, an, summ) print math.pow(10,power+1)/power
#-*-coding:utf-8-*- """ "创建者:Li Zhen "创建时间:2019/4/4 17:41 "描述:TODO 通过sin预测Cos """ import torch import torch.nn as nn from torch.nn import functional as F from torch import optim import numpy as np from matplotlib import pyplot as plt import matplotlib.animation import math, random # rnn时序不唱数 TIME_STEP=20 # rnn的输入维...
import nltk # nltk.download() from nltk import word_tokenize from nltk.util import ngrams from collections import Counter # text = "I need to write a program in NLTK that breaks a corpus (a large collection of txt files) into unigrams, bigrams, trigrams, fourgrams and fivegrams. I need to write a program in NLTK that...
# importing Dataloader class from data_transformation from data_transformation.data_loader import Dataloader from training.model import Model from application_logging.logger import Applog import warnings warnings.filterwarnings('ignore') if __name__ == '__main__': def load_data(func): logg_data_transform =...
from typing import List import random def mergesort(nums: List[int]) -> List[int]: if len(nums) <= 1: return nums center = len(nums) // 2 nums_l = nums[:center] nums_r = nums[center:] mergesort(nums_l) mergesort(nums_r) i = j = k = 0 while i < len(nums_l) and j < len(nums_r): ...
#!/usr/bin/env python3 """Check file for non-ascii lines.""" from sys import argv path = argv[1] print('Path:', path) def isascii(string): try: string_ascii = string.encode('ascii') return True except UnicodeEncodeError: return False def check_file(): num = 0 with open(pat...
import random import time import copy import sys def cal_time(func): '''计算函数运行时间的装饰器''' def wrapper(*args, **kwargs): t1 = time.time() result = func(*args, **kwargs) t2 = time.time() print("%s running time: %s secs." % (func.__name__, t2-t1)) return result return wr...
"""Access Rules Classes.""" from fmcapi.api_objects.apiclasstemplate import APIClassTemplate from fmcapi.api_objects.policy_services.accesspolicies import AccessPolicies from fmcapi.api_objects.policy_services.intrusionpolicies import IntrusionPolicies from fmcapi.api_objects.object_services.variablesets import Variab...
#!/usr/bin/python # coding: utf-8 import sys import Image import random import os import ImageDraw import ImageFont import ImageFilter from time import gmtime, strftime import time import ImageEnhance import pickle allongement = 4 im1 = Image.open(str(sys.argv[1])) im2 = Image.new("RGBA",(im1.size[0], im1.size[1])) ...
import tensorflow as tf import numpy as np from tf_util.stat_util import approx_equal from dsn.util.dsn_util import check_convergence DTYPE = tf.float64 EPS = 1e-16 def test_check_convergence(): np.random.seed(0) array_len = 1000 converge_ind = 500 num_params = 10 cost_grads = np.zeros((array_le...
import unittest from katas.beta.the_skeptical_kid_generator import alan_annoying_kid class AlanAnnoyingKidTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(alan_annoying_kid("Today I played football."), "I don't think you played football today, I think y" ...
def LS_X(string_input, X): """ Summary and Description of Function: This function shifts all of the characters of a string by "X" places to the left. The leftmost characters are deleted in replacement of "X" hashtags ("#") to the right. Parameters: ...
import random import math import numpy as np import torch import torch.nn.functional as F import torch.optim as optim import torch.nn as nn #import os, json #import matplotlib.pyplot as plt from agent_dir.agent import Agent from environment import Environment from collections import namedtuple use_cuda = torch.cuda.i...
import pandas as pn import math from sklearn.metrics import roc_auc_score data = pn.read_csv('./DATA/W03_03.csv', header=None) X = data.loc[:, 1:] y = data.loc[:, 0] S1, S2, w1, w2, w1_past, w2_past = 0,0,0,0,0,0 j = 0 #un-regularized # while j <= 10000: # w1_grad, w1_past = w1, w1 # w2_grad, w2_past = w2, ...
from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), path('<int:key>/detail/', views.post_detail, name='post_detail'), path('<int:key>/update/', views.post_update, name='post_update'), path('create/', views.post_create, name='post_create'), p...
from django.conf import settings from confapp import conf from pyforms.controls import ControlCheckBox from pyforms_web.web.middleware import PyFormsMiddleware from pyforms_web.widgets.django import ModelAdminWidget from finance.models import Project from .financeproject_form import FinanceProjectFormApp class Fin...
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # # Gathered Notebook # # This notebook was generated by an experimental feature called "Gather". The intent is that it contains only the code and cells required to produce the same results as the cell originally sel...
import math A=float(input("A= ")) B=float(input("B= ")) C=float(input("C= ")) D=(pow(B,2))-4*A*C smaller_root=(-B-math.sqrt(D))/(2*A) larger_root=(-B+math.sqrt(D))/(2*A) print("x1= ",smaller_root) print("x2= ",larger_root)
# Copyright (c) 2021 kamyu. All rights reserved. # # Google Code Jam 2021 Qualification Round - Problem C. Reversort Engineering # https://codingcompetitions.withgoogle.com/codejam/round/000000000043580a/00000000006d12d7 # # Time: O(N) # Space: O(1) # def reverse(L, i, j): while i < j: L[i], L[j] = L[j], ...
class RegionCodeIsAbsentError(Exception): pass class WorksheetAbsentError(Exception): pass
# -*- coding:utf-8 -*- # author: will import datetime import time from flask import request, jsonify, g from app import db from app.models import Banner, Article, UserBTN, UpdateTime from utils.user_service.login import login_required, admin_required from . import api_banner # @api_banner.route('/uploadimage',metho...
# Covered # lists # strings # dictionaries # tuples ############################################################################### # Lists ############################################################################### # Source: https://developers.google.com/edu/python/lists list = ['larry', 'curly', 'moe'] # Thi...
# Should use dedicated mayavi environment because of its odd requirements import pandas as pd import numpy as np import os import sys from mayavi import mlab # You can pass a set of folders to analyze, or else the script will do them all if len(sys.argv) > 1: folders = sys.argv[1:] else: folders = os.listdir(s...
from collections import defaultdict # 중복되는 report는 횟수로 사용하지 않으므로, set을 활용하여 중복값을 제거하여 사용하면 더 빠르게 좋은 값을 가져올 수 있다. def solution(id_list, report, k): answer = [] stoper = defaultdict(int) # 정지된 ID reporter = defaultdict(list) # 신고한 ID # 신고 중 신고 받은 횟수와 신고한 사람의 목록을 정리 for i in report: p1, p2...
# -*- coding: utf-8 -*- class TrieNode: def __init__(self): self.children = {} self.leaf = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): current = self.root for char in word: if char not in current.children: ...
from _typeshed import Incomplete def fast_gnp_random_graph( n, p, seed: Incomplete | None = None, directed: bool = False ): ... def gnp_random_graph(n, p, seed: Incomplete | None = None, directed: bool = False): ... binomial_graph = gnp_random_graph erdos_renyi_graph = gnp_random_graph def dense_gnm_random_graph...
from flask import jsonify from psycopg2 import IntegrityError from app.DAOs.BuildingDAO import BuildingDAO ADD_BUILDING_KEYS = ["edificioid", "nomoficial", "blddenom", "codigoold", "bldtype", "attributes"] def _buildBuildingResponse(building_tuple): """ Private Method to build building dictionary to be JSONi...
import os import dotenv def get_sql_connection_string(): dotenv.load_dotenv() return "DRIVER=%(SQL_DRIVER)s;SERVER=%(SQL_SERVER)s;PORT=1433;DATABASE=%(SQL_DATABASE)s;UID=%(SQL_USERNAME)s;PWD={%(SQL_PASSWORD)s}" % os.environ
import requests import time import simplejson import setting import config def get_proxy(retry=10): count=0 proxyurl = 'http://:8081/dynamicIp/common/getDynamicIp.do' for i in range(retry): try: r = requests.get(proxyurl, timeout=10) print(r.text) except Exception as ...
# -*- coding: utf-8 -*- ''' Created on 2016.6.14 @author: huke ''' def mul(n): if n <= 1: return 1 else: return n*mul(n-1) if __name__ == '__main__': n = input('请输入阶乘的次数') print(mul(int(n)))
#!/usr/bin/env python #coding=utf-8 ''' Created on 2018年2月23日 @author: jacket ''' import unittest from src.tools.CommentTool import isContainCommentForCPP,openFile fileText=openFile("/home/jacket/Server/src/main.cpp") # print fileText class Test(unittest.TestCase): def test_case1(self): print isContain...
#!/usr/bin/env python # # Script by Steven Grove (@sigwo) # www.sigwo.com # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AU...
""" BayesianOptimization package from https://github.com/fmfn/BayesianOptimization """ from __future__ import print_function from collections import OrderedDict import numpy as np try: from bayes_opt import BayesianOptimization bayes_opt_present = True except Exception: BayesianOptimization = None bay...
#!/usr/bin/env python3 from copy import deepcopy from lib.pos import Pos from lib.zone.zone_base import ZoneBase # Circular dependency workaround for Python; can be a normal import for Java import lib.zone.zone as zone class ZoneFragment(ZoneBase): """A zone fragment where non-standard behavior occurs. pos2 ...
# INFLATE.PY # Decompresses files compressed with deflate_not3 # Theoretically. import heapq as hq import sys import bitstring as bs import huff_functions as huff import deflate_fns as defl # ------------------------------------------------------------- # Function that takes care of buffer for reading individual bits...
# EXERCISE_5 WORK OF THE BOOK : num = eval(input("Enter the number :")) print( "The Number is :",num) print("Suquar of the User's Number :",num*num,sep=".")
# Generated by Django 2.1.4 on 2019-01-17 09:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('base', '0011_auto_20190117_0108'), ] operations = [ migrations.RemoveField( model_name='householdmembership', name='created_...
import mechanicalsoup url = "http://olympus.realpython.org/login" browser = mechanicalsoup.Browser() page = browser.get(url) html = page.soup form = html.select("form")[0] form.select("input")[0]["value"] = "zeus" form.select("input")[1]["value"] = "ThunderDude" profiles_page = browser.submit(form, page...
import dill # from aggregator import Data_Cleaner def pickle_object(object_to_pickle, name): ''' This function pickles the object with the name given. ''' savefile = open(name, 'wb') dill.dump(object_to_pickle, savefile, protocol=2) savefile.close() def load_pickled_object(filename): obj...
from django.contrib import admin from visitations.models import Visitation # Register your models here. admin.site.register(Visitation)
''' Given a .sam file extract the mapping of sequence to haplotype. ''' import argparse import re haplotype = {} def read_contigs(contig_file_name): with open(contig_file_name, 'r') as contig_file: for line in contig_file: found = re.search("(^seq[^\s]+)\s[^\s]+\s([^\s]+)", line) ...
import sys def min_heapify(heap, start, end): root = start left = 2 * root + 1 right = 2 * root + 2 if left < end and heap[root] > heap[left]: root = left if right < end and heap[root] > heap[right]: root = right if start != root: heap[start], heap[root] = heap[root], h...
from __future__ import absolute_import, unicode_literals from datetime import timezone import os from celery import Celery from celery.schedules import schedule from django.conf import settings # from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stock_tracker.settings') app = Celer...
import os input_path = os.path.join(os.path.dirname(__file__), 'input.txt') with open(input_path) as file: original_polymer = file.read() def react(polymer): index = -1 for char in polymer: index += 1 if index != 0: if polymer[index-1] == char.swapcase(): poly...
import time from django.core.management.base import BaseCommand from django.db.models import Sum from django.template.defaultfilters import filesizeformat from ... import scan from ... import models class Command(BaseCommand): help="Scan the filesystem for changes and update the cache database" def handle(s...
import urllib3 import json import threading import time import argparse import logging import sys import base64 from urllib3 import HTTPConnectionPool query = { "query": { "bool": { "must": [ { "match_phrase": { "send_dy": "7850858542" } }, { ...
cols=['a','b','c'] res_cols=[1,2,3,4,5,6,7] li=[] mapping = {'surface': cols[0],'base': res_cols[6],'pos': res_cols[0],'pos1': res_cols[1]} li.append(mapping) mapping = {'surface': cols[1],'base': res_cols[5],'pos': res_cols[1],'pos1': res_cols[2]} li.append(mapping) print(li)
# coding: utf-8 from ansible.module_utils.basic import * import os def main(): module = AnsibleModule(argument_spec=dict(args=dict(required=True))) args = module.params['args'] try: res = os.popen('echo {0}'.format(args)).read().strip() res_json = dict(echo=res, changed=False, stdout_li...
# -*- coding: UTF-8 -*- ''' Created on 20171031 @author: leochechen @Summary: 一个Client连接过来,对应一个Worker。worker使用Python中的线程实现 ''' import os import pickle import argparse import traceback import threading from threading import Thread from operator import itemgetter from protocol import Command from ctf_local import CTFWork...
#! /usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import sys from scipy.optimize import minimize from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection #GLOBAL CONSTANTS - conversion factors degToRad = np.pi/180 radToDeg = 180.0/np.pi P...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os PATH = '/tmp' def enumerate_path(path): """ Returns list of path to all files in dir :param path: path name :return: list of path to files """ path_collection = [] for dir_path, dir_names, file_names in os.walk(path): for fi...
#Philip Brendel #I pledge my honor that I have followed the Stevens Honor code def bmiCalc(): weight = int(input("Please enter your weight (in pounds): ")) height = int(input("Please enter your height (in inches): ")) bmi = (weight * 720)/(height**2) if bmi < 19: print("Your BMI is ", bmi, "w...
#!/usr/bin/env python from sys import version_info if version_info[0] < 3: from urllib import quote else: from urllib.request import quote from glob import glob import json import re header = ''' Place for everything Pandas. Lessons ------- ''' format_item = '* [{name}]({url})'.format bb_url = 'bitbuck...
#!/home/kiwitech/mysite/dbcon/bin/python3 from django.core import management if __name__ == "__main__": management.execute_from_command_line()
import flask from flask import request, jsonify import psutil import json from uptime import uptime app = flask.Flask(__name__) @app.route('/cpuinfo', methods=['GET']) def cpuinfo(): return jsonify({'cpu_percent': psutil.cpu_percent(interval=None,percpu=False)}) @app.route('/cpuinfopercore', methods=['GET']) def...
#Li Xin #Student number: 014696390 #xin.li@helsinki.fi import socket import sys import time if __name__ == "__main__": #get port from the input port = sys.argv[1] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() s.bind((host, int(port))) s.listen(5) loop = True while loop: ...
def greet(): print("hello") greet() def gree_two(greeting): print(greeting) gree_two("dinesh")
#! /usr/bin/python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class HtmlMail(object): """This class sends HTML emails""" def __init__(self, subject, sender, to, username, password, smtp="smtp.gmail.com", port=587): # Server attr ...
# coding: utf-8 # Python script created by Lucas Hale # Standard library imports from typing import Optional, Union # http://www.numpy.org/ import numpy as np # https://github.com/usnistgov/atomman import atomman as am import atomman.unitconvert as uc def sdvpn(ucell: am.System, C: am.ElasticConstants, ...
from tensorflow.keras.layers import Dense, LSTM, BatchNormalization, Dropout from tensorflow.keras import Sequential import json data_config = json.load(open("data_config.json")) timesteps_x = data_config["input_timesteps"] n_features = len(data_config["input_features"]) # Model definition model = Sequential() model....
def pyramid(n): output = '' for x in reversed(range(n)): if x != 0: output += (x * ' ' + '/' + (((x+1) - n)*-1)*2 * ' ' + '\\' + '\n') else: output += (x * ' ' + '/' + (((x+1) - n)*-1)*2 * '_' + '\\' + '\n') return output ''' The task is very simple. You must to r...
import functools import time import uuid from concurrent.futures.thread import ThreadPoolExecutor from wacryptolib.exceptions import KeyAlreadyExists, KeyDoesNotExist, OperationNotSupported from wacryptolib.utilities import generate_uuid0 # SEE https://docs.pytest.org/en/stable/writing_plugins.html#assertion-rewriti...
from django.utils.translation import ugettext from querystring_parser import parser from utils.exceptions import CustomException def jwt_response_payload_handler(token): """ Add any data you want to payload of response :param token: :return: """ return { 'token': token, } def pa...
# Override Zinnia's default urlconf to filter listings by language/category """Urls for the Zinnia archives""" from django.conf.urls import url from django.conf.urls import include from django.conf.urls import patterns from zinnia.urls import _ from developer_portal.blog.views import MultiLangEntryDay from developer_...
from __future__ import print_function from flask import Flask, render_template, request, make_response, jsonify, send_file import sys, os, re, random, logging, stat, time import requests, json import pandas as pd from urllib import urlencode from lxml import html from config import * app = Flask(__name__) @app.ro...
# __init__.py # Copyright (C) 2011-2014 Andrew Svetlov # andrew.svetlov@gmail.com # # This module is part of BloggerTool and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from bloggertool.__version__ import __version__ __all__ = ['__version__']
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 16/4/24 上午10:15 # @Author : ZHZ import pandas as pd import datetime item_store_feature = pd.read_csv("/Users/zhuohaizhen/PycharmProjects/Tianchi_Python/Data/OutputData/1_isf1.csv", index_col=0) item_feature = pd.read_csv("/Users/zhuohaizhen/PycharmProjects/Ti...
#!/usr/bin/python -tt # # Copyright (c) 2011 Intel, Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; version 2 of the License # # This program is distributed in the hope that it will be us...
thislist =["apple", "banana", "grapes"] print(thislist[0])
def crossover(chr1, chr2, index): return [chr1[:index]+chr2[index:], chr2[:index]+chr1[index:]] ''' In genetic algorithms, crossover is a genetic operator used to vary the programming of chromosomes from one generation to the next. The one-point crossover consists in swapping one's cromosome part with another in ...
from matplotlib import pyplot as plt from utils import * import numpy as np import argparse def load(path='./input.dat'): """ Load the sequential training data Arg: path - The path of the training data Ret: The 2-D array whose shape is [num_epoch, 2] """ string = open(path...
#!/usr/bin/python # # Copyright (C) 2010 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of...
def get_bioc_TxDb_pkg(wildcards): """Get the package bioconductor package name for the the species in config.yaml""" species = config["txdb"]["species"].capitalize() Source = config["txdb"]["Source"] build = config["txdb"]["build"] version = config["txdb"]["version"] if Source == "UCSC": ...
# Generated by Django 3.0.7 on 2020-08-19 14:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('staff', '0003_auto_20200817_2050'), ] operations = [ migrations.AlterField( model_name='districtstaff', name='empnum...
# flake8: noqa from .evaluation_callback import EvaluationCallback from .gradient_clipping_callback import GradientClippingCallback from .learning_rate_finder_callback import LearningRateFinderCallback from .lr_scheduler_callback import LRSchedulerCallback from .partial_freeze_embeddings_callback import PartialFreezeEm...
from spack import * import sys,os,re sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class LlvmLibToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f0...
from waveapi import events from waveapi import model from waveapi import robot import waveapi.document as doc import re def OnParticipantsChanged(properties, context): """Invoked when any participants have been added/removed.""" added = properties['participantsAdded'] for p in added: Notify(context) def OnRobotA...
import pygame, sys from config import Config from snake import Snake from apple import Apple class Game(): def __init__(self): pygame.init() self.screen = pygame.display.set_mode((Config.WINDOW_WIDTH,Config.WINDOW_HEIGHT)) self.clock = pygame.time.Clock() self.BASICFONT = pygame.fon...
class Flight(object): def __init__(self, **kwargs): mandatory_fields = ["source", "destination", "start_date", "end_date", "price", "airway", "flight_id"] for key, val in kwargs.iteritems(): setattr(self, key, val) for key in mandatory_fields: if not hasattr...
from swa.items import * from scrapy.spiders import Spider from scrapy.http import FormRequest,Request from scrapy.selector.lxmlsel import HtmlXPathSelector from scrapy.selector import Selector from scrapy.http import HtmlResponse from datetime import datetime, timedelta from dateutil.parser import parse as dateParse im...
# encoding: utf-8 """Program do testowania naiwnego klasyfikatora bayesowskiego.""" import glob import re import sys import NaiveBayes from Task901 import train from Task905 import classify def getwords(docname): """Wyznacza zbiór cech (słów).""" doc = open(docname).read() splitter = re.compile('\\W*') ...
import os import yaml import codecs from general_tools.file_utils import write_file class RC: def __init__(self, directory): """ :param string directory: """ self.dir = directory manifest_file = os.path.join(directory, 'manifest.yaml') self.manifest = self.__read_y...
# @Time : 2018-9-10 # @Author : zxh import hashlib import os def cal_md5(filepath): md5file=open(filepath, 'rb') md5=hashlib.md5(md5file.read()).hexdigest() md5file.close() return md5 def write_md5(filepath, md5): with open(filepath, 'w') as f: f.write(md5) def read_md5(filepath): ...
import zmq.green as zmq from basesocket import BaseSocket class Server(BaseSocket): def __init__(self, host='0.0.0.0', port=12305): context = zmq.Context() self.receiver = context.socket(zmq.PULL) self.receiver.bind('tcp://%s:%i' % (host, port)) self.sender = context.socket(zmq.P...
import json import jwt import time import logging import pre from gmssl import sm2 jwt_secret = 'tuna and bacon are my favorite' def register(username, pubkey): # ensure user names are distinct sql = "SELECT * FROM Users WHERE UserName='{}'".format(username) if len(pre.select(sql)) != 0: return jso...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module with functions common to whole project.""" from django.views import i18n from django.conf import settings from django.http import HttpResponse, HttpResponseServerError, \ HttpResponseNotFound from django.template import Context, RequestC...