text
string
size
int64
token_count
int64
import unittest import pickle from array import array import complete_tdf from floodberry.floodberry_ed25519 import GE25519 from tdf_strucs import TDFMatrix, TDFError from complete_tdf import CTDFCodec as Codec, CTDFCipherText as CipherText from utils import int_lst_to_bitarr TEST_DIR = "legacy/tests/" PACK_TEST_KEY...
1,639
688
import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wherethefuck.settings') # create and run celery workers. app = Celery(broker=settings.CELERY_BROKER_URL) app.config_from_object('djan...
431
150
from MLSR.data import DataSet from MLSR.plot import * x = DataSet('data/rand_select_400_avg.csv') x.generate_feature() y = DataSet('data/not_selected_avg.csv') y.generate_feature() z = DataSet.static_merge(x, y) #plot_tsne(z, 'log/tsne.png') z = z.convert_to_ssl() z0, z1 = z.split_by_weak_label() plot_tsne_ssl(z0, 'lo...
395
190
import numpy as np import scipy.io as sio import os, glob, sys import h5py_cache as h5c sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal') sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal/source') from batch_gen_hdf5 import BatchGeneratorWithSceneMeshMatfile import torch ''' In t...
7,652
2,989
from django.db import models class Train(models.Model): no = models.CharField(max_length=20) destination = models.CharField(max_length=50) source = models.CharField(max_length=50) days = models.CharField(max_length=10) name = models.CharField(max_length=50) arrival = models.CharField(max_length...
421
136
# -*- coding: utf-8 -*- from fontbro import Font from tests import AbstractTestCase class NamesTestCase(AbstractTestCase): """ Test case for the methods related to the font names. """ def test_get_name_by_id(self): font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf") ...
3,324
1,125
from amara.bindery import html from amara.lib import U import urllib import urlparse import time ''' This script extract data from html pages and write the data into a .json file ready to create the mediawiki / wikieducator pages ''' BASE = 'http://academics.smcvt.edu/dmccabe/teaching/Community/' def parse_notes_...
3,901
1,318
from scraper import * s = Scraper(start=138996, end=140777, max_iter=30, scraper_instance=78) s.scrape_letterboxd()
117
59
from django.core.exceptions import PermissionDenied from django.test import TestCase from backend.models import UserModel, AwsEnvironmentModel from unittest import mock # デコレーターをmock化 with mock.patch('backend.models.OperationLogModel.operation_log', lambda executor_index=None, target_method=None, target_arg_index_...
20,826
7,943
def check(b,ind,c): i=ind while i<len(b): if b[i]==c: return i i+=1 return -1 a=raw_input() b=raw_input() i=0 index=0 co=0 if a[0]==b[0]: co+=1 i+=1 while i<len(a): index1=check(b,index+1,a[i]) print a[i],index1 if index1!=-1: index=index1 co+=1 ...
371
166
import os from pathlib import Path from shutil import rmtree # change your parent dir accordingly try: directory = "TempDir" parent_dir = "E:/GitHub/1) Git_Tutorials_Repo_Projects/core-python/Core_Python/" td1, td2 = "TempA", "TempA" path = os.path.join(parent_dir, directory) temp_mul_dirs = os.path...
1,273
453
from __future__ import absolute_import, division, print_function, unicode_literals from echomesh.color import WheelColor from echomesh.util.TestCase import TestCase EXPECTED = [ [ 0., 1., 0.], [ 0.3, 0.7, 0. ], [ 0.6, 0.4, 0. ], [ 0.9, 0.1, 0. ], [ 0. , 0.2, 0.8], [ 0. , 0.5, 0.5], [ 0. , 0...
587
303
from modules.CommandData import CommandData class IPlugin(object): def __init__(self): """create the plugin interface """ self.pluginName = "" self.pluginAutor = "" self.pluginVersion = 0 self.pluginDescription = "" self.pluginCommand = "" self.comman...
1,000
255
# -*- coding: utf-8 -*- #Used to generate positive building samples from google satellite images #based on OSM building polygons in geojson format # #Note 1: Accuracy of OSM building polygons may vary #Note 2: Requires downloaded google satellite images(tiles) to # have the following file name structure # ...
4,890
1,731
from ctypes import cdll,c_int,c_double,POINTER _lib = cdll.LoadLibrary('./demo/bin/libmultifuns.dll') # double dprod(double *x, int n) def dprod(x): _lib.dprod.argtypes = [POINTER(c_double), c_int] _lib.dprod.restype = c_double n = len(x) # convert a Python list into a C array by using ctypes a...
779
326
from nivo_api.core.db.connection import metadata, create_database_connections from sqlalchemy.engine import Engine from sqlalchemy.exc import ProgrammingError def is_postgis_installed(engine: Engine) -> bool: try: engine.execute("SELECT postgis_version()") return True except ProgrammingError: ...
843
277
""" @Author:lichunhui @Time: @Description: 百度百科爬虫程序入口 """ from scrapy import cmdline # cmdline.execute("scrapy crawl baidu_spider".split()) # cmdline.execute("scrapy crawl baike_spider".split()) # cmdline.execute("scrapy crawl wiki_zh_spider".split()) # cmdline.execute("scrapy crawl wiki_en_spider".split()) cmdline...
357
147
import PySimpleGUI as sg layout = [ [sg.Text("Wie heißt Du?")], [sg.Input(key = "-INPUT-")], [sg.Text(size = (40, 1), key = "-OUTPUT-")], [sg.Button("Okay"), sg.Button("Quit")] ] window = sg.Window("Hallo PySimpleGUI", layout) keep_going = True while keep_going: event, val...
515
198
import numpy as np import pathlib from torch.utils.data import Dataset, DataLoader import dgl import torch from dgl.data.utils import load_graphs import json from datasets import util from tqdm import tqdm class FusionGalleryDataset(Dataset): @staticmethod def num_classes(): return 8 def __init__...
3,247
965
# Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # from mmdet.models.builder import HEADS, build_loss from mmdet.models.losses import smooth_l1_loss from mmdet.models.dense_heads.ssd_head import SSDHead @HEADS.register_module() class CustomSSDHead(SSDHead): def __init__( self,...
3,690
1,167
""" Copyright 2020 daduz11 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 writin...
2,918
900
def find_from(string, subs, start = None, end = None): """ Returns a tuple of the lowest index where a substring in the iterable "subs" was found, and the substring. If multiple substrings are found, it will return the first one. If nothing is found, it will return (-1, None) """ string = strin...
628
188
# todos # - [ ] all dates and date deltas are in time, not integers from loguru import logger from typing import Dict import sys import datetime from datetime import timedelta import numpy as np from ta_scanner.data.data import load_and_cache, db_data_fetch_between, aggregate_bars from ta_scanner.data.ib import IbDat...
4,844
1,787
import tkinter as tk import os print(tk) print(dir(tk)) print(tk.TkVersion) print(os.getcwd()) '''To initialize tkinter, we have to create a Tk root widget, which is a window with a title bar and other decoration provided by the window manager. The root widget has to be created before any other widgets and there can...
841
241
from django.shortcuts import render,redirect,get_object_or_404 from remiljscrumy.models import ScrumyGoals,GoalStatus,ScrumyHistory,User from django.http import HttpResponse,Http404,HttpResponseRedirect from .forms import SignupForm,CreateGoalForm,MoveGoalForm,DevMoveGoalForm,AdminChangeGoalForm,QAChangeGoalForm,QAC...
14,700
4,576
''' Cilia classes are used to compute fixed points faster. - Assume symmetry like in an m-twist (make a plot to see it) - Assume that symmetries is not broken in time -> define classes of symmetry and interactions between them. Done: - Create a ring of cilia. - Define symmetry classes - Use classes to solve ODE - Map...
3,088
1,186
""" SCL <scott@rerobots.net> 2018 """ import json import os import tempfile import time class PCA9685: def __init__(self): self._fd, self._pathname = tempfile.mkstemp(prefix='kuaikai_sim_', dir='/tmp', text=True) self._fp = os.fdopen(self._fd, 'wt') def __del__(self): self._fp.close(...
749
292
import numpy as np import matplotlib.pyplot as plt import scipy.stats def set_ax_range(): LEFT_AX.set_xlim(X_RANGE) LEFT_AX.set_ylim(Y_RANGE) def range_plot(ax, f, x_range, y_range): bins = 50 xi, yi = np.mgrid[ min(x_range):max(x_range):bins*1j, min(y_range):max(y_range):bins*1j ...
2,851
1,250
import numpy as np import logging import matplotlib.pyplot as plt from sklearn.cluster import KMeans from ..results import Results logger = logging.getLogger(__name__) class KmeansResults(Results): """ Contains results and metadata of a k-means refinement calculation """ def reset(self): sel...
9,255
2,985
import sys import os import configparser import argparse import glob def parse_args(): AP = argparse.ArgumentParser("Convert BAF into LOH") AP.add_argument('-indir',help='result dir',dest='indir') AP.add_argument('-name',help='sample name',dest='name') AP.add_argument('-bam',help='bam',dest='bam') ...
5,175
2,393
# All rights reserved by forest fairy. # You cannot modify or share anything without sacrifice. # If you don't agree, keep calm and don't look at code bellow! __author__ = "VirtualV <https://github.com/virtualvfix>" __date__ = "$Apr 13, 2014 8:47:25 PM$" import re from config import CONFIG from tests.exceptions impor...
3,221
1,034
import sys import unittest import os import tempfile import shutil import contextlib import json import subprocess import PIL import templatelayer.testing_common _APP_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) _SCRIPT_PATH = os.path.join(_APP_PATH, 'templatelayer', 'resources', 'scri...
3,879
1,111
import argparse import torch import torch.nn as nn from gpt2.modeling import Transformer from gpt2.data import Dataset, Vocab, TokenizedCorpus from gpt2.evaluation import EvaluationSpec, EvaluateConfig, Evaluator from typing import Dict class GPT2EvaluationSpec(EvaluationSpec): def __init__(self, eval_corpus: str...
3,993
1,259
from typing import Dict from src.alerter.alert_data.alert_data import AlertData class ChainlinkContractAlertData(AlertData): """ ChainlinkContractAlertData will store extra information needed for the data store such as the contract_proxy_address. """ def __init__(self): super().__init__(...
571
166
from processutils.textfilter import Unpack from utils.simplelog import Logger import argparse parser = argparse.ArgumentParser(description="my_unpack") parser.add_argument('-f', "--file_prefix", required=True) parser.add_argument('-sep', "--separator", required=True) # args = parser.parse_args([ # "-f", "../test...
1,332
468
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import os import json import urllib.parse import boto3 import decimal from decimal import Decimal from datetime import datetime from chalice import Chalice from chalice import IAMAuthorizer from chalice imp...
10,173
2,835
from xml.etree import ElementTree as Etree from model import * from astro_unit import * from io import StringIO import logging class FieldMeta: """ OEC field metadata. """ def __init__(self, datatype: str, unit: str = None): self.type = datatype self.unit = unit # Maps field name to ...
9,559
2,634
"""Validate AnVIL workspace(s).""" import os from google.cloud.storage import Client from google.cloud.storage.blob import Blob from collections import defaultdict import ipywidgets as widgets from ipywidgets import interact from IPython.display import display import pandas as pd import firecloud.api as FAPI from typ...
9,072
2,464
''' Intermediate C#1, stigid PROBLEM: Given a number less than 10^50 and length n, find the sum of all the n -digit numbers (starting on the left) that are formed such that, after the first n -digit number is formed all others are formed by deleting the leading digit and taking the next n -digits. '''...
1,513
849
# 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 writing, software # distributed under t...
1,857
589
# -*- coding: utf-8 -*- """Utility file for the HASYv2 dataset. See https://arxiv.org/abs/1701.08380 for details. """ from __future__ import absolute_import from keras.utils.data_utils import get_file from keras import backend as K import numpy as np import scipy.ndimage import os import tarfile import shutil import...
5,760
1,985
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def QuiesceDatastoreIOForHAFailed(vim, *args, **kwargs): '''A QuiesceDatastoreIOForHAFail...
1,201
363
""" Based on Extended kalman filter (EKF) localization sample in PythonRobotics by Atsushi Sakai (@Atsushi_twi) """ import math import matplotlib.pyplot as plt import numpy as np # Simulation parameter INPUT_NOISE = np.diag([0.1, np.deg2rad(30.0)]) ** 2 GPS_NOISE = np.diag([0.1, 0.1]) ** 2 # Covariance for EKF ...
8,071
3,347
from unittest import TestCase, main as unittest_main from q2_winnowing.plugin_setup import plugin as winnowing_plugin class PluginSetupTests( TestCase ): package = 'q2_winnowing.tests' def test_plugin_setup(self): self.assertEqual( winnowing_plugin.name, "winnowing") if __name__ == '__main__': ...
337
121
l = [0, "-", "+"] def backIter(): x = [0] # candidate solution while len(x) > 0: choosed = False while (not choosed) and l.index(x[-1]) < len(l) - 1: x[-1] = l[l.index(x[-1]) + 1] # increase the last component choosed = consistent(x) if choosed: ...
974
377
from datetime import datetime from enum import Enum, auto from random import randint from time import sleep from typing import Optional, Tuple class GameItem(Enum): DEATH = auto() WOODEN_SWORD = auto() SIMPLE_BOW = auto() VIOLIN = auto() ORDINARY_SWORD = auto() STRAHD_SLAYER_SWORD...
31,674
9,260
from django.db import models class Vestibular(models.TextChoices): ENEM = 'ENEM' UNICAMP = 'Unicamp' FUVEST = 'Fuvest' UNESP = 'Unesp' UERJ = 'UERJ' OUTROS = 'Outros'
193
87
import numpy as np def mds(d, dimensions=3): """ Multidimensional Scaling - Given a matrix of interpoint distances, find a set of low dimensional points that have similar interpoint distances. """ (n, n) = d.shape E = (-0.5 * d ** 2) # Use mat to get column and row means to act as co...
635
244
#!/usr/bin/env python3 from collections import Counter # Complete the isValid function below. def isValid(s): freq = Counter(s) values = list(freq.values()) values.sort() return "YES" if values.count(values[0]) == len(values) or (values.count(values[0]) == len(values) - 1 and values[-1] - values[-2]...
492
180
''' This file provides data and objects that do not change throughout the runtime. ''' import converter import string import traceback import warnings from voussoirkit import sqlhelpers from voussoirkit import winwhich # FFmpeg ##########################################################################################...
10,238
3,071
# -*- coding: utf-8 -*- """ Spectra analysis utilities """ from ._version import __version__ __all__ = ['__version__']
122
49
# Copyright (C) 2020 FUJITSU # 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 by a...
88,309
29,254
# codplayer supporting package # # Copyright 2013-2014 Peter Liljenberg <peter.liljenberg@gmail.com> # # Distributed under an MIT license, please see LICENSE in the top dir. # Don't include the audio device modules in the list of modules, # as they may not be available on all systems from pkg_resources import get_dis...
841
287
"""Common imports for generated bigtableclusteradmin client library.""" # pylint:disable=wildcard-import import pkgutil from googlecloudsdk.third_party.apitools.base.py import * from googlecloudsdk.third_party.apis.bigtableclusteradmin.v1.bigtableclusteradmin_v1_client import * from googlecloudsdk.third_party.apis.bi...
436
137
from typing import Tuple, Optional import click from cloup import constraint, option, command, pass_context from cloup.constraints import RequireExactly from .pagescommands import Create, Remove, Push, Pull, List, Publish, Unpublish class Pages(click.Group): def __init__(self): super(Pages, self).__ini...
4,229
1,218
#!/user/bin/python3 import cv2 #loading image img=cv2.imread("dog.jpeg") img1=cv2.line(img,(0,0),(200,114),(110,176,123),2) #print height and width print(img.shape) #to display that image cv2.imshow("dogg",img1) #image window holder activate #wait key will destroy by pressing q button cv2.waitKey(0) cv2.d...
339
147
import gensim import fnmatch import os import pickle import numpy as np # from symspellpy.symspellpy import SymSpell, Verbosity # import the module # initial_capacity = 83000 # # maximum edit distance per dictionary precalculation # max_edit_distance_dictionary = 2 # prefix_length = 7 # sym_spell = SymSpell(initial_c...
2,139
817
import pandas as pd import numpy as np from hashlib import md5 import datetime import pyarrow.parquet as pq import pyarrow as pa from src.dimension_surrogate_resolver import DimensionSurrogateResolver def run(): for dt in ["20160201", "20160301"]: create_fact_dimension_tables(dt) display_output() de...
8,611
2,895
"""Starts a fake fan, lightbulb, garage door and a TemperatureSensor """ import logging import signal import random from pyhap.accessory import Accessory, Bridge from pyhap.accessory_driver import AccessoryDriver from pyhap.const import (CATEGORY_FAN, CATEGORY_LIGHTBULB, ...
3,294
1,096
from django.urls import path from .views import ( # CRUDS CommercialList, CommercialDelete, CommercialDetail, CommercialCreate, CommercialUpdate, CommercialDelete, CommercialInactivate, # QUERY ) urlpatterns = [ #CRUD path('', CommercialList.as_view()), path('create/', Com...
574
208
import folium def add_lyr_google_hybrid(min_zoom, max_zoom): row = { 'link': 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', 'name': 'Google Hybrid', 'attribution': 'https://www.google.com/maps', } lyr = folium.TileLayer( tiles=row['link'], attr=('<a href="{}"...
2,715
1,033
"""Add Hometasks for Students Revision ID: 6e5e2b4c2433 Revises: b9acba47fd53 Create Date: 2020-01-10 20:52:40.063133 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '6e5e2b4c2433' down_revision = 'b9acba47fd53' branch_labels = None depends_on = None def upgr...
1,277
472
import time import math import fyplot import o80_roboball2d from functools import partial def _plot(frontend_robot,frontend_simulation): plt = fyplot.Plot("o80_roboball2d",50,(2000,800)) def get_observed_angle(frontend,dof): return frontend.read().get_observed_states().get(dof).get_position() ...
1,759
713
# # Copyright (C) 2018 The Android Open Source Project # # 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 la...
10,099
3,888
from cbapi.response import * from lrjob import run_liveresponse from cbapi.example_helpers import get_cb_response_object, build_cli_parser def main(): parser = build_cli_parser("Cb Response Live Response example") parser.add_argument("sensorid", nargs=1) args = parser.parse_args() c = get_cb_response...
469
161
from os import rename from os.path import isfile import pickle import sqlite3 from stasis.DiskMap import DiskMap from utils import tsToDate, dateToTs from datetime import timedelta source = sqlite3.connect('db') source.row_factory = sqlite3.Row dest = DiskMap('db-new', create = True, cache = False) # Some cleanup, be...
6,655
2,358
import boto3 aws_ebs_client = boto3.client('ebs')
52
25
''' Generate slideshows from markdown that use the remark.js script details here: https://github.com/gnab/remark Run it like this: python MakeSlides.py <source_text.md> <Slidestack Title> index.html ''' import sys import os template = ''' <!DOCTYPE html> <html> <head> <title>{title_string}</title> <met...
1,211
424
# -*- coding: utf-8 -*- from __future__ import division, print_function from ._mesh import * from ._openscad import * from ._threads import *
144
52
import gzip import os import re import sys import time from functools import reduce from itertools import chain from multiprocessing import cpu_count import lmdb import psutil import joblib from joblib import Parallel, delayed import numpy as np from pricePrediction import config from pricePrediction.config import USE...
6,805
2,184
# import just one function from a module # to save memory from module import dowork #now we can us a different name to get to the imported function # dowork(13,45) dir()
173
55
from PyQt5.QtCore import QThread, pyqtSignal, QMutex from lanzou.api import LanZouCloud from lanzou.gui.models import Infos from lanzou.debug import logger class GetMoreInfoWorker(QThread): '''获取文件直链、文件(夹)提取码描述,用于登录后显示更多信息''' infos = pyqtSignal(object) share_url = pyqtSignal(object) dl_link = pyqtSig...
2,894
1,040
""" Source: https://camcairns.github.io/python/2017/09/06/python_watchdog_jobs_queue.html This class inherits from the Watchdog PatternMatchingEventHandler class. In this code our watchdog will only be triggered if a file is moved to have a .trigger extension. Once triggered the watchdog places the event object on the...
2,728
770
#!/usr/bin/python3 import sys #import fileinput from operator import itemgetter myDictionary = {} myList=[] for line in sys.stdin: line = line.strip() line = line.split("\t") batsman, bowler, wickets = line[0], line[1], int(line[2]) if batsman not in myDictionary: myDictionary[batsman] = {} ...
1,492
528
from abstractions.datastore import Datastore from unittest.mock import Mock from google.cloud.datastore.entity import Entity from unittest.mock import patch import pytest """ #test_valid_information::ut #test_with_invalid_information::ut """ @patch("google.cloud.datastore.Client") def test_update_entity(mocked_data...
2,478
856
import logging import logging.config import os from importlib.metadata import version from typing import Any, Union from .trace import ( make_request_logging_trace_config, make_sentry_trace_config, make_zipkin_trace_config, new_sampled_trace, new_trace, new_trace_cm, notrace, setup_sent...
2,331
775
# Copyright 2017 QuantRocket - 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 by applicable law or ...
3,628
1,063
from random import shuffle from math import sqrt from enum import Enum from src.Sudoku.SudokuSolver import SudokuSolver from src.Sudoku.Sudoku import Sudoku """ **** SUDOKU GENERATOR **** Author: Andrea Pollastro Date: September 2018 """ class SudokuGenerator: __solver = SudokuSolver() def createSudoku(...
3,778
1,181
import argparse import random, os from os.path import join as j from collections import OrderedDict import conllu import torch import pathlib import tempfile import depedit import stanza.models.parser as parser from stanza.models.depparse.data import DataLoader from stanza.models.depparse.trainer import Trainer from s...
15,753
5,171
def makeSentence(x, y, z): return '{0}時の{1}は{2}'.format(x, y, z) if __name__ == '__main__': ans = makeSentence(12, '気温', 22.4) print(ans)
151
80
__version__ = '0.1.0' from .parser import parse
49
20
from os.path import expanduser import sys import json ''' The configuration file will be stored as a json file @example { window: { w_dimension: 800 h_dimension: 600 resizeable: False } } ''' class ConfigurationLoader: ''' ''' def __init__(self): ''' Initialize with defaut values ''' ...
1,769
687
#!/bin/python3 import sys import os import getopt import csv import json import itertools import zipfile import tarfile import binwalk import collections from heapq import nsmallest from collections import defaultdict import tlsh import numpy as np import matplotlib.pyplot as plt from multiprocessing.dummy import Poo...
11,432
3,648
from pyomo.environ import * import numpy as np cijr = [] fjr = [] with open("./Test_Instances/RAND2000_120-80.txt") as instanceFile: n = int(instanceFile.readline()) clientsFacilitiesSizeStr = instanceFile.readline().strip().split(" ") instanceFile.readline() for phase in range(2): for i in range(1, len(cl...
3,132
1,474
# # exports a specific folder in the import directory to the google cloud # # Syntax: # python3 import.py <GS URI> # # Example: # python3 import.py gs://bini-products-bucket/training-sets-2/intrusion/poc1_v1.2.0/frames # # import os import sys # uri cloud_uri = sys.argv[1] os.system('mkdir -p import') os.system...
367
145
#!/usr/bin/env python import xml.etree.ElementTree as ET class brocade_xstp_ext(object): """Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def get_stp_brief_info_input_request_type_getnext_request_last_rcvd_instance_instance_id(sel...
482,361
173,762
import pytz from django.conf import settings class TZMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): browser_tz = request.COOKIES.get("browserTimezone") tz = None if browser_tz: try: tz = p...
735
241
default_app_config = 'foundation.apps.FoundationConfig'
56
17
from flask import Flask from flask_migrate import Migrate from app.model import db from app.controller import api app = Flask(__name__) app.register_blueprint(api) app.config[ "SQLALCHEMY_DATABASE_URI" ] = "postgresql://newschatbotdevelopment:Wlk8skrHKvZEbM6Gw@database.internal.newschatbot.ceskodigital.net:5432/n...
483
189
from .test_vehicles_crud import * from .test_soat_vehicles import *
67
26
"""Example on how to read sleep data from SIHA """ import os from tasrif.data_readers.siha_dataset import SihaDataset from tasrif.processing_pipeline import SequenceOperator from tasrif.processing_pipeline.custom import JqOperator from tasrif.processing_pipeline.pandas import ( ConvertToDatetimeOperator, JsonN...
2,887
843
import pytest from visionpy import Vision, Contract from visionpy import AsyncVision, AsyncContract from visionpy.keys import PrivateKey # vpioneer addr and key PRIVATE_KEY = PrivateKey(bytes.fromhex("a318cb4f1f3b87d604163e4a854312555d57158d78aef26797482d3038c4018b")) FROM_ADDR = 'VSfD1o6FPChqdqLgwJaztjckyyo2GSM1KP' ...
6,169
2,974
from django.db.models import Avg from store.models import Book, UserBookRelation def set_rating(book: Book) -> None: rating = UserBookRelation.objects.filter(book=book).aggregate(rating=Avg('rate')).get('rating') book.rating = rating book.save()
261
84
"""Default base class for PSP pages. This class is intended to be used in the future as the default base class for PSP pages in the event that some special processing is needed. Right now, no special processing is needed, so the default base class for PSP pages is the standard Webware Page. """ from Page import Page ...
555
149
## # File: DictMethodEntityInstanceHelper.py # Author: J. Westbrook # Date: 16-Jul-2019 # Version: 0.001 Initial version # # # Updates: # 22-Nov-2021 dwp authSeqBeg and authSeqEnd are returned as integers but must be compared as strings in pAuthAsymD # ## """ This helper class implements methods supporting enti...
139,378
42,552
"""Long statement strings and other space consuming data definitions for testing are declared here. This is done to avoid clutter in main test files. """ from typing import Dict from typing import List from typing import Tuple import pytest from _pytest.fixtures import SubRequest from fi_parliament_tools.parsing.dat...
12,788
5,039
import sys import math import itertools from collections import deque sys.setrecursionlimit(10000000) input=lambda : sys.stdin.readline().rstrip() a,b,x=map(int,input().split()) if (a**2*b)-x<=(a**2*b)/2: c=2*((a**2*b)-x)/(a**2) print(math.degrees(math.atan2(c,a))) else: c=2*x/b/a print(math.degrees(ma...
336
159
import struct import itertools import freetype ENDIAN = '<' # always little endian # If you make a modified version, please change the URL in the string to # let people know what generated the file! # example: Bakefont 3.0.2 (compatible; Acme Inc version 1.3) ENCODER = "Bakefont 3.0.2 (https://github.com/golightlyb/b...
12,644
4,412
"""Test health check""" def test_healthcheck(client): response = client.get("/healthcheck") assert response.status_code == 200
137
45
""" This INTERNAL module is used to manage fbs's global state. Having it here, in one central place, allows fbs's test suite to manipulate the state to test various scenarios. """ from collections import OrderedDict SETTINGS = {} LOADED_PROFILES = [] COMMANDS = OrderedDict() def get(): return dict(SETTINGS), list...
578
201