id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9899272 | from xgboost import XGBRegressor
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.tree import DecisionTreeRegressor
def train_model(X_train, y_train, black_box="MLP", random_see... |
9899285 | import asyncio
from abc import ABCMeta, abstractmethod
from . import logutils
logger = logutils.get_logger('ccxtws')
# https://refactoringguru.cn/design-patterns/observer/python/example
class ExchangeBoost(metaclass=ABCMeta):
@abstractmethod
def subscribe(self, observer):
pass
@abstractmethod
... |
9899294 | import requests
from unittest.mock import patch, Mock, ANY
from unittest import TestCase
from samcli.lib.telemetry.telemetry import Telemetry
class TestTelemetry(TestCase):
def setUp(self):
self.gc_mock = Mock()
self.global_config_patcher = patch("samcli.lib.telemetry.telemetry.GlobalConfig", se... |
9899324 | def init():
import tensorflow as tf
global sess, predict, x, keep_prob
# load the saved tensorflow model and parameters
sess = tf.Session()
sess.run(tf.global_variables_initializer())
saver = tf.train.import_meta_graph('./my_ConvNet_MNIST_model.meta')
saver.restore(sess,tf.train.latest_chec... |
9899397 | from data_structure import Corpus
import argparse
import cPickle
def main(train_path, dev_path, test_path):
corpus = Corpus()
corpus.load(train_path, 'train')
corpus.load(dev_path, 'dev')
corpus.load(test_path, 'test')
corpus.preprocess()
options = dict(max_sents=60, max_tokens=100, skip_gram=... |
9899413 | import numpy as np
class WyckoffSet():
"""Represents a group of atoms in a certain Wyckoff position, for a certain
space group.
"""
def __init__(
self,
wyckoff_letter=None,
atomic_number=None,
element=None,
indices=None,
x=None,
... |
9899434 | from .kwcnndescriptor import KWCNNDescriptorGenerator
__author__ = '<EMAIL>,<EMAIL>'
DESCRIPTOR_GENERATOR_CLASS = KWCNNDescriptorGenerator
|
9899472 | import pybitcointools
import hashlib
import base58
from io import BytesIO
from pybitcoin import BitcoinPrivateKey
def wif_private_key(private_key_with_version):
# Hash the private_key_with_version value using the cryptographic hash function SHA256.
# This Secure Hash Algorithm generates a 256-bit (32-byte) s... |
9899477 | from tests.test_base import BaseUnitTest
from tests.test_base import Context
from cf.main import GaExportedNestedDataStorage
class TestCFFlattenMethods(BaseUnitTest):
def test_flatten_ga_data(self):
c = Context()
ga_source = GaExportedNestedDataStorage(gcp_project=c.env["project"],
... |
9899489 | import logging
from typing import Dict
from carball.json_parser.game import Game
from carball.generated.api import game_pb2
from carball.generated.api.game_pb2 import mutators_pb2 as mutators
from carball.generated.api.player_pb2 import Player
log = logging.getLogger(__name__)
def create_dropshot_ball_events(game: G... |
9899507 | from isitfit.utils import logger
from .tagsSuggestBasic import TagsSuggestBasic
class TagsDump(TagsSuggestBasic):
def tags_to_dict(self, ec2_obj):
tags_dict = {x['Key']: x['Value'] for x in ec2_obj.tags}
return tags_dict
def suggest(self):
logger.info("Dumping to csv")
from .tagsSuggestBasi... |
9899516 | import tensorflow as tf
import tflearn
import argparse
import pickle
import sys
class Model:
def __init__(self,params):
self.input_dir = params['input_path']
self.output_dir = params['output_path']
self.lr = float(params['learning_rate'])
self.batch_size = int(params['batch_size'])... |
9899524 | import copy
import time
import os
import random
from collections import defaultdict
from typing import Any, Callable, Dict, List, Optional, Union
import numpy as np
from .segment_tree import SumSegmentTree, MinSegmentTree
from ctools.utils import remove_file
DataType = Dict[str, Any] # TODO(Local State) replace An... |
9899533 | import os
import yaml
import requests
from time import time, sleep
cfg = yaml.safe_load(open('config.yaml', 'r', encoding='utf-8-sig'))
text = yaml.safe_load(open('text.yaml', 'r', encoding='utf-8-sig'))
DEBUG = os.environ.get('debug', 'False') in ['True', 'true']
def download(url, file_path, timeout=30... |
9899547 | import torch
import tensorflow as tf
import config
import pandas as pd
import pickle
import io
import json
import os
import config
from torch.utils.data import Dataset
def get_dataloaders(name):
if name=='imdb':
return get_imdb_dataloaders()
if name=='human_numbers':
return get_human_numbers_da... |
9899573 | def search(arr,number):
arr.sort()
low,high=0,len(arr)-1
while(low<=high):
mid=low+high//2
if(arr[mid]==number):
return mid
elif(arr[mid]>number):
high=mid-1
else:
low=mid+1
else:
return -1
arr = list(map(int,input("Enter Numbers... |
9899581 | from pynani.core.pynani import Component, RunApp
from pynani.core.widgets import Widgets
widgets = Widgets()
class MyApp(Component):
def build(self):
return widgets.header1(
text="Hello, World!",
styles=[
"margin: 30px"
]
)
RunApp(MyApp()) |
9899627 | from nj import core, operators
__all__ = ['and_', 'nor_', 'not_', 'or_']
class and_(operators.ArgsOperator):
pass
class nor_(operators.ArgsOperator):
pass
class not_(operators.UnaryOperator):
def prepare(self, value: core.MongoObject_T) -> core.MongoObject: # type: ignore
return core.MongoO... |
9899642 | import re
import time
from datetime import datetime
import pytz
from pytz import timezone
TZ = timezone('Asia/Shanghai')
time_type = datetime or time.struct_time or str
RSSHUB_PREFIX = 'https://rsshub.app'
class RSS:
def __init__(self,
name: str,
url: str,
title... |
9899669 | import os
import time
import numpy as np
import random
import torch
from behavenet.data.utils import build_data_generator
from behavenet.fitting.eval import export_train_plots
from behavenet.fitting.hyperparam_utils import get_all_params
from behavenet.fitting.hyperparam_utils import get_slurm_params
from behavenet.fi... |
9899676 | import lin_reg
import numpy as np
import matplotlib.pyplot as plt
from ml.linear_regression import LinearRegression
import time
x = sorted([0.1, 2.3, 6.3, 9.2, 1.6, 2.3, 5.1, 7.2, 4.3, 1.5, 6.3, 8.9, 3.2, 3.5, 5.6])
y = list(map(lambda x: 0.3*x + 0.2, x))
start_time = time.time()
#theta = LinearRegression()
#theta.fi... |
9899699 | from uds import Uds
if __name__ == "__main__":
a = Uds(reqId=0x7E0, resId=0x7E8, interface="peak", device="PCAN_USBBUS1")
## transmit a standard tester present
TesterPresent = a.send([0x3E, 0x00])
print(TesterPresent) # This should be [0x7E, 0x00]
## transmit a request for ECU Serial Number
... |
9899705 | def parse_properties(request):
"""Parses the query string for properties and returns them in the format:
property_id|option_id
"""
properties = []
for prop, option_id in request.POST.items():
if prop.startswith("property"):
try:
prop_group_id = prop.split("_")[1]
... |
9899727 | import atexit
import logging
import os
import shutil
import tempfile
from logging import DEBUG
log = logging.getLogger(__name__)
CLEANUP = True
class ImageDebug(object):
def __init__(self):
self.index = 0
self.dir = tempfile.mkdtemp(prefix="pyscreenshot_img_")
if CLEANUP:
ate... |
9899746 | import cv2
# getting the path for first image
src1 = input("Enter the path of the image 1\n")
src1 = cv2.imread(src1)
# src1 = cv2.resize(src1,(540,540)) #resizing the image
# getting the path for second image
src2 = input("Enter the path of the image 2\n")
src2 = cv2.imread(src2)
# Resizing the image... |
9899750 | faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,
minNeighbors=4,\
minSize=(30,30),\
maxSize=(200,200)) |
9899760 | import torchvision.ops # noqa: F401
from torch2trt_dynamic.plugins import create_roiextractor_plugin
from torch2trt_dynamic.torch2trt_dynamic import (get_arg, tensorrt_converter,
trt_)
@tensorrt_converter('torchvision.ops.roi_align')
def convert_roi_align(ctx):
i... |
9899772 | from decimal import Decimal
from .abc import WithdrawalStrategy
# This one is super-simple...just take a constant percentage every
# year. Don't try to index for inflation. So it will vary as the portfolio
# value varies...
class ConstantPercentage(WithdrawalStrategy):
def __init__(self, portfolio, harvest_strateg... |
9899803 | import numpy as np
from spartan import expr, core, array, blob_ctx
from sklearn.neighbors import NearestNeighbors as SKNN
def _knn_mapper(ex,
X,
Q,
n_neighbors,
algorithm):
"""
knn kernel for finding k(n_neighbors) nearest neighbors of a giving query... |
9899828 | import torch
import torch.nn as nn
from latent_variable_model import LatentVariableModel
from lib.modules.latent_levels import LSTMLatentLevel
from lib.modules.networks import LSTMNetwork, FullyConnectedNetwork
from lib.modules.layers import FullyConnectedLayer
from lib.distributions import Normal, Bernoulli
class SV... |
9899847 | import os
import logging
from typing import List, Dict
import pandas as pd
import numpy as np
from hypermodel import hml
from hypermodel.features import one_hot_encode
import requests
from hypermodel.platform.gcp.services import GooglePlatformServices
MODEL_NAME = "titanic-xgb"
TARGET_COLUMN = "Survived"
# Lets just ... |
9899878 | import unittest
import torch
from hamcrest import assert_that, equal_to
from torchvectorized.debug.nn import Logm, EigVals, Expm
from torchvectorized.utils import sym
from torchvectorized.vlinalg import vSymEig
class NnTest(unittest.TestCase):
def setUp(self):
self._target = torch.tensor(
... |
9899880 | n=int(input("Enter number: "))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
|
9899884 | from .converters import * # noqa: F401,F403
from .mmdet2trt import Int8CalibDataset, mask_processor2trt, mmdet2trt
__all__ = ['Int8CalibDataset', 'mask_processor2trt', 'mmdet2trt']
|
9899896 | from .climate import TuyaClimate
from .cover import TuyaCover
from .fan import TuyaFanDevice
from .light import TuyaLight
from .lock import TuyaLock
from .scene import TuyaScene
from .switch import TuyaSwitch
def get_tuya_device(data, api):
dev_type = data.get("dev_type")
devices = []
if dev_type == "lig... |
9899898 | from django.shortcuts import render, HttpResponse
from django.core.files.storage import FileSystemStorage
import os, datetime, base64
from . import remover
extensions = ['.jpg', '.jpeg', '.png']
def index(request):
if request.method == 'POST' and request.FILES['image']:
image = request.FILES['image']
... |
9899932 | import tkinter
import cv2
from PIL import Image, ImageTk
import numpy as np
import sqlite3
import pandas as pd
from tkinter import ttk
from tkinter import Menu
import tkinter.messagebox
import csv
import threading
from tkinter import filedialog
import os
class Application(tkinter.Frame):
#GUIウィンドウの設定と画像描画
def ... |
9899942 | import re
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import dash_loading_spinners as dls
from dash.dependencies import Input, Output
__all__ = ["get_component_details"]
HEADER_PATTERN = re.compile(r"---.*---", flags=re.DOTALL)
SPLIT_PATTERN = re.com... |
9899961 | import os
from collections import OrderedDict
import numpy as np
from lib.dataset_analysis import print_characteristics
# name, path, number of realization, number of nodes, end_time
hawkes_datasets = [
('Bund', '../hawkes/bund/bund.npz', 20, 4, 50400)
]
def iterate_hawkes_dataset_path():
for name, path, *a... |
9899987 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from gluonnlp.utils.preprocessing import get_trimmed_lengths, match_tokens_with_char_spans
def test_get_trimmed_lengths():
for lengths, do_merge, max_length, gt_trimmed_lengths in\
[([10, 5, 4, 8], False, 6, [6, 5, 4, 6]),
... |
9900023 | import os, shutil
from glob import glob
from subprocess import call
import argparse
import ipdb as pdb
def main():
parser = argparse.ArgumentParser(description="Convert gif to xbm")
parser.add_argument('input', type=str)
parser.add_argument('output', type=str)
parser.add_argument('--frameskip', type=i... |
9900032 | import os
import decimal
import json
total_time_tag = 'Total time without IO:'
root_folder_gpu23 = '/home/yche/mnt/gpu-23/projects/python_experiments'
root_folder_knl = '/home/yche/mnt/luocpu8//nfsshare/share/python_experiments'
gpu23_tag = 'gpu23'
knl_tag = 'knl'
data_set_lst = ['snap_orkut', 'webgraph_webbase', '... |
9900038 | from __future__ import print_function
from simpleflow import Workflow, activity
from simpleflow.exceptions import ExecutionBlocked
from .worker import build_boat, find_crew, find_or_steal_money, find_parrot, steal_boat
# decorator for all activities
def pirate_activity(func):
return activity.with_attributes(tas... |
9900070 | from django.db import models
from wagtail.contrib.settings.models import BaseSetting, register_setting
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.core.fields import RichTextField
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.snippets.edit_handlers import SnippetChooserPane... |
9900077 | from ckeditor_uploader.widgets import CKEditorUploadingWidget
from django import forms
from django.contrib import admin
from django.contrib import messages
from backend.blog.models import Post, Tag, SpySearch, BlogCategory, Comment
from mptt.admin import MPTTModelAdmin
class ActionPublish:
"""Action для публикаци... |
9900078 | from collections import defaultdict
from typing import Generic, TypeVar, Union
from . import INDENT
T = TypeVar('T')
class ListEx(list, Generic[T]):
"""
Extended list with shortcut methods
"""
def safe_index(self, value: T):
try:
return self.index(value)
except ValueErro... |
9900088 | import angr
import itertools
######################################
# malloc
######################################
malloc_mem_counter = itertools.count()
class malloc(angr.SimProcedure):
#pylint:disable=arguments-differ
def run(self, sim_size):
return self.state.heap._malloc(sim_size)
|
9900102 | import argparse
import xml.etree.cElementTree as etree
import os
from os import listdir
from os.path import isfile, join
import codecs
import re
from six.moves import html_parser
# Remove empty brackets (that could happen if the contents have been removed already
# e.g. for citation ( [3] [4] ) -> ( ) -> nothing
def r... |
9900134 | from __future__ import absolute_import
from __future__ import print_function
from keras import backend as K
import os
import argparse
import warnings
import numpy as np
import tensorflow as tf
import keras.backend as K
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
fr... |
9900178 | from ehp import *
html = Html()
data = '''<tag> The & is a good & symbol. </tag>'''
dom = html.feed(data)
for root, ind in dom.find_with_root(AMP):
print(ind)
|
9900182 | import pytest
from blockapi.v2.api.ethplorer import EthplorerApi
from blockapi.v2.api.solana import SolanaApi
from blockapi.v2.api.terra_money import TerraMoneyApi
# TODO create method for auto loading all classes
API_CLASSES = [EthplorerApi, SolanaApi, TerraMoneyApi]
NON_EMPTY_VALID_ADDRESSES_BY_SYMBOL = {
'ETH... |
9900195 | import weakref
from functools import wraps
from typing import Sequence
import numpy as np
from torch.optim.lr_scheduler import _LRScheduler, CosineAnnealingLR as CosineAnnealingLR_
from torch.optim import Optimizer
__all__ = [
"BaseLRScheduler", "LinearLR",
"ExponentialLR", "TriangularLR",
"GradualWarmupS... |
9900217 | data = (
'mil', # 0x00
'milg', # 0x01
'milm', # 0x02
'milb', # 0x03
'mils', # 0x04
'milt', # 0x05
'milp', # 0x06
'milh', # 0x07
'mim', # 0x08
'mib', # 0x09
'mibs', # 0x0a
'mis', # 0x0b
'miss', # 0x0c
'ming', # 0x0d
'mij', # 0x0e
'mic', # 0x0f
'mik', # 0x10
'mit', # ... |
9900243 | import os
from typing import Union
from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout, QSizePolicy, QLayout
from .Util import parse_version
class WhatsNew(QDialog):
def __init__(self, parent, changelogs):
from .. import release_ver
super().__init__(parent)
self.setWindowTitle("What'... |
9900245 | from ebu_tt_live.documents import EBUTT3Document, EBUTT3DocumentSequence
from pytest_bdd import given, when, then, scenarios, parsers
import pytest
scenarios('features/validation/sequence_identical_timing_model.feature')
# We cannot use a sequence fixture here like in other sequence tests because
# the sequence is ... |
9900252 | from geodata.addresses.config import address_config
import random
from geodata.addresses.config import address_config
from geodata.addresses.numbering import NumericPhrase
from geodata.encoding import safe_decode
class MetroStationPhrase(NumericPhrase):
key = 'metro_stations.alphanumeric'
dictionaries = ['... |
9900254 | import sys
import numpy as np
from tqdm import tqdm
from .actor import Actor
from .critic import Critic
from utils.stats import gather_stats
from utils.networks import tfSummary, OrnsteinUhlenbeckProcess
from utils.memory_buffer import MemoryBuffer
import os
class DDPG:
""" Deep Deterministic Policy Gradient (DD... |
9900341 | from pathlib import Path
import json
import re
import requests
import time
import os
dictionary_filename = 'efremova.txt'
dictionary_forms_filename = 'odict.csv'
json_filename = 'data.json'
output_without_filter_json_filename = 'russian_nouns_with_definition_without_filter.json'
output_json_filename = 'russian_nouns_w... |
9900345 | from .coco_api import COCO, COCOeval
from .coco_video_parser import CocoVID
__all__ = ['COCO', 'COCOeval', 'CocoVID']
|
9900360 | signature = ""
accesskey = ""
sandbox = True
localhost = "http://localhost/"
database = "mysql://root@localhost/turkic"
# probably no need to mess below this line
import multiprocessing
processes = multiprocessing.cpu_count()
import os.path
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
9900394 | import requests
import boto3
from uuid import uuid4
from django.core.management.base import BaseCommand
from django.db.models import Q, Count
from botocore.exceptions import ClientError
from user.models import User
from django.conf import settings
from std_bounties.seo_client import SEOClient
import logging
seo_clien... |
9900404 | import ui
dog = ui.Image('Dog_Face')
cat = ui.Image('Cat_Face')
def set_dog(sender):
v['imageview1'].image = dog
def set_cat(sender):
v['imageview1'].image = cat
v = ui.load_view()
v.background_color = 'gray'
v['imageview1'].image = dog
v['button1'].background_image = dog
v['button1'].background_color... |
9900439 | from rpython.rtyper.lltypesystem import rffi, lltype
from async_io import *
import rlibuv as uv
import core
import uv_callback
import uv_util
# TODO: Upgrade the stuff to Handle2 as you go. Once done, remove the old Handle
# TODO: It would very much make sense to make certain things actual queues
# and event ha... |
9900442 | import asyncio
from logging import error
from telethon import TelegramClient
import telethon
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.tl.functions.messages import CheckChatInviteRequest, ImportChatInviteRequest
from telethon.tl.functions.users import GetFullUserRequest
import random
... |
9900444 | import math
from catalyst.dl import RunnerState, CriterionCallback
from catalyst.dl.callbacks.criterion import _add_loss_to_state
from torch import nn
__all__ = ["LPRegularizationCallback"]
class LPRegularizationCallback(CriterionCallback):
"""
Generalized L1/L2 weight decay callback that may exponentially ... |
9900446 | import b2d
from ..gui_base import GuiBase
class EmptyDebugDraw(b2d.batch_debug_draw_cls(False, True, True)):
def __init__(self):
super(EmptyDebugDraw, self).__init__()
def _draw_solid_polygons(self, points, sizes, colors):
pass
def _draw_polygons(self, points, sizes, colors):
pas... |
9900448 | import pickle
import time
import numpy as np
from modules import UNetModel
from modules import ImageGenerator
if __name__ == '__main__':
img_width = -1
while(True):
print('Smaller images allows training to be perfomed faster with a slight loss in accuracy\n')
choice = input('Select the ima... |
9900451 | from django.contrib import admin
from .models import MyModel
class MyModelAdmin(admin.ModelAdmin):
model = MyModel
admin.site.register(MyModel, MyModelAdmin)
|
9900455 | import torch
def jacobian(f, x, out_dim):
"""Computes Jacobian of a vector-valued function.
Given f: batch_size x input_dim -> batch_size x output_dim
Computes Jacobian Matrix J: batch_size x output_dim x input_dim
By passing a gradient matrix to the backward call of the output tensor
NOTE:
... |
9900497 | import binascii
import hashlib
import logging
from typing import Union, Type, TypeVar
import eth_keyfile
from coincurve import PrivateKey, PublicKey
from loopchain.crypto.cert_serializers import DerSerializer, PemSerializer
T = TypeVar('T', bound='SignVerifier')
class SignVerifier:
def __init__(self):
... |
9900589 | from dbt.tests.util import AnyStringWith, AnyFloat, AnyString
def redshift_stats():
return {
"has_stats": {
"id": "has_stats",
"label": "Has Stats?",
"value": True,
"description": "Indicates whether there are statistics for this table",
"include"... |
9900595 | import datetime
import json
import os
from os import path
import bson.json_util as j
import pexpect
from bson import ObjectId
from django.conf import settings
from django.http import HttpResponse
from numpy import NaN
from pandas import read_excel, read_csv
from xlrd import XLRDError
from dal.copo_da import Annotatio... |
9900629 | import re
import sys
def read_config(file):
with open(file, "rt") as inp:
lines = [l.strip() for l in inp.readlines() if l.strip() and not l.strip()[0] == '#']
sections = {}
sections[''] = cur_section = {}
for n, line in enumerate(lines):
lineno = n+1
head = re.match(r'^\[(.+)\]$', line)
if head is N... |
9900645 | def solution(A):
"""Check if an array is a permutation.
A permutation is a sequence containing each element from 1 to N once, and
only once.
Args:
A (list): A non-empty list of N integers.
Returns:
int: 1 if the array is a permutation, 0 if it is not.
Complexity:
Time... |
9900677 | import os
from .schema import Schema
import pandas as pd
class TiingoData:
"""Tiingo (stocks & indeces) Data container class."""
def __init__(self, file, schema=None, **params):
if schema is None:
self.schema = TiingoData.default_schema()
file_extension = os.path.splitext(file)[1]... |
9900701 | import os
import struct
from io import BytesIO
from PIL import Image
from torch.utils.data import Dataset
from torchkit.data import example_pb2
def read_index_file(index_file):
""" Parse index file, each line contains record_name, record_index, record_offset and label
"""
samples_offsets = []
record_f... |
9900718 | import shutil
import numpy as np
from keras.models import load_model
from sklearn.externals import joblib
from gensim.models import KeyedVectors
from steps.base import BaseTransformer
from .contrib import AttentionWeightedAverage
class BasicClassifier(BaseTransformer):
"""
Todo:
load the best model ... |
9900725 | import re
import io
import html
import logging
import collections
import collections.abc
from piecrust import APP_VERSION, PIECRUST_URL
from piecrust.page import FLAG_RAW_CACHE_VALID
logger = logging.getLogger(__name__)
css_id_re = re.compile(r'[^\w\d\-]+')
CSS_DATA = 'piecrust-debug-info-data'
CSS_DATABLOCK = 'p... |
9900728 | MODES = ["201", "202", "203", "204", "206"]
TABLE_HEADER = ["Server", "Americas", "Europe", "Korea"]
STATISTICS_HEADER = ["Race", "P", "T", "Z", "R"]
STATISTICS_HEADER_WITH_TOTAL = STATISTICS_HEADER + ["Total"]
LEAGUES = ["Bronze", "Silver", "Gold", "Platinum", "Diamond", "Master", "GrandMaster"]
REGIONS = ["us", "eu",... |
9900734 | from eaglesong import EaglesongHash
import sys
from binascii import hexlify
lines = sys.stdin.readlines()
input_bytes = "\n".join(lines)
input_bytes = bytearray(input_bytes, "utf8")
output_bytes = EaglesongHash(input_bytes)
print(hexlify(bytearray(output_bytes)))
|
9900752 | n = int(input())
for i in range(1, n+1, 1):
for spaces in range(1, (n-i)+1, 1):
print(" ", end="")
for forward_count in range(i, 2*i, 1):
print(forward_count, end="")
for rev_count in range(2*i-2, i-1, -1):
print(rev_count, end="")
print()
|
9900766 | import os
import time
import numpy as np
from panda3d.core import loadPrcFile
from citysim3d.envs import GeometricCarPanda3dEnv
from citysim3d.spaces import BoxSpace
assert "CITYSIM3D_DIR" in os.environ
loadPrcFile(os.path.expandvars('${CITYSIM3D_DIR}/config.prc'))
def main():
# actions are forward acceleration ... |
9900773 | from tir import Webapp
import unittest
import datetime
class TMSA150(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
dataAtual = str(datetime.datetime.now().strftime("%d/%m,%Y"))
inst.oHelper.Setup('SIGATMS',dataAtual,'T1','M SP 02 ','43')
inst.oHelper.Program('TMSA150')
def... |
9900779 | import random
import math
import numpy as np
from scipy.stats import cauchy
from stochastic.simulated_annealing import simulated_annealing
def QA(x0, t0, f, N=2500):
"""
алгоритм имитации отжига
метод Коши
"""
annealing = lambda k: t0 / math.pow(k, 1. / len(x0))
# passage = lambda e_old, e_new... |
9900795 | import os
import re
import subprocess
from io import StringIO
import pandas as pd
pd.options.mode.chained_assignment = None
REPOSITORIES = [
"nns-dapp",
"internet-identity",
"motoko",
"sdk",
"ic",
"docs",
"agent-js",
"ic-staking-documentation",
"keysmith",
"examples",
]
COLUMN... |
9900815 | from django.contrib import admin
from django.contrib.auth.hashers import make_password
from accounts.models import Customer, ServiceProvider
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ('phone_number', 'first_name', 'last_name', 'date_joined', 'is_active')
list_filter = ('... |
9900822 | from cStringIO import StringIO
import json
import mock
from flask import current_app
from changes.artifacts.analytics_json import AnalyticsJsonHandler, MAX_ENTRIES
from changes.models.failurereason import FailureReason
from changes.testutils import TestCase
class AnalyticsJsonHandlerTest(TestCase):
def setUp(... |
9900895 | import sys
import argparse
import konverter
from konverter.utils.general import success, info, warning, error, COLORS, color_logo, blue_grad
KONVERTER_VERSION = "v0.2.5" # fixme: unify this
KONVERTER_LOGO_COLORED = color_logo(KONVERTER_VERSION)
class KonverterCLI:
def __init__(self, args):
self.args = args
... |
9900904 | import os
import numpy as np
import argparse
from tqdm import tqdm
#from pqdm.processes import pqdm
#from joblib import Parallel, delayed
#from joblib.externals.loky import set_loky_pickler
#from joblib import wrap_non_picklable_objects
#from joblib import parallel_backend
import pandas as pd
import sys
import pickle
... |
9900921 | import numpy as np
from collections import deque
class LineSearchOptimizer(object):
def __init__(self, f, grad, step_size, memory_size=1, **kwargs):
self.convergence = []
self._f = f
self._grad = grad
if step_size is not None:
step_size.assign_function(f, grad, self._f_u... |
9900924 | import httpx
ARCGIS_BASE_URL = "https://services1.arcgis.com/0MSEUqKaxRlEPj5g/ArcGIS/rest/services/ncov_cases/FeatureServer"
ARCGIS_API_URL = f"{ARCGIS_BASE_URL}/1/query"
ARCGIS_REGION_API_URL = f"{ARCGIS_BASE_URL}/2/query"
def parse_summary_data():
stats = {}
for stat in ["confirmed", "deaths", "recovered"... |
9900926 | from ._common import *
# Price Target
IEX_PRICE_TARGET_URL = prepend_iex_url('stock') + '{symbol}/price-target?'
def price_target(symbol, vprint=False):
""":return: Analyst's price targets for the requested ticker.
:param symbol: The ticker or symbol of the stock you would like to request.
:type symbol:... |
9900950 | import numpy as np
from .MaterialBase import Material
from Florence.Tensor import trace
#####################################################################################################
# NeoHookean Material Model 2
###########################################################... |
9900998 | from __future__ import annotations
from abc import ABCMeta, abstractmethod, abstractstaticmethod
from typing import Generic, Type, TypeVar
from google.protobuf.message import Message as _Message
P = TypeVar("P", bound=_Message)
class SerDe(Generic[P], metaclass=ABCMeta):
proto_cls: Type[P]
@classmethod
... |
9900999 | import os , win32api,win32gui
import sys, socket
import platform
import json ,time
import win32con
# One Shot
HOSTNAME = []
IPADRESS = []
TIME = []
PLATFORM = []
USERNAME = []
hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(hide, False)
try:
s = socket.socket(socket.AF_INET, ... |
9901013 | from twindb_backup.copy.mysql_copy import MySQLCopy
def test_key():
backup_copy = MySQLCopy('foo', 'daily', 'some_file.txt', type='full')
assert backup_copy.key == 'foo/daily/mysql/some_file.txt'
|
9901017 | import sublime_plugin
import sublime
import subprocess
from platform import system
from os import path, makedirs
from hashlib import md5
import json
from ..setting.setting import get_setting
from ..setting.setting import SettingObject
from ..setting.db_json_settings import DBJsonSetting
def index_popen_ar... |
9901020 | from .base import BaseAggregator
class RecentTypeAggregator(BaseAggregator):
"""
This aggregator returns activity feeds based on the same activity type (verb)
"""
def set_aggregation_section(self):
self.query_dict["size"] = 0
self.query_dict["aggs"] = {
"types": {
... |
9901060 | from unittest import mock
from corehq.apps.linked_domain.local_accessors import get_enabled_previews
from corehq.apps.linked_domain.tests.test_linked_apps import BaseLinkedDomainTest
from corehq.apps.linked_domain.updates import update_previews
from toggle.shortcuts import set_toggle
from corehq.feature_previews impo... |
9901075 | from click.testing import CliRunner
from pathlib import Path
from PIL import Image, ImageDraw
from bs4 import BeautifulSoup as bs
from ih.cli import main
from ih.palette import get_palette
from ih import helpers
from test_cli import runner, TEST_OUTPUT
s = 1 #square
length = 8
stars_image = "stars_image.png"
def t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.