text
string
size
int64
token_count
int64
from collections import OrderedDict import itertools import sys from tensorflow.keras.layers import Input from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from flowket.callbacks import TensorBoard from flowket.callbacks.exact import default_wave_function_callbacks_factory, ExactO...
3,912
1,378
#!/usr/bin/python # Copyright (c) 2014 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A archive_info is a json file describing a single package archive.""" import collections import hashlib import json import os ...
3,833
1,137
"""Ad hoc tests of the LsstLatexDoc class. Other test modules rigorously verify LsstLatexDoc against sample documents. """ from pybtex.database import BibliographyData import pytest from lsstprojectmeta.tex.lsstdoc import LsstLatexDoc def test_no_short_title(): """title without a short title.""" sample = r"...
3,546
1,165
frase = str(input('Digite o seu nome completo para a análise ser feita:')).strip() print('-' * 50) print('Analisando nome...') print('O seu nome em maiúsculas é {}.'.format(frase.upper())) print('O seu nome em minúsculas é {}.'.format(frase.lower())) print('O seu nome tem ao todo {} letras.'.format(len(frase) - frase.c...
454
168
from functools import partial import logging import msgpack import msgpack_numpy as mpn from confluent_kafka.cimpl import KafkaException import numpy as np import pickle import pytest from bluesky_kafka import Publisher, BlueskyConsumer from bluesky_kafka.tests.conftest import get_all_documents_from_queue from blues...
8,012
2,479
import time import heapq class PriorityQueue(object): def __init__(self): self._q = [] def add(self, value, priority=0): heapq.heappush(self._q, (priority, time.time(), value)) def pop(self): return heapq.heappop(self._q)[-1] def f1(): print('hello') def f2(): print('world') pq...
407
163
import requests import sys from lxml import html #csv_file_name = sys.argv[1] # output file csv_file_name = "../webshot_data/popular-web-sites.csv" csv_file = open(csv_file_name, "w") categories = ["Arts", "Business", "Computers", "Games", "Health", "Home", "Kids_and_Teens", "News", "Recreation", "Reference", "Regio...
1,080
384
""" Common solar physics coordinate systems. This submodule implements various solar physics coordinate frames for use with the `astropy.coordinates` module. """ from __future__ import absolute_import, division import numpy as np from astropy import units as u from astropy.coordinates.representation import (Cartesia...
13,653
4,322
import pytest import os import sys import numpy as np import ray from ray import serve from ray.serve.api import _get_deployments_from_node from ray.serve.handle import PipelineHandle from ray.serve.pipeline.pipeline_input_node import PipelineInputNode @serve.deployment class Adder: def __init__(self, increment...
4,640
1,605
#helpers def logd(tag, msg): print "[Debug-"+tag+"]", msg def loge(tag, msg): print "[Error-"+tag+"]", msg
118
51
from kafka import KafkaProducer from kafka.errors import KafkaError import json # produce json messages producer = KafkaProducer(bootstrap_servers='kafka:9092', security_protocol='PLAINTEXT', value_serializer=lambda m: json.dumps(m).encode('ascii')) result = producer.send('ktig', {'measure_i...
598
182
try: import uasyncio.core as asyncio except: import asyncio def cb(a, b): assert a == "test" assert b == "test2" loop.stop() loop = asyncio.get_event_loop() loop.call_soon(cb, "test", "test2") loop.run_forever() print("OK")
248
104
""" Provides a mock for the plx_gpib_ethernet package used in the Ando devices. """ from unittest.mock import Mock # The commands that are used in the methods of the # ANDO devices and typical responses. QUERY_COMMANDS = { # Spectrum Analyzer commands "*IDN?": "ANDO dummy\r\n", "SWEEP?": "0\r\...
1,491
749
import sys from inspect import getmembers, isclass from typing import Union from hearthstone.simulator.core.cards import MonsterCard from hearthstone.simulator.core.events import CardEvent, EVENTS, BuyPhaseContext, CombatPhaseContext from hearthstone.simulator.core.monster_types import MONSTER_TYPES class FloatingWa...
2,898
944
# -*- coding: utf-8 -*- """Scan views.""" from flask import Blueprint, render_template, flash, redirect, url_for, session from flask_login import current_user from .forms import ScanForm from .service import ScanService from cookiecutter_mbam.utils import flash_errors blueprint = Blueprint('scan', __name__, url_prefix...
1,026
321
import pytest import dbstore inMemFile = ":memory:" measurementTable = "measurements" alertTable = "alerts" def test_db_store_constructor(): s = dbstore.dbstore(file=inMemFile) assert(s != None) def test_dbStore_connect(): s = dbstore.dbstore(file=inMemFile) s.connect() assert s._connection i...
3,460
1,160
import importlib _NOTIFICATION_BACKENDS = None def load(modules): global _NOTIFICATION_BACKENDS; if _NOTIFICATION_BACKENDS == None: _NOTIFICATION_BACKENDS = dict() for backend in modules: backend = backend.strip() backend = getattr(importlib.import_module("Notifier.Bac...
446
142
import numpy as np import cv2 labels = ['dog', 'cat', 'panda'] np.random.seed(1) # Simulate model already trained W = np.random.randn(3, 3072) b = np.random.randn(3) orig = cv2.imread('beagle.png') image = cv2.resize(orig, (32, 32)).flatten() scores = W.dot(image) + b for (label, score) in zip(labels, scores): ...
604
257
import pandas as pd import numpy as np import matplotlib.pyplot as plt from .signal_processing import ( resample_data, normalize_signal, calculate_magnitude, calculate_offset_in_seconds_using_cross_correlation, calculate_sampling_frequency_from_timestamps, ) def get_synchronization_offset( vi...
2,759
872
s = 'vpoboooboboobooboboo' y = 0 counter = 0 times_run = 0 start = 0 end = 3 for letter in s: sc = s[start:end] start += 1 end += 1 if sc == str('bob'): counter += 1 print('Number of times bob occurs is: ', counter)
244
126
#! /usr/bin/env python2 # -*- coding: utf-8 -*- import random import unittest import sfml as sf class TestColor(unittest.TestCase): def random_color(self): return sf.Color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), ...
5,469
2,093
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: Word level augmentations including Replace words with uniform random words or TF-IDF based word replacement. """ import collections import copy import math import numpy as np from textgen.utils.log import logger min_token_num = 3 class Eff...
12,840
3,934
from . import three_D_resnet from .kernel import get_kernel_to_name def build_three_d_resnet(input_shape, output_shape, repetitions, output_activation, regularizer=None, squeeze_and_excitation=False, use_bottleneck=False, kernel_size=3, kernel_name='3D'): """Return a full customizable res...
6,539
2,012
from matplotlib import use use('WXAgg') import pylab as plt import numpy as np plt.figure(figsize=(8,5)) ax = plt.subplot(111) fil = './spectrum_GOME.out' data = np.loadtxt(fil) y = data[:,1] x = data[:,0] pl_list = [] pl, = ax.plot(x,y,'r') pl_list.append(pl) y = 10*data[:,3] pl, = ax.plot(x,y,'...
1,198
538
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-30 23:53 from __future__ import unicode_literals from django.db import migrations from tasks.models import BeneficiariesMatching def save_json_fields_again(apps, schema_editor): # Ugly but works for bf in BeneficiariesMatching.objects.all(): ...
569
217
""" An AWS Python3+Flask web app. """ from flask import Flask, redirect, url_for, request, session, flash, get_flashed_messages, render_template, escape from flask_oauthlib.client import OAuth import boto3,botocore import jinja2 from boto3.dynamodb.conditions import Key, Attr import urllib.request import json import c...
24,156
6,384
import json from newsapi import covid_news def news_test_one(): news_json = json.load(open('gb-news.json')) news:str = covid_news(news_json) assert news[0]['title'] != None
186
66
#!/usr/bin/env python3 # imports go here import atexit # # Free Coding session for 2015-02-10 # Written by Matt Warren # def clean_up(): print("CLEANING UP") @atexit.register def done(): print("DONE") if __name__ == '__main__': atexit.register(clean_up) try: import time while True:...
390
144
#!/usr/bin/env python # -*- coding: utf-8 -*- """ apscheduler. """ import subprocess from apscheduler.scheduler import Scheduler from apscheduler.jobstores.shelve_store import ShelveJobStore from datetime import date, datetime, timedelta import os import shelve import zmq from core.config.settings import logger de...
3,133
936
import warnings from .base import TorchFramework from .dqn import DQN from .dqn_per import DQNPer from .rainbow import RAINBOW from .ddpg import DDPG from .hddpg import HDDPG from .td3 import TD3 from .ddpg_per import DDPGPer from .a2c import A2C from .a3c import A3C from .ppo import PPO from .sac import SAC from ....
897
377
# Generated by Django 3.2.7 on 2021-09-24 02:31 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('preferences', '0002_auto_20210923_2348'), ('paper', '0007_auto_20210923_2353'), ] operations = [ mi...
575
217
# -*- coding: utf-8 -*- """The hashers CLI arguments helper.""" from plaso.cli import tools from plaso.cli.helpers import interface from plaso.cli.helpers import manager from plaso.lib import errors class HashersArgumentsHelper(interface.ArgumentsHelper): """Hashers CLI arguments helper.""" NAME = 'hashers' D...
2,925
833
# Generated by Django 3.1.5 on 2021-01-11 08:07 from django.db import migrations, models import django.db.models.deletion import django_mysql.models import utils.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
20,297
7,888
#!/usr/bin/env python """ Convert the output of Noise Cancelling Repeat Finder to bed format. """ from sys import argv,stdin,stdout,stderr,exit from os import path as os_path from ncrf_parse import alignments,parse_noise_rate def usage(s=None): message = """ usage: ncrf_cat <output_from_NCRF> | ncrf_...
2,098
926
# Copyright (c) 2018-present, Royal Bank of Canada. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import warnings import numpy as np import torch import torchvision.transforms.functional as F from advertorch.utils im...
2,551
934
from __future__ import division import itertools import matplotlib.pyplot as plt from matplotlib.pyplot import savefig import random from random import shuffle from collections import Counter def flatten_list(somelist): if any(isinstance(el, list) for el in somelist) == False: return somelist ...
5,595
1,792
from PyQt5.QtCore import pyqtSlot from channels.channel import Channel from operators.base import OutputOperator import numpy as np class DeviceOutput(OutputOperator): def __init__(self, input_ops, volume=1.0, name=None): super().__init__(input_ops, name) self.total_count = 0 self.stream =...
1,316
455
class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ # 左移 if n == 1: return True power = 0 flag = True while flag: val = 2 << power if val == n: return True ...
524
165
from celery.task import task from django.conf import settings from social_core.backends.utils import get_backend @task def post_social_media(user_social_auth, social_obj): backend = get_backend(settings.AUTHENTICATION_BACKENDS, user_social_auth.provider) backend.post(user_social_auth, social_obj)
308
97
#pathList = [ #"/global/project/projectdirs/als/spade/warehouse/als/bl832/phosemann/20160512_092220_tensile7_T700_240mic/raw/20160512_092220_tensile7_T700_240mic.h5", #"/global/project/projectdirs/als/spade/warehouse/als/bl832/phosemann/20160512_085327_tensile7_T700_200mic/raw/20160512_085327_tensile7_T700_200mic.h...
7,753
5,703
import asyncio import json import discord from discord.ext import commands, tasks from discal.bot import Bot from datetime import datetime, timedelta from discal.logger import get_module_logger logger = get_module_logger(__name__) class Handler(commands.Cog): def __init__(self, bot): self.bot: Bot = bot...
3,870
1,167
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (c) 2015 David I. Urbina, david.urbina@utdallas.edu # # 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...
2,738
948
def merge_sort(arr): if len(arr) > 1: middle = len(arr) // 2 lefthalf = arr[:middle] righthalf = arr[middle:] merge_sort(lefthalf) merge_sort(righthalf) i = j = k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]:...
1,103
414
from django.db import models class ContentBlock(models.Model): """ A simple block of HTML content that can be used by various sections of the site based on the provided name, which acts as a key. """ name = models.CharField(max_length=64) content = models.TextField(blank=True) def __...
418
120
# -*- coding: utf-8 -*- # URI Judge - Problema 1017 tempo = int(input()) velocidade = int(input()) litros = (velocidade / 12.0) * tempo print("%.3f" % litros)
162
75
''' Date: 2021-08-10 17:17:35 LastEditors: Liuliang LastEditTime: 2021-08-10 18:27:56 Description: ''' import random import sys sys.path.append("..") from bacic_module.random_int_list import random_int_list def partition(nums, left, right): tmp = nums[left] while left < right: while left<right a...
765
319
import os import json def create_json_CYC_envs(root_dir): DI_ROOT = root_dir CYC_ROOT = "%s/CyclopsVFX" % DI_ROOT DATA_FILENAME = os.path.join(CYC_ROOT, "CYC_envs.json") CYC_HYDRA_PATH = "%s/Hydra" % (CYC_ROOT) CYC_HYDRA_CACHE = "%s/Hydra/cache" % (CYC_ROOT) CYC_CORE_PATH = "%s/Core/...
2,144
1,042
import unittest import drawzero class ColorTest(unittest.TestCase): def test_wrong_color(self): self.assertRaises(TypeError, drawzero._make_color, '#abcd') self.assertRaises(TypeError, drawzero._make_color, 'dummy') self.assertRaises(TypeError, drawzero._make_color, '#aabbZZ') self...
956
346
import numpy as np from fedot.api.api_utils.api_data import ApiDataProcessor from fedot.api.api_utils.api_data_analyser import DataAnalyser from fedot.api.main import Fedot from fedot.core.data.data import InputData from fedot.core.repository.dataset_types import DataTypesEnum from fedot.core.repository.tasks import T...
4,143
1,299
from multiprocessing import cpu_count, Manager, Process from time import sleep class Parallelizer: def __init__( self, *, target: 'function', args: list, enable_results: bool, auto_proc_count: bool, max_proc_count: int): ...
7,765
2,049
# # SFA XML-RPC and SOAP interfaces # import sys import os import traceback import string import xmlrpclib import sfa.util.xmlrpcprotocol as xmlrpcprotocol from sfa.util.sfalogging import logger from sfa.trust.auth import Auth from sfa.util.config import * from sfa.util.faults import * from sfa.util.cache import Cache...
9,781
2,808
__author__ = 'rknight' import os import csv import logging import datetime from requests_futures.sessions import FuturesSession def dl(reports, dlkeys): # Primary call # Send requests allreports = dlrequest(reports=reports, dlkeys=dlkeys) # Write results for outreport in allreports.keys(): ...
9,507
2,801
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from anchore_engine.services.policy_engine.api.models.base_model_ import Model from anchore_engine.services.policy_engine.api import util class Image(Model): """N...
7,210
2,197
"""Module for machine learning models.""" from dataclasses import dataclass from typing import Any, Optional, Union import numpy as np import pandas as pd from bayes_opt import BayesianOptimization from catboost import CatBoostClassifier from sklearn.discriminant_analysis import ( LinearDiscriminantAnalysis, ...
28,531
8,597
#!/usr/bin/env python3 # The MIT License (MIT) # # Copyright (c) 2015 Lucas Koegel # # 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 limitation the ri...
7,603
2,568
import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Ellipse NUM = 250 ells = [Ellipse(xy=np.random.rand(2) * 10, width=np.random.rand(), height=np.random.rand(), angle=np.random.rand() * 360) for i in range(NUM)] fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}) for e in ells: ...
480
221
from enum import Enum class Formation(Enum): LINE_AHEAD = 0 # 単縦陣 DOUBLE_LINE = 1 # 複縦陣 DIAMOND = 2 # 輪形陣 ECHELON = 3 # 梯形陣 LINE_ABREAST = 4 # 単横陣 FORMATION_3 = 5 # 第3陣形(第三警戒航行序列(輪形陣))
231
162
#import OpenStack connection class from the SDK from openstack import connection # Create a connection object by calling the constructor and pass the security information conn = connection.Connection(auth_url="http://192.168.0.106/identity", project_name="demo", username="admin", password="manoj", user_domain_id="defa...
638
177
from sympy import * import pandas as pd def bisection(xl, xu, tolerance, function): x = Symbol('x') f = parse_expr(function) iteration = 0 data = pd.DataFrame(columns=['iteration','xl','xu','xr','f(xl)','f(xu)','f(xr)','f(xl)f(xr)','error']) while abs(xu-xl)>=tolerance: xr = (xl + xu)/2 ...
849
395
"""Main module for operating on crypted/encoded strings in Geometry Dash""" from gd.utils.crypto.coders import Coder from gd.utils.crypto.xor_cipher import XORCipher as xor
176
61
from pid import PID import pdb #for anonymous objects Object = lambda **kwargs: type("Object", (), kwargs) class MotorController: def __init__(self, wheelBase,numberOfMotors): self.pidControllerFrontLeft = PID() self.pidControllerFrontRight = PID() self.pidControllerRearLeft = PID() ...
3,684
1,118
import tkinter as tk from tkinter import filedialog from tkinter import messagebox from tkinter import scrolledtext from tkinter import ttk import tkcalendar as tkc from shiftscheduler.data_types import data_types from shiftscheduler.excel import output as excel_output from shiftscheduler.gui import constants from ...
4,931
1,741
# Generated by Django 2.1.5 on 2019-01-26 19:42 import datetime from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Order', fields=[ ('id', mod...
1,093
329
from setuptools import setup, find_packages setup( name='selfstoredict', version='0.6', packages=find_packages(), url='https://github.com/markus61/selfstoredict', license='MIT', author='markus', author_email='ms@dom.de', description='a python class delivering a dict that stores itself in...
353
110
def add(*args): c = 0 for n in args: c += n return c sum = add(2,5,6,5) print(sum) def calculate(**kwargs): print(kwargs) calculate(add=3, mul=5) class Car: def __init__(self, **kw): # self.make = kw["make"] # self.model = kw["model"] self.ma...
428
181
# -*- coding: utf-8 -*- import os import sys import logging import json from urllib import urlencode import urlparse # for CSRF state tokens import time import base64 # Get available json parser try: # should be the fastest on App Engine py27. import json except ImportError: try: import simplejson as json ...
21,406
6,957
#!/usr/bin/env python3 from __future__ import print_function import os import pythondata_cpu_ibex print("Found ibex @ version", pythondata_cpu_ibex.version_str, "(with data", pythondata_cpu_ibex.data_version_str, ")") print() print("Data is in", pythondata_cpu_ibex.data_location) assert os.path.exists(pythondata_cp...
766
302
"""LAPKT-BFWS https://github.com/nirlipo/BFWS-public """ import re import os import sys import subprocess import tempfile from pddlgym_planners.pddl_planner import PDDLPlanner from pddlgym_planners.planner import PlanningFailure import numpy as np from utils import FilesInCommonTempDirectory DOCKER_IMAGE = 'khodeir/b...
2,652
880
import csv import re import sys import requests import json import Data # data container, replace with your own orgName = Data.orgName # replace with your own apiKey = Data.apiKey # provide your own API token api_token = "SSWS " + apiKey headers = {'Accept': 'application/json', 'Content-Type': 'application...
1,914
520
import random import PySimpleGUI as sg class SimuladorDeDado: def __init__(self): self.valor_minimo = 1 self.valor_maximo = 6 self.layout = [ [sg.Text("Jogar o dado?")], [sg.Button("Sim"),sg.Button("Não")] ] def Iniciar(self): self.janela = sg.W...
959
329
import math from typing import List, Iterable, Union Numeric = Union[int, float] def magnitude(p: Iterable[Numeric]) -> float: res: float = 0 for component in p: res += component ** 2 res = math.sqrt(res) return res def vdot(p: List[Numeric], q: List[Numeric]) -> float: "...
1,712
643
# Written 9/10/14 by dh4gan # Code reads in output eigenvalue file from tache # Computes statistics import numpy as np import matplotlib.pyplot as plt import io_tache as io # Read in inputs from command line filename = ff.find_local_input_files('eigenvalues*') threshold = input("What is the threshold for classificat...
1,231
456
from django.views.generic.edit import CreateView, FormMixin from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django import forms from django.urls import reverse from reportlab.pdfgen import canvas from django.http import HttpResponse from forwarder.models import A...
4,179
1,257
import h5py # torch imports import torch from torch.utils.data import Dataset # generic imports import os import sys import numpy as np import random import pandas as pd import cv2 from decord import VideoReader from decord import cpu, gpu from matplotlib import pyplot as plt import gc # create data loader class ...
4,793
1,544
""" @file: sklearn_method.py @time: 2020-12-09 17:38:38 """ import pandas as pd import seaborn as sns from tqdm import tqdm from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import...
1,583
579
import tempfile from django.conf import settings from django.contrib.auth.models import User from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase from filer.models import Image from handypackages.tag.models import Tag from .models import Gallery class TestGalleryModels(Tes...
2,087
553
import os import typing import jk_typing from .ProcessFilter import ProcessFilter class WikiCronProcessFilter(ProcessFilter): ################################################################################################################################ ## Constructor ###############################...
1,926
498
/home/runner/.cache/pip/pool/ab/0b/2c/7ae80e56fd2208fbee5ef317ac009972f468b5601f62f8f799f9d9279a
96
73
""" Loader and Parser for the xml format. Version: 0.01-alpha """ from xml.dom import minidom from konbata.Data.Data import DataNode, DataTree from konbata.Formats.Format import Format def xml_toTree(file, delimiter, options=None): """ Function transforms a xml file into a DataTree. Parameters ...
2,094
666
#!/usr/env python import pandas as pd import os import sys import numpy as np if len(sys.argv) != 3: sys.exit('[usage] python %s <repeat_index table> <indel cutoff>') ref_table = sys.argv[1] indel_cut_off = int(sys.argv[2]) for gdf in pd.read_csv(ref_table, sep='\t', chunksize = 10000): for contig, contig...
1,650
512
class Solution(object): def findMaxForm(self, strs, m, n): """ :type strs: List[str] :type m: int :type n: int :rtype: int """ dp = [[0] * (n + 1) for _ in range(m + 1)] def counts(s): return sum(1 for c in s if c == '0'), \ ...
662
246
# -*- coding: utf-8 -*- """ .. Authors: Novimir Pablant <npablant@pppl.gov> Define the :class:`InteractNone` class. """ import numpy as np from copy import deepcopy from xicsrt.tools.xicsrt_doc import dochelper from xicsrt.optics._InteractObject import InteractObject @dochelper class InteractNone(InteractObject...
474
157
def ficha(nome, gols): if gols.isnumeric(): gols = int(gols) else: gols = 0 if nome.strip() != '': print(f'O jogador {nome} fez {gols} gol(s) no campeonato.') else: nome = '<desconhecido>' print(f'O jogador {nome} fez {gols} gol(s) no campeonato.') print('='*30)...
416
172
#!/usr/bin/env python """ ZMQ Subscriber for 1602 display Queue: INF and CMD """ import wiringpi2 as wiringpi import datetime import time import json import Adafruit_DHT import traceback import zmq import sys import pprint infoSocket = "tcp://localhost:5550" cmdSocket = "tcp://localhost:5560" wiringpi.wiringPiSetu...
3,598
1,347
from typing import List, Dict from fastapi import APIRouter, UploadFile, File, Depends, HTTPException from pydantic import create_model from starlette.responses import StreamingResponse from app.business_layers.domain import Work from app.business_layers.repository import WorkRepository from app.business_layers.use_c...
2,079
663
from essentials_kit_management.interactors.storages.storage_interface \ import StorageInterface from essentials_kit_management.interactors.presenters.presenter_interface \ import PresenterInterface class GetPayThroughDetailsInteractor: def __init__( self, storage: StorageInterface, presenter: ...
651
185
import FWCore.ParameterSet.Config as cms from RecoEgamma.EgammaElectronProducers.gsfElectronSequence_cff import * from RecoEgamma.EgammaElectronProducers.uncleanedOnlyElectronSequence_cff import * from RecoEgamma.EgammaPhotonProducers.photonSequence_cff import * from RecoEgamma.EgammaPhotonProducers.conversionSequence...
5,287
2,027
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 ...
3,632
1,065
import json import pprint from urllib.request import urlopen with urlopen('http://pypi.python.org/pypi/Twisted/json') as url: http_info = url.info() raw_data = url.read().decode(http_info.get_content_charset()) project_info = json.loads(raw_data) pprint.pprint(project_info) print('-----------------------------...
449
160
from argparse import Namespace from functools import partial from typing import Any import molotov from .formatters import DefaultFormatter from .record_table import RecordTable from .recorder import Recorder from .reporter import Reporter from .scenario import Scenario __all__ = ("Reporter", "register_reporter", "s...
1,323
395
from slugify import slugify from services.viewcounts.models import PageViewsModel def get_page_views(url: str): """Returns the number of views for a given page object.""" # Pre-processing checks: Client should not pass full or partial URL. if not url.startswith("/"): raise Exception("Partial URL...
936
291
import tensorflow as tf import tensorflow_probability as tfp from scipy.stats import expon from videos.linalg import safe_cholesky from manim import * # shortcuts tfd = tfp.distributions kernels = tfp.math.psd_kernels def default_float(): return "float64" class State: def __init__(self, kernel, x_grid, x...
9,875
3,635
""" This module defines the base model and associated functions """ from flask import Flask, jsonify from psycopg2.extras import RealDictCursor from ....database import db_con class BaseModels(object): """ This class encapsulates the functions of the base model that will be shared across all other models...
932
256
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # ================================================================================================ # # Project : Deep Learning for Conversion Rate Prediction (CVR) # # Version : 0.1.0 ...
9,288
2,344
from typing import Set from numpy import ndarray class Matroid: def is_independent(self, s: Set) -> bool: raise NotImplementedError @property def rank(self) -> int: raise NotImplementedError @property def matrix(self) -> ndarray: raise NotImplementedError
304
93
"""traits/traitcommon.py - Common functionality across trait operations.""" import re from ..constants import UNIVERSAL_TRAITS VALID_TRAIT_PATTERN = re.compile(r"^[A-z_]+$") def validate_trait_names(*traits): """ Raises a ValueError if a trait doesn't exist and a SyntaxError if the syntax is bad. ""...
779
266
class MessageType(object): REG = 1 class Message(object): def __init__(self): self.type = None self.body = None def get_type(self): return self.type def get_body(self): return self.body def set_type(self, type): self.type = type def set_body(self, bod...
349
114
import unittest from ..model import RandomForestWithFeatureSelection from sklearn.model_selection import train_test_split import os import numpy as np def create_dataset(n_rows=1000, n_feats=10, pos_loc=2.0, neg_loc=0.0, pos_scale=3.0, neg_scale=3.0, random_state=1): np.random.seed(random_state...
2,293
830
import matplotlib.pyplot as plt; plt.rcdefaults() import csv import sqlite3 as lite from calendar import monthrange from datetime import datetime, date, timedelta from datetimerange import DateTimeRange import numpy as np import pycountry_convert as pc from dateutil.relativedelta import relativedelta from forex_pytho...
43,051
13,681
from flask import Flask, render_template, request, jsonify import numpy as np import pickle import sys import json import re app = Flask(__name__) app.config['JSON_AS_ASCII'] = False target_names = [ 'AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'OM','PL', 'QA', ...
1,733
850