content
stringlengths
5
1.05M
"""Models of results for storage in NDB.""" import datetime import json import os import random import re from google.appengine.ext import ndb USER_NAME_RE = re.compile(r'^[\w\d\-]+-([12])$') SUPERPOWERS = [ "Detect garbage", "Scare small fish", "Read own mind", "Invisible eyebrows", "Induce flat...
import logging from yacman import select_config from .const import * from .exceptions import * _LOGGER = logging.getLogger(__name__) def get_bedbase_cfg(cfg=None): """ Determine path to the bedbase configuration file The path can be either explicitly provided or read from a $BEDBASE environment va...
# -*- coding: utf-8 -*- """ Preprocessing routine ===================== Preprocessing includes:\n * Selection of proper time-interval * Band pass filtering in [2, 50]Hz * Mark bad segments * Bad channels interpolation * Independent component analysis * Additional automatic removal of bad segments """ impor...
#!/usr/bin/python3 import argparse import site import sys import logging try: sites = site.getsitepackages() for site_path in sites: sys.path.append(site_path + "/captcha22") except: pass logging.basicConfig(level=logging.INFO) import captcha22 as _; for path in _.__path__: sys.path.append...
from i2c.bmp180 import BMP180 from i2c.i2c_bus import I2CBus from i2c.lsm303dlhl import * from time import sleep from util.utils import get_compass bus = I2CBus(1) # conf = CtrlReg1A(0x01, CtrlReg1A.X_AXIS_ENABLE|CtrlReg1A.Z_AXIS_ENABLE) acc = LSM303DLHL(bus) bar = BMP180(bus) bar.set_mode(BMP180.ULTRA_LOW_POWER_MODE)...
import inspect import os import unittest from rhc.config import Config, validate_int, validate_file class ConfigText(unittest.TestCase): def test_default(self): cfg = Config() cfg._define('foo', 'bar') self.assertEqual(cfg.foo, 'bar') def test_reset(self): cfg = Config() ...
import nbformat try: from pytest import fixture except ImportError: # pragma: no cover def fixture(func, *args, **kwargs): return func from .client import TestbookNotebookClient class testbook: def __init__(self, nb, execute=None, timeout=60, kernel_name='python3', allow_errors=False): ...
import numpy as np import pickle def get_functions(config: dict, functions_by_name: dict, file_folder=None, seed=1234) -> list: """ :config: A dictionary, keys are functions names, values are either true boolean either a dictionary of parameters. Parameters must be consistent with the corresponding fu...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ sum_numbers = int(sel...
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython Calcular el tamaño de la cadena "Esta es una cadena" sin usar la función len. TODO: add docstring and tests. """ def len_(ss, i=0): for _ in ss: i += 1 return i def len_alt(ss): return sum(1 for _ in ss) print(len_("Esta es una ca...
class Node: def __init__(self, data): self.data = data self.right = None self.left = None self.parent = None class BinarySearchTree: def __init__(self): self.root = None def search(t,x): if self.root !=None: if self.root.data == x:...
"""clean up an account after an experiment. Using command line python others/account_cleanup.py <DRIFTER_SCREEN_NAME> Delete: 1. friend list 2. follower list ## block and then unblock them 3. tweet 4. like """ from bot import source from bot.action import Action import sys class UserTimeLine(source.Sour...
#!python #from binarytree import BinarySearchTree, BinaryTreeNode from cursed_tree import CursedTree as BinarySearchTree import unittest # NOTE: some of the stuff got pulled out, didn't feel like fixing the left/rights class BinarySearchTreeTest(unittest.TestCase): def test_init(self): tree = BinarySear...
# Copyright 2019-present MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Generated by Django 2.2.14 on 2020-07-17 11:37 from django.db import migrations, models from olympia.constants.promoted import RECOMMENDED def add_promoted_approval_for_each_recommended(apps, schema_editor): Version = apps.get_model('versions', 'Version') PromotedApproval = apps.get_model('promoted', 'Pro...
from mapa import Map from path import choose_move, choose_random_move, dist_to, goToPosition from Node import astar def choose_key2(mapa, ways, my_pos, positions, wall, oneal, last_pos_wanted): # já sabe o caminho if positions != []: key = goToPosition(my_pos, positions[0]) positions.pop(0) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This is the primary fast image transformer definition trained to quickly transfer a style onto a photo Note: to make quantization work, need to add 1) QuantStub, DeQuantStub 2) res connections (add) -> nn.quantized.FloatFunctional """ import t...
#!/usr/bin/env python3 # coding: utf-8 import os import platform import sys from PyInstaller.utils.hooks import collect_submodules OS_NAME = platform.system() if OS_NAME == 'Windows': from PyInstaller.utils.win32.versioninfo import ( VarStruct, VarFileInfo, StringStruct, StringTable, StringFileInf...
from tool.runners.python import SubmissionPy class JulesdtSubmission(SubmissionPy): def run(self, s): """ :param s: input in string format :return: solution flag """ depth = 0 horizontal = 0 for line in s.split("\n"): move, amount = line.split() ...
import numpy as np import os import torch import torch.nn as nn import torch.nn.functional as F from glob import glob import math import copy import time from torch.autograd import Variable from src.utils.bleu import compute_bleu import pdb class Voc: def __init__(self): self.trimmed = False self....
import inspect import traceback import sys from aatest.events import EV_RESPONSE from aatest.events import EV_HTTP_RESPONSE __author__ = 'rolandh' INFORMATION = 0 OK = 1 WARNING = 2 ERROR = 3 CRITICAL = 4 INTERACTION = 5 INCOMPLETE = 6 NOT_APPLICABLE = 7 STATUSCODE = ["INFORMATION", "OK", "WARNING", "ERROR", "CRITIC...
from pygame import * import random width, height = size = (900, 500) window = display.set_mode(size) display.set_caption("Пинг-понг") background = transform.scale (image.load("background.jpg"), size) FPS = 60 clock = time.Clock() font.init() font2 = font.SysFont('Arial', 80) class GameSprite(sprite.Sp...
from path import Path from musicdl import musicdl from pydub import AudioSegment import random # config = {'logfilepath': 'musicdl.log', 'savedir': 'Downloads/songs/', 'search_size_per_source': 5, 'proxies': {}} # target_srcs = ['migu'] # client = musicdl.musicdl(config=config) # search_results = client.search('说好不哭', ...
import tarfile import time import urllib.request from subprocess import Popen, PIPE, STDOUT import pytest @pytest.fixture(scope='session') def elasticsearch_dir(tmpdir_factory): return tmpdir_factory.mktemp('elasticsearch') @pytest.fixture(scope="session") def elasticsearch_fixture(elasticsearch_dir): thet...
import sys, os import rasterio, geojson, json import numpy as np import pandas as pd import geopandas as gpd from affine import Affine from rasterio.warp import reproject, Resampling from scipy.ndimage import generic_filter from scipy import stats from rasterio import features from rasterio.features import rasterize ...
import os from .backend.backend_server import BackendServer def init_experiment_(token): backend = BackendServer(token) exp_info = backend.init_backend() print("Initialized experiment") print("\n") print("Details of your experiment ... ") for k, v in payload.items(): print(str(k) + " :...
############################################################################### # -*- coding: utf-8 -*- # Order: A tool to characterize the local structure of liquid water # by geometric order parameters # # Authors: Pu Du # # Released under the MIT License ####################################################...
import importlib import pkgutil from functools import lru_cache import typing as ty from types import ModuleType import msrc.appconfig_decl @lru_cache(maxsize=1) def get_installed_decl() -> ty.Mapping[str, ModuleType]: prefix = getattr(msrc.appconfig_decl, "__name__", '') + '.' path: ty.Iterable[str] = getatt...
import bitcoin # Generate a random private key valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N print "Private Key (hex) is: ", private_key pri...
from model_seq_cnn import * from tqdm import trange import torch import numpy as np import unittest class TestSeqCNN(unittest.TestCase): def test_shape_2d(self): for i in trange(20, desc='test_shape_2d'): in_C = np.random.randint(2, 4) in_H = np.random.randint(30, 100) ...
import csv , os def files2array(location): '''Returns all files on a dir in an array''' out = [] for file in os.listdir(location): if not file.startswith('.') and not file.startswith("~"): out.append(location+file) return out def array2csv(filename,arraytowrite): '''This functi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2022 Lorenzo Carbonell <a.k.a. atareao> # 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...
from django.conf import settings from django.db import models from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from i18n.fields import I18nCharField, I18nTextField class HotelRoom(models.Model): conference = models.ForeignKey( "conferences.Confere...
import random import string import pytest from nltk.metrics import distance from persephone.distance import min_edit_distance, min_edit_distance_align from persephone.distance import cluster_alignment_errors, word_error_rate from persephone.exceptions import EmptyReferenceException def rand_str(length: int, alphabet...
# Use "x" to convert the number into Hex format: txt = "The Hexadecimal version of {0} is {0:x}" print(txt.format(255))
#!/usr/bin/env python import pychemia from pychemia.visual.searcher import * from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt if len(sys.argv) != 3: print('Use:') print("Report_Metaheuristics.py dbname formula") exit(1) gen_size = 16 name = sys.argv[1] formula = sys.a...
import pytest from ke.asm import ( assemble, Literal, Multiple, Either, Concat, CharacterClass, DIGIT, Capture, Setting, Boundary, START_LINE, START_STRING, WORD_BOUNDARY, ) def test_literal(): assert assemble(Literal("abc")) == "abc" assert assemble(Literal...
import http.server, ssl, os, sys, codecs def getScriptPath(): return os.path.dirname(os.path.abspath(__file__))+'/' # generate self signed certificate using openssl command def generate_selfsigned_cert(): # absolute path of pyServer.py thisScriptPath=getScriptPath() try: cmd = 'openssl req -ne...
import pytest from simio_di import DependenciesContainer, SingletoneDependenciesContainer @pytest.mark.parametrize( "container_type, expected_is_same_instance", ((DependenciesContainer, False), (SingletoneDependenciesContainer, True),), ) def test_dependencies_containers(container_type, expected_is_same_inst...
from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from DAlphaFS.views import gotoHomePage, shared_dir from datetime import datetime import psycopg2 as pgad # Create your vie...
from collections import deque class Elevator(object): def __init__(self): self.cf = 0 # current floor self.dirc = "NULL" self.req = deque([]) self.reqSet = set([]) def in_cmg_req(self, floor): self.req.append(floor) self.reqSet.add(floor) def process(self)...
# -*- coding: utf-8 -*- ## # \file case4_scattering.py # \title Study of an acoustic impulse scattered by a circular obstacle. # \author Pierre Chobeau # \version 0.2 # \license BSD 3-Clause License # \inst UMRAE (Ifsttar Nantes), LAUM (Le Mans Université) # \date 2017, 07 Sep. ## import numpy as np ...
#!/usr/bin/python #coding: utf-8 import numpy as np import cv2 import math import sys import PIL from PIL import Image, ImageTk class CvImage: def __init__(self, path): self.load_img(path) print "loaded, inited ok..." def load_img(self, file_path): self.img = cv2.imread(file_path) ...
__author__ = 'disaster' import unittest import mock from fr.webcenter.backup.Config import Config def fakeSetting(path): settings = { 'rancher.host': "test", 'rancher.port': 1234 } indexes = { 'mysql': { 'image': 'fake/image', ...
from tests import run_async from tests.engine_tests.unit.repos.users import user_data from tests.engine_tests.unit.storage.mongo import TestRepositories from engine.models.user import User class TestUsers(TestRepositories): @run_async async def setUp(self) -> None: await TestRepositories.setUp(self...
from django.db import models from django.urls import reverse from jinja2 import Environment, TemplateSyntaxError from .abstracts import Template from .jinja2 import FILTER_DICT class Configuration(Template): def get_absolute_url(self): return reverse("peering:configuration_details", kwargs={"pk": self.pk...
import os import matplotlib.pyplot as plt import cv2 from matplotlib.widgets import PolygonSelector, TextBox import numpy as np import shutil import sys from create_json import to_json class metos_annotation_tool(): def __init__(self): # PROGRAMI ISTEDIGINIZ GIBI AYARLAMAK ICIN BURADAKI DEGE...
for numbers in range(5): print(numbers) for number in range(10): if number % 2 == 0: print(number) for number in [0,1,2,3,4]: print(number)
"""Unit tests for treadmill.sproc.alert_monitor. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import tempfile import unittest import click import click.testing import mock from treadmill import aler...
# Copyright 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
from pwn import * # to print out stack values using format string #e = ELF("./b0f") #for i in range(20): #io = e.process(level="error") #io.sendline("%%%d$lx" % i) ##io.recvline() #print("%d - %s" % (i, io.recvline().strip())) #io.close() r = remote('35.246.42.94', 31337) # canary found at li...
#!/usr/bin/python # -*- coding: utf-8 -*- #モードクラス サーボも込で #from servo import servo import time class mode(): def __init__(self,vehicle): self.SERVO=0 self.SERVO_MODE=0 self.ROCKING_WINGS=0 self.CAMERA=0 self.RCSAFETY=0 self.vehicle=vehicle #self.motor=servo()...
from pathlib import Path from typing import List from xdg import BaseDirectory from . import __version__ from .config import CheckerConfig from .runner import check_output, clean_temporary_files, run_source_file from .boj_parser import fetch_sample_io import argparse import colorama import difflib import os def mai...
import logging import os from pathlib import Path from unittest.mock import patch, MagicMock import pytest import yaml from _pytest.logging import LogCaptureFixture from _pytest.monkeypatch import MonkeyPatch from bs4 import BeautifulSoup from json_schema_for_humans.cli import get_schemas_to_render_from_cli_arguments...
# Based on works by: # TensorFlow Lite Tutorial Part 3: Speech Recognition on Raspberry Pi By ShawnHymel # https://www.digikey.com/en/maker/projects/tensorflow-lite-tutorial-part-3-speech-recognition-on-raspberry-pi/8a2dc7d8a9a947b4a953d37d3b271c71 # # Aaron Judy # https://theneverworks.com/ # https://followalon...
from .final_states import * from .repetition import Repetition from ..check import Check from .dead_position import DeadPosition from .finish_condition import FinishCondition from .fifty_moves import FiftyMoves from .available_moves import AvailableMoves
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\Jojo\PhD\ClimbingRobot\ClimbingLizardDLCAnalysis\start_new_analysis\lizards_direction_of_climbing_gui.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run a...
# yolo_hardcoded_recoder.py ''' This is a dumb script that fixes an even dumber problem. Let's say we've gone to the pain of collecting a bunch of images, and getting people to annotate them. What if these people entered their annotations in MANUALLY using hand typing, rather than selecting from a dropdown? Of course ...
import json from uuid import uuid4 import pytest from dateutil.relativedelta import relativedelta from dateutil.utils import today from django.core.files.uploadedfile import SimpleUploadedFile from freezegun import freeze_time from guardian.shortcuts import assign_perm from rest_framework import status from rest_frame...
from marshmallow import fields, Schema import pytest from sqlalchemy import Column, Integer, String from flask_resty import Api, GenericModelView from flask_resty.testing import assert_response # ----------------------------------------------------------------------------- @pytest.yield_fixture def models(db): ...
from setuptools import setup, find_packages setup(name="sandz", packages=find_packages('sandz'))
""" # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: Test the Bayesian GMM. fixme : some of these tests take too much time at the moment to be real unit tests Author : Bertrand Thirion, 2009 """ import numpy as np import numpy.random as nr from ..bgmm...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : Xiaobo Yang @Contact : hal_42@zju.edu.cn @Time : 2021/6/22 15:07 @File : voc_cooccur_analysis.py @Software: PyCharm @Desc : """ from typing import Optional import numpy as np from alchemy_cat.contrib.voc import VOCAug, VOC_CLASSES from alchemy_cat...
import thread from diesel.util.queue import Queue from diesel import fork_from_thread def put_stream_token(q, line): q.put(line) def consume_stream(stream, q): while True: line = stream.readline() fork_from_thread(put_stream_token, q, line) if line == '': break def create_...
x = int(input("Digite um número")) y = int(input("Digite outro número")) if(x>y): print("Seu primeiro número é maior que o segundo ") else: print("Seu segundo número é maior que o primeiro ")
import json import datetime import threading from base_plugin import * import base_plugin #=============================================Messaging=================================== def send_message(recipient, message, mtype='chat'): ''' Send a message to recipient. :param recipient: The To field of your messa...
import urllib from BeautifulSoup import * url = raw_input('Enter - ') html = urllib.urlopen(url).read() print html soup = BeautifulSoup(html) # Retrieve all of the anchor tags tags = soup('span') count = 0 summary = int() for tag in tags: # Look at the parts of a tag #print 'TAG:',tag #print 'URL:',tag.g...
from pyethapp.rpc_client import JSONRPCClient from pyethapp.jsonrpc import default_gasprice from ethereum.utils import sha3 from ethereum._solidity import compile_file from raiden.utils import get_contract_path from raiden.network.rpc.client import patch_send_transaction, patch_send_message def connect(host='127.0.0....
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
from multiprocessing import Process, Queue import random import time import sys from pyprocsync import ProcSync import redis """ This is a simple script created to test the sole sync precision of PyProcSync. The sync starts multiple processes on the same machine, since all threads running on the same machine the syst...
# -*- coding:utf-8 -*- from django.apps import AppConfig from . import strings class FBAuthConfig(AppConfig): name = 'fbauth' verbose_name = strings.APP_VERBOSE_NAME
# coding: utf-8 from __future__ import unicode_literals import logging from .chat import Chat logger = logging.getLogger(__name__) class User(Chat): """ 好友(:class:`Friend`)、群聊成员(:class:`Member`),和公众号(:class:`MP`) 的基础类 """ @property def remark_name(self): """ 备注名称 """ ...
import numpy as np from scipy.fft import fft, fftfreq, fftshift import matplotlib.pyplot as plt class FreqAnalyzer: def compute_fft_binning(self, meta): ''' Compute a list of frequencies to use as freq domain for FFT ''' sampling_rate = 1000 / meta['interval_between_samples'] # Hz x_fft =...
import anonymizer.anonymizer as anonymizer from anonymizer.anonymizer import Anonymizer from anonymizer.iio.mongodb_manager import MongoDB_Manager from anonymizer.iio.opendata_writer import OpenDataWriter from datetime import datetime from anonymizer.anonymizer_config import AnonymizerConfig import os from sys import a...
from torch.utils.data import Dataset import pymongo import json from collections import OrderedDict import logging logger = logging.getLogger(__name__) class MongoWrapper: """ Load single turn Q,A data """ def __init__(self, config_path, filter_func=None): """ 1. Mong...
from sphinxext.rediraffe import create_simple_redirects import pytest from sphinx.errors import ExtensionError def test_create_simple_redirects_empty(): assert create_simple_redirects({}) == {} def test_create_simple_redirects_no_cycle(): simple_redirects = redirects = { "a": "b", } assert c...
"""This module implements permutation-building functions.""" import numpy as np import sympy.combinatorics as cb from qfast import utils def swap_bit ( i, j, b ): """ Swaps bits i and j in b. Args: i (int): Bit index 1 j (int): Bit index 2 b (int): Input number Returns: ...
class Settings(object): OPENSUBTITLES_SERVER = 'http://api.opensubtitles.org/xml-rpc' USER_AGENT = 'uflix' LANGUAGE = 'eng'
from ducktape.services.service import Service from ducktape.services.background_thread import BackgroundThreadService class VerifiableClient(BackgroundThreadService): """ VerifiableClient wraps ClientCli for use in system testing. It allows propagate exceptions thrown in background threads. """ def...
# encoding=utf-8 import io from rich.columns import Columns from rich.console import Console COLUMN_DATA = [ "Ursus americanus", "American buffalo", "Bison bison", "American crow", "Corvus brachyrhynchos", "American marten", "Martes americana", "American racer", "Coluber constrict...
#!/usr/bin/env python3 """Algorithms for finding dense subgraphs. Edges must be symmetric (u, v) <==> (v, u). TODOS ----- - These are naive implementations. I believe a better implementation of Core number is possible. See https://arxiv.org/pdf/1103.5320 for inspiration (or just google distributed k-core). - Thes...
# Parsing CSV into Python without using any library import os directory = " " datafile = "beatles-diskography.csv" def parse_file(datafile): dat = [ ] with open(datafile, 'rb') as f: label = f.readline().split(",") c = 0 for line in f: if c == 10: break fields = line.split(",") datadict = { } ...
"""Model with the main Orange Widget. This module contains the world bank data widget, used for fetching data from world bank data API. """ import sys import time import math import signal import logging from PyQt4 import QtGui from Orange.data import table from Orange.widgets import widget from Orange.widgets impor...
from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html from app import app colors = { 'background': '#111111', 'text': '#7FDBFF' } layout = dcc.Markdown(""" ## Startup Prediction What causes a startup to succeed or fail? Startups, or new established...
''' This class calculates the total price of the drinks Author: Fasermaler March 2019 ''' class price_calculator: # initialize with the price list def __init__(self, price_list): self.set_price_list(price_list) self.drinks_list = [] self.total_price = 0.0 self.old_ids = None # subroutine to set the pri...
#!flask/bin/python from flask import request, render_template, Flask import db, os, spark, sys, json import requests app = Flask(__name__) from random import randint from ciscosparkapi import CiscoSparkAPI api = CiscoSparkAPI("ZDY0MThkMDktZDg2Yi00OGYxLWI3MDYtNzljNmEzMGE2ZjBjM2ViOTY1M2YtYTU2") auth_code = 'Bearer Z...
# Python solution for 'Bit Counting' codewars question. # Level: 6 kyu # Tags: Algorithms, Bits, and Binary. # Author: Jack Brokenshire # Date: 17/03/2020 import unittest def count_bits(n): """ Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary...
# インストールした discord.py を読み込む import discord from googletrans import Translator # 自分のBotのアクセストークンに置き換えてください TOKEN = 'NzAzOTgyNDQ2NzE4NDg0NTYw.XqWnvQ.HjoHlresLWBLU17T253pecyKh1o' # 接続に必要なオブジェクトを生成 client = discord.Client() # 起動時に動作する処理 @client.event async def on_ready(): # 起動したらターミナルにログイン通知が表示される ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Train and eval functions used in main.py """ import math import os import sys import datetime import json import random import time from typing import Iterable from ipdb import set_trace import torch import utils import util impo...
# # setup_new_proj.py - create a new PhysiCell Jupyter notebook project [for nanoHUB] by copying the contents of this # project and an existing PhysiCell project into the new project. # # Assumptions: # - the new project is a cloned, empty, public GitHub repo # - you have an existing PhysiCell...
n = int(input()) while n <= 1000: n *= n n += 1 print(n)
import ctypes import pytest c_lib = ctypes.CDLL('../solutions/0258-add-digits/add-digits.so') @pytest.mark.parametrize('num, ans', [(38, 2), (1, 1), (125, 8)]) def test_add_digits(num, ans): out = c_lib.addDigits(num) assert out == an...
#myPyGameWorld.py # from myPyGameBase import * class World: def __init__(self, host, sprites): worldMap = readFileMatrix('level0.txt') self.drawRect = [-20, 10, host.screenSize[0], host.screenSize[1]] self.tileSize = ( 40, 40 ) self.worldTiles = list() self....
""" This file reads Unihan_DictionaryLikeData.txt in the Unihan database, then generates a Python file that stores the data in a dict. The Unihan database can be downloaded from: http://www.unicode.org/Public/UCD/latest/ucd/Unihan.zip Unihan_DictionaryLikeData.txt can be seen after extracting the above zip file. """ ...
import os import shutil import zipfile, os.path import string from xml.dom import minidom, Node import CommonFunctions #filePath = 'Cramer.docx' #infilePath = 'testfile' #fileData = '' import TextParser class DocxParser(): def __init__(self, db, Stopwords=[], Stemmer=None, bloomFilter=None): ...
import pytest import numpy as np from plan_opt.demand import Demand from assets.demand.sample_demand import sample_demand from plan_opt.demand_small_samples import four_weeks_uprising as sample_demand def create_demand(): demand = Demand(period=len(sample_demand), data=sample_demand) return demand def test...
import json from investing_algorithm_framework import db, Portfolio from tests.resources import TestBase, TestOrderAndPositionsObjectsMixin, \ SYMBOL_A, SYMBOL_B, SYMBOL_A_PRICE, SYMBOL_B_PRICE from tests.resources.serialization_dicts import portfolio_serialization_dict class Test(TestBase, TestOrderAndPositions...
def SC_DFA(y): N = len(y) tau = int(np.floor(N/2)) y = y - np.mean(y) x = np.cumsum(y) taus = np.arange(5,tau+1) ntau = len(taus) F = np.zeros(ntau) for i in range(ntau): t = int(taus[i]) x_buff = x[:N - N % t] x_buff = x_buff.reshape((int(N / t),t)) ...
''' post a tweet from the queued file ''' from bot import settings, generator import json from TwitterAPI import TwitterAPI try: API = TwitterAPI(settings.TWITTER_API_KEY, settings.TWITTER_API_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACC...