text
string
size
int64
token_count
int64
# coding: utf-8 from wilde import WILDE_VECTOR from corey import COREY_VECTOR
78
32
# """run the models and calculate ELO ratings # 19.11.2020 - @yashbonde""" # from argparse import ArgumentParser # from chess_lm.model import ModelConfig # from chess_lm.game import Player # import torch # def expected(p1, p2): # return 1 / (1 - 10 ** ((p2 - p1) / 400)) # def elo(p, e, s, k=32): # return ...
1,343
517
""" Description: Requirements: pySerial, wxPython Phoenix glossary and of other descriptions: DMM - digital multimeter PSU - power supply SBC - single board computer INS - general instrument commands GEN - general sequence instructions """ import json import logging import serial import serialfunctions as sf imp...
5,092
1,664
# -*- coding: utf-8 -*- """\ Coroutine utilities ------------------- Some code snippets inspired by http://www.dabeaz.com/coroutines/ """ import re import functools def coroutine(func): """Prime a coroutine for send commands. Args: func (coroutine): A function that takes values via yield Retur...
1,723
498
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime from sqlalchemy.orm import relationship import datetime from database import Base class Org(Base): __tablename__ = "orgs" id = Column(Integer, primary_key=True, index=True) name = Column(String, unique=True, index=True) cr...
1,467
454
import math import pygame class Virus: """ Main Virus class """ def __init__(self, impact, virulence, detectability, industry, start_region, renderer=None): self.blocks = [] self.impact = impact self.virulence = virulence self.detectability = detectability # self.graph...
6,991
2,510
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ReduceInfo(object): def __init__(self): self._brand_name = None self._consume_amt = None self._consume_store_name = None self._payment_time = None self._pr...
3,507
1,138
'''Rafaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.''' n = int(input('Digite um número para ver sua tabuada: ')) print('-' * 12) for tabu in range(0, 11): print('{} x {:2} = {}'.format(n, tabu, n*tabu)) print('-' * 12)
290
124
#!/usr/bin/python3 import sys import time import array import numpy as np import pandas as pd import statistics import matplotlib.pyplot as plt import seaborn as sns # sns.set_theme(style="darkgrid") x_b = [1, 10, 100, 1000, 10000, 100000, 1000000] cyc_pi2 = [8379072, 8379072, 3675200, 372864, 37312, 3728, 368] cyc...
1,899
981
from flask_bcrypt import Bcrypt from flask_caching import Cache from flask_debugtoolbar import DebugToolbarExtension from flask_login import LoginManager from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy import logging bcrypt = Bcrypt() login_manager = LoginManager() db = SQLAlchemy() migrate =...
446
133
import time def f(): [ # Must be split over multiple lines to see the error. # https://github.com/benfred/py-spy/pull/208 time.sleep(1) for _ in range(1000) ] f()
207
77
from collections import OrderedDict from typing import Collection, List, Mapping, MutableSequence, Optional, Set, Tuple, Union import numpy as np from slicedimage import Tile, TileSet from starfish.core.imagestack.parser import TileCollectionData, TileData, TileKey from starfish.core.types import ArrayLike, Axes, Coo...
13,175
3,816
#!/usr/bin/python # This is a modified verison of turtlebot_teleop.py # to fullfill the needs of HyphaROS MiniCar use case # Copyright (c) 2018, HyphaROS Workshop # # The original license info are as below: # Copyright (c) 2011, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binar...
6,456
2,155
import math class Config: G = 9.8 EPISODES = 1000 # input dim window_width = 800 # pixels window_height = 800 # pixels window_z = 800 # pixels diagonal = 800 # this one is used to normalize dist_to_intruder tick = 30 scale = 30 # distance param mini...
895
388
# Apresentação print('Programa para identificar a que cargos eletivos') print('uma pessoa pode se candidatar com base em sua idade') print() # Entradas idade = int(input('Informe a sua idade: ')) # Processamento e saídas print('Esta pessoa pode se candidatar a estes cargos:') if (idade < 18): print...
726
277
# -*- coding: utf-8 -*- """ Microsoft-Windows-UAC-FileVirtualization GUID : c02afc2b-e24e-4449-ad76-bcc2c2575ead """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import S...
13,261
5,233
import requests from requests.auth import HTTPBasicAuth from elasticsearch import Elasticsearch import json import sys import datetime from operator import itemgetter import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) INCIDENT_INDEX = "incident" INCIDENT_TYPE = "incident" RESOURCE_INDE...
4,073
1,319
import pandas as pd import matplotlib.pyplot as plt import numpy as np import tensorflow from numpy import * from math import sqrt from pandas import * from datetime import datetime, timedelta from sklearn.preprocessing import LabelEncoder, MinMaxScaler from sklearn.preprocessing import OneHotEncoder from sklearn.met...
10,080
3,610
""" 0081. Search in Rotated Sorted Array II Medium Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. Example 1: Input...
1,323
431
import pathlib, typing, random, xml.etree.ElementTree as ET from itertools import chain from typing import List, Tuple from PIL import Image, ImageOps def split_background(background: Image.Image) -> list[Image.Image]: res = [] for x in range(0, background.width-416, 416): for y in range(0, background....
4,142
1,467
""" Processing data in win32 format. """ import glob import logging import math import os import subprocess import tempfile from fnmatch import fnmatch from multiprocessing import Pool, cpu_count from subprocess import DEVNULL, PIPE, Popen # Setup the logger FORMAT = "[%(asctime)s] %(levelname)s: %(message)s" logging....
15,708
5,005
import asyncio import aiopg dsn = 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1' @asyncio.coroutine def test_select(): pool = yield from aiopg.create_pool(dsn) with (yield from pool.cursor()) as cur: yield from cur.execute("SELECT 1") ret = yield from cur.fetchone() assert r...
426
160
"""Top-level package for sta-etl.""" __author__ = """Boris Bauermeister""" __email__ = 'Boris.Bauermeister@gmail' __version__ = '0.1.0' #from sta_etl import *
162
65
from collections import defaultdict import io import hashlib from datetime import date, datetime from pyexcel_xls import get_data as xls_get import pandas import magic from contextlib import closing import csv from django.db import connection from io import StringIO import uuid from psycopg2.errors import UniqueViolati...
14,399
4,216
from unittest import TestCase from siriuspy.pwrsupply.bsmp.constants import ConstPSBSMP from pydrs.bsmp import CommonPSBSMP, EntitiesPS, SerialInterface class TestSerialCommandsx0(TestCase): """Test BSMP consulting methods.""" def setUp(self): """Common setup for all tests.""" self._serial...
1,061
366
"""Converts synonyms into SMILES for the data from Gerber's paper.""" # data/hsd11b1_validation/get_smiles_cactus.py from io import BytesIO import pandas as pd import pycurl def getsmiles_cactus(name): """Converts synonyms into SMILES strings. A function to use the public cactus (National Institutes of Canc...
1,102
414
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : eval-referential.py # Author : Chi Han, Jiayuan Mao # Email : haanchi@gmail.com, maojiayuan@gmail.com # Date : 30.07.2019 # Last Modified Date: 16.10.2019 # Last Modified By : Chi Han, Jiayuan Mao # # This file is...
4,541
1,677
import pytest @pytest.fixture(scope="module") def client(looper, txnPoolNodeSet, client1, client1Connected): return client1Connected
139
47
#!/usr/bin/env python # # Copyright (c) 2018 10X Genomics, Inc. All rights reserved. # # Utils for feature-barcoding technology import numpy as np import os import json import tenkit.safe_json as tk_safe_json def check_if_none_or_empty(matrix): if matrix is None or matrix.get_shape()[0] == 0 or matrix.get_shape(...
1,316
475
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """SHERIFS Seismic Hazard and Earthquake Rates In Fault Systems Version 1.0 @author: thomas """ import numpy as np import os from scipy.stats import chisquare from scipy.stats import multivariate_normal import matplotlib.pyplot as plt def sampling_analysis(Run_name...
53,492
18,307
import json import rimu from rimu import options def unexpectedError(_, message): raise Exception(f'unexpected callback: {message}') def test_render(): assert rimu.render('Hello World!') == '<p>Hello World!</p>' def test_jsonTests(): with open('./tests/rimu-tests.json') as f: data = json.load...
1,481
384
#!/usr/bin/env python import urllib2 package_list = ['wget.tcz', 'python-pip.tcz', 'unzip.tcz', 'sudo.tcz', 'mksquashfs.tcz', 'gawk.tcz', 'genisoimage.tcz', 'qemu.tcz', 'pidgin.tcz'] serv_url = "http://distro.ibiblio.org/tinycorelinux/2.x/tcz/" suffix = ".dep" UP_SET = set(package_list)...
1,786
606
# Copyright (c) 2014-2019, Manfred Moitzi # License: MIT License import pytest from ezdxf.sections.acdsdata import AcDsDataSection from ezdxf import DXFKeyError from ezdxf.lldxf.tags import internal_tag_compiler, group_tags from ezdxf.lldxf.tagwriter import TagCollector, basic_tags_from_text @pytest.fixture def sect...
4,685
3,177
# -*- coding: utf-8 -*- """ app_test.py Tests the tkit.App class. Author: Garin Wally; Oct 2017 License: MIT """ import tkit if __name__ == "__main__": # Create app test_app = tkit.App("Test App", 250, 100) # Create and customize menubar menubar = tkit.Menubar() menubar.add_menu("File") #tes...
772
314
""" Database models """ from typing import Tuple import attr import sqlalchemy as sa from .settings import DATCORE_STR, SIMCORE_S3_ID, SIMCORE_S3_STR #FIXME: W0611:Unused UUID imported from sqlalchemy.dialects.postgresql #from sqlalchemy.dialects.postgresql import UUID #FIXME: R0902: Too many instance attributes (...
3,652
1,260
import pandas as pd from sklearn.pipeline import Pipeline from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import confusion_matrix, roc_auc_score from category_encoders import MEstimateEncoder import numpy as np from collections import defaultdict import os from sklearn.metrics import roc_au...
13,715
4,558
# Solution of; # Project Euler Problem 527: Randomized Binary Search # https://projecteuler.net/problem=527 # # A secret integer t is selected at random within the range 1 ≤ t ≤ n. The # goal is to guess the value of t by making repeated guesses, via integer g. # After a guess is made, there are three possible outco...
1,929
649
''' No 2. Buatlah fungsi tanpa pengembalian nilai, yaitu fungsi segitigabintang. Misal, jika dipanggil dg segitigabintang(4), keluarannya : * ** *** **** ''' def segitigabintang(baris): for i in range(baris): print('*' * (i+1))
242
110
import asyncio from aiohttp import web from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor from multiprocessing import Queue, Process import os from time import sleep async def handle(request): index = open("index.html", 'rb') content = index.read() return web.Response(body=content, co...
2,402
742
# -*- coding: utf-8 -*- from __future__ import unicode_literals import ujson as json import datetime from elex.api import maps from elex.api import utils from collections import OrderedDict from dateutil import parser as dateutil_parser PCT_PRECISION = 6 class APElection(utils.UnicodeMixin): """ Base class fo...
41,018
11,762
# coding: utf-8 """Preview dataset content without extracting.""" import os import itertools from pathlib import Path from zipfile import ZipFile from concurrent.futures import ThreadPoolExecutor as Pool import hashlib cwd = Path(__file__).parent / "dataset" ls = lambda pattern: sorted(cwd.glob(pattern)) def all_fi...
1,308
434
import pytest from fixtures import world from wecs.core import UID from wecs.core import NoSuchUID from wecs.core import Component @Component() class Reference: uid: UID def test_user_defined_names(world): entity = world.create_entity(name="foo") assert entity._uid.name == "foo" def test_automatic_n...
1,472
487
from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager from pages.home_page import HomePage from pages.profile_page import ProfilePage from pages.login_page import LoginPage from pages.registration_page import RegistrationPage from p...
5,268
1,618
api_output_for_empty_months = """"Usage Data Extract", "", "AccountOwnerId","Account Name","ServiceAdministratorId","SubscriptionId","SubscriptionGuid","Subscription Name","Date","Month","Day","Year","Product","Meter ID","Meter Category","Meter Sub-Category","Meter Region","Meter Name","Consumed Quantity","Reso...
2,818
1,244
#!/usr/bin/python3 m1 = int(input("Enter no. of rows : \t")) n1 = int(input("Enter no. of columns : \t")) a = [] print("Enter Matrix 1:\n") for i in range(n1): row = list(map(int, input().split())) a.append(row) print(a) m2 = int(n1) print("\n Your Matrix 2 must have",n1,"rows and",m1,"columns \n") n2 ...
644
282
# Copyright (c) 2021, ifitwala and contributors # For license information, please see license.txt import frappe from frappe.model.document import Document from frappe import _ class TrainingFeedback(Document): def validate(self): training_event = frappe.get_doc("Training Event", self.training_event) if training_...
596
198
import numpy as np import numpy.linalg as LA from .solve_R1 import problem_R1, Classo_R1, pathlasso_R1 from .solve_R2 import problem_R2, Classo_R2, pathlasso_R2 from .solve_R3 import problem_R3, Classo_R3, pathlasso_R3 from .solve_R4 import problem_R4, Classo_R4, pathlasso_R4 from .path_alg import solve_path, pathalgo...
9,891
3,592
# Copyright (c) 2019 - now, Eggroll Authors. All Rights Reserved. # # 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 ...
1,547
475
# ============================================================================= # TexGen: Geometric textile modeller. # Copyright (C) 2015 Louise Brown # 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 Found...
2,460
983
from nltk.tokenize import word_tokenize from torch.autograd import Variable import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import torch import torch.optim as optim # Set parameters context_size = 3 embed_size = 2 xmax = 2 alpha = 0.75 batch_size = 20 l_rate = 0.001 num_epoch...
3,201
1,429
''' Created on Jul 5, 2021 @author: mballance ''' from tblink_rpc_testcase import TblinkRpcTestcase import sys from tblink_rpc_core.json.json_transport import JsonTransport import asyncio from tblink_rpc_core.param_val_map import ParamValMap from tblink_rpc_core.endpoint import Endpoint class TblinkRpcSmoke(TblinkRpc...
971
293
from django.contrib.auth.models import User from django.core.management.base import BaseCommand class Command(BaseCommand): """ Command for creating default superuser """ def handle(self, *args, **options): if not User.objects.filter(username="admin").exists(): User.objects.create...
445
125
from __future__ import print_function, division import torch import matplotlib.pyplot as plt import argparse, os import numpy as np from torch.utils.data import DataLoader from torchvision import transforms from models.CDCNs_u import Conv2d_cd, CDCN_u from Load_OULUNPUcrop_train import Spoofing_train_g, Sep...
13,856
4,940
from tensorpy import image_base classifications = image_base.classify_folder_images('./images') print("*** Displaying Image Classification Results as a list: ***") for classification in classifications: print(classification)
230
57
import argparse import torch from torch.utils.data import DataLoader import sys, os sys.path.insert(0, os.path.join( os.path.dirname(os.path.realpath(__file__)), "../../")) from deep_audio_features.dataloading.dataloading import FeatureExtractorDataset from deep_audio_features.models.cnn import load_cnn from deep_a...
4,201
1,157
# # This is the Robotics Language compiler # # ErrorHandling.py: Implements Error Handling functions # # Created on: June 22, 2017 # Author: Gabriel A. D. Lopes # Licence: Apache 2.0 # Copyright: 2014-2017 Robot Care Systems BV, The Hague, The Netherlands. All rights reserved. # # Licensed under t...
3,113
937
# !/usr/local/bin/python3.4.2 # ----Copyright (c) 2016 Carnegie Hall | The MIT License (MIT)---- # ----For the full license terms, please visit https://github.com/CarnegieHall/quality-control/blob/master/LICENSE---- # run script with 5 arguments: # argument 0 is the script name # argument 1 is the path to the Isilon HD...
5,765
1,871
# -*- coding: utf8 -*- from urllib.request import Request, urlopen import logging import parsing __author__ = 'carlos' class Downloader(object): def __init__(self, url): self.url = url def read(self): request = Request( self.url ) request.add_header('Accept-encoding', 't...
1,020
314
import re import traceback from textwrap import dedent def camel_to_snake(value): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', value) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def snake_to_camel(value): camel = '' words = value.split('_') for w in words: camel += w.title() ...
1,403
487
from .identity import *
24
8
from setuptools import setup from eaclogger import __version__ as plugin_version setup( name="whipper-plugin-eaclogger", version=plugin_version, description="A plugin for whipper which provides EAC style log reports", author="JoeLametta, supermanvelo", maintainer="JoeLametta", license="ISC Lice...
558
184
from PrimeSearcher import PrimeSearcher ### ps = PrimeSearcher("./images/euler.jpg") ps.rescale(60*60, fit_to_original=True) ps.search(max_iterations=1000, noise_count=1, break_on_find=False)
201
84
import sys import os import random klasorAdi = os.path.dirname(sys.argv[0]) dosyaIsmi = klasorAdi + "/test.txt" soruSayisi = 40 ogrenciSayisi = 60 d = {} dogruSayisi = {} yalisSayisi = {} bosSayisi = {} puan = {} def sinavHazirla(): for j in range(1, soruSayisi + 1): r1 = random.randint(1, 5) d[0, j] = chr(...
2,432
1,209
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from heufybot.utils.timeutils import now, timestamp from zope.interface import implements from datetime import datetime class TimeCommand(BotCommand): implements(IPlugin, IBo...
5,639
1,502
import pandas as pd import click import collections def kmer_suffix(kmer): return kmer[1:] def kmer_prefix(kmer): return kmer[:-1] def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def build_graph(kmers): graph = collection...
2,132
779
#!/usr/bin/env python3 import sys import re import time import datetime import os for module in sorted(sys.modules): print("%-20s : %s" % (module, sys.modules[module])) print('USER : ', os.environ['USER']) print('PWD : ', os.environ['PWD']) print('PYTHONPATH: ', os.environ.get('PYTHONPATH')) print(sy...
328
116
# SPDX-FileCopyrightText: 2020 Hlib Babii <hlibbabii@gmail.com> # # SPDX-License-Identifier: Apache-2.0 from unittest import mock import pytest from codeprep.bpepkg.bpe_config import BpeConfig, BpeParam, BpeConfigNotSupported from codeprep.pipeline.bpelearner import run @mock.patch('codeprep.pipeline.bpelearner.Da...
997
382
#!/usr/bin/env python3 import torrent_parser as tp import asyncio import contextlib import pathlib import argparse import pprint import hashlib import concurrent.futures import os.path import logging import tqdm class TorrentChecker(object): def __init__(self, datadir=pathlib.Path('.'), data_file_globs=["**"], ...
6,321
2,095
# Functions to segment chromosomes from . import chromosome from . import cell
78
22
"""Scrape episodes from online sources.""" from datetime import datetime import re from typing import Dict, Iterable, Match, Optional, Tuple import requests from .episode import Episode from .settings \ import WUNSCHLISTE_IMPLIED_TIMEZONE, \ WUNSCHLISTE_QUERY_PARAMETERS, WUNSCHLISTE_URL WUNSCHLISTE_SELECT_E...
3,127
1,072
from locust import HttpUser, task, between from locust.contrib.fasthttp import FastHttpUser class TestUser(FastHttpUser): @task def viewPage(self): self.client.get('/insamlingar/varldshjalte') self.client.get('/webpack-runtime-72a2735cd8a1a24911f7.js') self.client.get('/framework-...
1,824
788
# -*- coding: UTF-8 -*- logger.info("Loading 1 objects to table invoicing_plan...") # fields: id, user, today, journal, max_date, partner, course loader.save(create_invoicing_plan(1,6,date(2015,3,1),1,None,None,None)) loader.flush_deferred_objects()
251
98
from time import time from json import dumps, loads from redis import StrictRedis, ConnectionPool, WatchError from PyYADL.distributed_lock import AbstractDistributedLock class RedisLock(AbstractDistributedLock): def __init__(self, name, prefix=None, ttl=-1, existing_connection_pool=None, redis_host='localhost', ...
4,943
1,387
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
68,660
25,721
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from darknet_ros_msgs/CheckForObjectsAction.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import darknet_ros_msgs.msg import sensor_msgs.msg import genpy import actionli...
37,327
12,783
import os _rootdir = os.getcwd() def find_rootdir(filenames = ('__main__.py', 'main.ipynb')): path = os.getcwd() while os.path.isdir(path): ls = os.listdir(path) if any([f in ls for f in filenames]): return os.path.abspath(path) else: path += '/..' # nothi...
612
220
# Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. # # For example, given the following Node class: class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left ...
1,292
474
import math import random import numpy as np # 先生成一个随机的信源 def random_sources(): random_sources = random.randint(0, 16) print('这个随机数是', random_sources) return hanming(random_sources) # return bin(int(random_sources)...
2,051
1,034
import json from unittest import TestCase from unittest.mock import patch from bug_killer_api_interface.schemas.entities.bug import BugResolution from bug_killer_api_interface.schemas.request.bug import CreateBugPayload, UpdateBugPayload from bug_killer_api_interface.schemas.request.project import CreateProjectPayload...
17,778
5,597
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jul 21 13:15:22 2017 @author: fernando """ import matplotlib import matplotlib.pyplot as plt import pandas as pd matplotlib.style.use('ggplot') # Look Pretty # If the above line throws an error, use plt.style.use('ggplot') instead df = pd.read_csv("co...
566
220
from django.db import models from users.models import User class Assignment(models.Model): title = models.CharField(max_length=50) teacher = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class GradedAssignment(models.Model): student = models.ForeignK...
1,488
388
import numpy as np import scipy.sparse from src.main.functions.interface_function import InterfaceFunction class PoissonRegression(InterfaceFunction): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # В формулах в задании и на вики почему-то максимизирует loss # Для...
1,543
558
from fastapi import FastAPI from . import api app = FastAPI(debug=True) app.include_router(api.router)
105
36
import time import math from . import settings class TimeKeeper: """ Handles timekeeping in timecodes """ def __init__(self, minpertimecode=None, runtime=0, update=True, latestcode=None): self._minPerTimeCode = minpertimecode or settings.Global.minPerTimeCode self.late...
1,769
553
#!/usr/bin/env python """ Perform compressed sensing analysis on a dax file using the homotopy approach. Return the results in hres image format and as a list of object locations. Hazen 09/12 """ import numpy import storm_analysis.sa_library.datareader as datareader import storm_analysis.sa_library.parameters as par...
5,223
1,703
""" Methods for handling DB creation and CRUD operations in Sqlite3. """ # Standard library imports import logging import sqlite3 # Local application imports from ism.exceptions.exceptions import UnrecognisedParameterisationCharacter from ism.interfaces.dao_interface import DAOInterface class Sqlite3DAO(DAOInterfac...
3,620
980
import os import json import argparse from gensim import corpora from gensim.utils import simple_preprocess from gensim.models import LdaModel # reaad json file def parseJson(json_file): ''' parsing the JSON file from the pre-processing pipeline :param json_file :return: dictionary with docID as key ...
7,373
2,322
# Author: btjanaka (Bryon Tjanaka) # Problem: (UVa) 247 import sys from collections import defaultdict def kosaraju(g, g_rev): order = [] visited = set() def visit(u): visited.add(u) for v in g[u]: if v not in visited: visit(v) order.append(u) for...
1,267
432
import math import numpy as np from sklearn.linear_model import LinearRegression def get_heading_angle(traj: np.ndarray): """ get the heading angle traj: [N,2] N>=6 """ # length == 6 # sort position _traj = traj.copy() traj = traj.copy() traj = traj[traj[:, 0].argsort()] ...
1,970
809
# Generated by Django 3.0.4 on 2020-05-17 22:34 from django.db import migrations, models from django.utils import timezone def migrate_job_completion(apps, schema_editor): Job = apps.get_model("jobserver", "Job") JobHistory = apps.get_model("jobserver", "JobHistory") # Iterate over all jobs for job ...
1,637
471
#!/usr/bin/env python3 # Copyright 2018 Comcast Cable Communications Management, LLC # 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 re...
8,603
3,314
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Christian Kotte <christian.kotte@gmx.de> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'met...
8,810
2,392
#!/usr/bin/env python """This script simply calls drizzlepac/hlautils/hla_flag_filter.py for test purposes""" import json import glob import os import pdb import sys from astropy.table import Table import drizzlepac from drizzlepac.hlautils import config_utils from drizzlepac.hlautils import poller_utils def run_hla...
12,483
5,287
import pyautogui import time time.sleep(3) print(pyautogui.position())
71
27
from tools.configurations import ConcatenatedBrainLSTMCfg from brains.concatenated_brains import ConcatenatedLSTM from brains.lstm import LSTMNumPy from brains.ffnn import FeedForwardNumPy import numpy as np from gym.spaces import Box class TestConcatenatedLSTM: def test_concatenated_lstm_output(self, concat_ls...
4,182
1,335
import json from pathlib import Path import pytest @pytest.fixture(scope="module") def test_path_root(tmp_path_factory): file_test_root = tmp_path_factory.mktemp("file_util") return file_test_root @pytest.fixture(scope="module") def json_data(): data = {"key1": "value1", "key2": "value2", "key3": "valu...
1,432
539
# ------------------Bombermans Team---------------------------------# # Author : B3mB4m # Concat : b3mb4m@protonmail.com # Project : https://github.com/b3mb4m/Shellsploit # LICENSE : https://github.com/b3mb4m/Shellsploit/blob/master/LICENSE # ------------------------------------------------------------------# from ...
3,118
799
import os from optparse import make_option from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): args = 'url' help = 'Download VCR tapes from remote server' option_list = BaseCommand.option_list + ( make_option( '-u', '--url', dest...
732
206
# @copyright@ # Copyright (c) 2006 - 2018 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ import stack.commands class Plugin(stack.commands.Plugin): def provides(self): return 'bootaction' def run(self, args): if args and 'b...
958
391
# Generated by Django 2.0.3 on 2018-04-19 07:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('faq', '0004_auto_20180322_1330'), ] operations = [ migrations.AlterModelOptions( name='faq', options={'ordering': ('subject_...
608
218