code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import logging from flask import request, abort as flask_abort from werkzeug.exceptions import HTTPException from webargs import core from webargs.core import text_type logger = logging.getLogger(__name__) def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any...
webargs/flaskparser.py
import logging from flask import request, abort as flask_abort from werkzeug.exceptions import HTTPException from webargs import core from webargs.core import text_type logger = logging.getLogger(__name__) def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any...
0.601594
0.080647
import requests import json import datetime import time import os def main(): print(""" _______ _______ _______ _______ _ _________ ( )( ____ \( ____ )( ___ )| \ /\\__ __/ | () () ||...
MerakiAPIGet.py
import requests import json import datetime import time import os def main(): print(""" _______ _______ _______ _______ _ _________ ( )( ____ \( ____ )( ___ )| \ /\\__ __/ | () () ||...
0.097106
0.084758
from flask import Flask, request, jsonify from utils.nodefinder import node_finder from utils.simulator import car_mover, simulator from entities.carpool import Carpool from entities.user import User from entities.car import Car from threading import Thread from utils.bluetooth.serial_connection import SerialConnection...
server/main.py
from flask import Flask, request, jsonify from utils.nodefinder import node_finder from utils.simulator import car_mover, simulator from entities.carpool import Carpool from entities.user import User from entities.car import Car from threading import Thread from utils.bluetooth.serial_connection import SerialConnection...
0.491944
0.165593
import argparse from utils.BaseFlags import parser as parser # DATASET NAME parser.add_argument('--dataset', type=str, default='CelebA', help="name of the dataset") # add arguments parser.add_argument('--style_img_dim', type=int, default=32, help="dimension of varying factor latent space") parser.add_argument('--styl...
celeba/flags.py
import argparse from utils.BaseFlags import parser as parser # DATASET NAME parser.add_argument('--dataset', type=str, default='CelebA', help="name of the dataset") # add arguments parser.add_argument('--style_img_dim', type=int, default=32, help="dimension of varying factor latent space") parser.add_argument('--styl...
0.616243
0.046747
import os, sys, re print("Building all_exercises_challenges.html...") path_to_notebooks = '/srv/projects/intro_programming/intro_programming/notebooks/' # Work through notebooks in the order listed here. filenames = ['var_string_num.html', 'lists_tuples.html', 'introducing_functions.html', 'if_statemen...
scripts/build_all_exercises_page.py
import os, sys, re print("Building all_exercises_challenges.html...") path_to_notebooks = '/srv/projects/intro_programming/intro_programming/notebooks/' # Work through notebooks in the order listed here. filenames = ['var_string_num.html', 'lists_tuples.html', 'introducing_functions.html', 'if_statemen...
0.396652
0.216115
## ========================== Import libraries ================================= import json import csv import os ## =========================== Useful classes ================================== class Daemon: '''Fields: daemon, card_desc, skill_name, skill_desc, skill_quote, summon_quote, lb_quote,...
sola.py
## ========================== Import libraries ================================= import json import csv import os ## =========================== Useful classes ================================== class Daemon: '''Fields: daemon, card_desc, skill_name, skill_desc, skill_quote, summon_quote, lb_quote,...
0.291384
0.125065
from django import newforms as forms from django.utils.datastructures import MultiValueDict from django.utils.text import capfirst, truncate_words from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_unicode from django.conf import sett...
django/contrib/admin/widgets.py
from django import newforms as forms from django.utils.datastructures import MultiValueDict from django.utils.text import capfirst, truncate_words from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_unicode from django.conf import sett...
0.409457
0.168139
import tensorflow as tf import numpy as np from utils.utils import load_data, preprocess_features, preprocess_adj_bias, adj_to_bias from .models import GAT def train(model, inputs, bias_mat, lbl_in, msk_in, optimizer): with tf.GradientTape() as tape: logits, accuracy, loss = model(inputs=inputs, training=...
algorithms/gat/gat.py
import tensorflow as tf import numpy as np from utils.utils import load_data, preprocess_features, preprocess_adj_bias, adj_to_bias from .models import GAT def train(model, inputs, bias_mat, lbl_in, msk_in, optimizer): with tf.GradientTape() as tape: logits, accuracy, loss = model(inputs=inputs, training=...
0.781289
0.571826
import re import os import glob import numpy as np from tqdm import tqdm import torch import torch.nn.functional as F import torchvision.models as models use_gpu = True cuda_available = torch.cuda.is_available() device = torch.device("cuda" if (cuda_available and use_gpu) else "cpu") from utils import to_var from mo...
PyTorch/predict_utilsMulti.py
import re import os import glob import numpy as np from tqdm import tqdm import torch import torch.nn.functional as F import torchvision.models as models use_gpu = True cuda_available = torch.cuda.is_available() device = torch.device("cuda" if (cuda_available and use_gpu) else "cpu") from utils import to_var from mo...
0.6705
0.454048
from selenium import webdriver import time import selenium.webdriver.support.ui as ui #shift-tab多行缩进(左) print 'please wait...system loading...' PostUrl = "https://www.douban.com/" driver=webdriver.Chrome()#用浏览器实现访问 driver_detail=webdriver.PhantomJS() wait = ui.WebDriverWait(driver,15) wait1 = ui.WebDriverWait(driver_de...
MrLevo520-豆瓣数据爬取与分析/furtherProject/cowboy231-DouBan/work9/work9.py
from selenium import webdriver import time import selenium.webdriver.support.ui as ui #shift-tab多行缩进(左) print 'please wait...system loading...' PostUrl = "https://www.douban.com/" driver=webdriver.Chrome()#用浏览器实现访问 driver_detail=webdriver.PhantomJS() wait = ui.WebDriverWait(driver,15) wait1 = ui.WebDriverWait(driver_de...
0.051427
0.064418
from django.test.simple import DjangoTestSuiteRunner from django.conf import settings from . import loading from ...exceptions import ResourceNotFound class CouchDbKitTestSuiteRunner(DjangoTestSuiteRunner): """ A test suite runner for couchdbkit. This offers the exact same functionality as the default d...
couchdbkit/ext/django/testrunner.py
from django.test.simple import DjangoTestSuiteRunner from django.conf import settings from . import loading from ...exceptions import ResourceNotFound class CouchDbKitTestSuiteRunner(DjangoTestSuiteRunner): """ A test suite runner for couchdbkit. This offers the exact same functionality as the default d...
0.388502
0.180974
from json import dumps as json_encode from aws_cdk import ( core, aws_ec2 as ec2, aws_iam as iam, aws_neptune as neptune, aws_s3_assets as s3_assets, ) class Instance(core.Construct): def __init__( self, scope: core.Construct, id: str, vpc: ec2.IVpc, cluster: neptune.C...
neptune/app.py
from json import dumps as json_encode from aws_cdk import ( core, aws_ec2 as ec2, aws_iam as iam, aws_neptune as neptune, aws_s3_assets as s3_assets, ) class Instance(core.Construct): def __init__( self, scope: core.Construct, id: str, vpc: ec2.IVpc, cluster: neptune.C...
0.505371
0.067454
import os, math from PySide2 import QtCore, QtWidgets, QtGui, QtUiTools from PySide2.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsEllipseItem, QGraphicsPixmapItem from PySide2.QtCore import Qt, QPointF from PIL import Image __copyright__ = 'Copyright © 2020 mmiikeke - All Right Reserved.' PA...
user_interface/page_widget.py
import os, math from PySide2 import QtCore, QtWidgets, QtGui, QtUiTools from PySide2.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsEllipseItem, QGraphicsPixmapItem from PySide2.QtCore import Qt, QPointF from PIL import Image __copyright__ = 'Copyright © 2020 mmiikeke - All Right Reserved.' PA...
0.474144
0.095771
from collections import namedtuple import tensorflow as tf import tensorflow_probability as tfp from gemlib.mcmc.occult_proposal import AddOccultProposal, DelOccultProposal tfd = tfp.distributions OccultKernelResults = namedtuple( "OccultKernelResults", ( "log_acceptance_correction", "target...
gemlib/mcmc/occult_events_mh.py
from collections import namedtuple import tensorflow as tf import tensorflow_probability as tfp from gemlib.mcmc.occult_proposal import AddOccultProposal, DelOccultProposal tfd = tfp.distributions OccultKernelResults = namedtuple( "OccultKernelResults", ( "log_acceptance_correction", "target...
0.93402
0.309043
import os from flask import Flask, redirect, render_template, request from google.cloud import storage from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types app = Flask(__name__) @app.route('/') def homepage(): # Return a Jinja2 HTML template and pass in i...
speech/main.py
import os from flask import Flask, redirect, render_template, request from google.cloud import storage from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types app = Flask(__name__) @app.route('/') def homepage(): # Return a Jinja2 HTML template and pass in i...
0.651577
0.15109
import argparse import functools import inspect import sys import unittest _use_native_pytest = False def enable_pytest(): global _use_native_pytest, pytest assert not _fallback import pytest _use_native_pytest = True def fixture(scope="function", params=None, autouse=False, ids=None, name=None): ...
resources/Wireshark/WiresharkDissectorFoo/test/fixtures.py
import argparse import functools import inspect import sys import unittest _use_native_pytest = False def enable_pytest(): global _use_native_pytest, pytest assert not _fallback import pytest _use_native_pytest = True def fixture(scope="function", params=None, autouse=False, ids=None, name=None): ...
0.55941
0.349089
import os, re import numpy as np import matplotlib.pyplot as plt debug = True def compute_rcr_parameters(area, Q_goal, P_min, P_max, P_mean, Q_mean, ratio_prox_to_distal_resistors, decay_time, C_prefactor=1.0): tol = 1e-12 # total resistances R_total = [] for Q in Q_goal: R_total.append(P...
compute_rcr_values.py
import os, re import numpy as np import matplotlib.pyplot as plt debug = True def compute_rcr_parameters(area, Q_goal, P_min, P_max, P_mean, Q_mean, ratio_prox_to_distal_resistors, decay_time, C_prefactor=1.0): tol = 1e-12 # total resistances R_total = [] for Q in Q_goal: R_total.append(P...
0.364664
0.503174
import time, random import numpy as np # User from tbscm.utils import data from tbscm.synthetic_controls import SyntheticControl as SC from tbscm.synthetic_controls import TreeBasedSyntheticControl as TBSC from tbscm.synthetic_controls import ElasticNetSyntheticControl as ENSC #---------------------------------------...
src/readme_demo.py
import time, random import numpy as np # User from tbscm.utils import data from tbscm.synthetic_controls import SyntheticControl as SC from tbscm.synthetic_controls import TreeBasedSyntheticControl as TBSC from tbscm.synthetic_controls import ElasticNetSyntheticControl as ENSC #---------------------------------------...
0.495606
0.291321
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from model_predict import read_xmls, get_target_image_paths, InputData, EvalSummary correct_index_map = { "763a8z0136b6aae04_20181218_042832_-329078_380494.jpg": 0, "763a8z0136...
research/object_detection/model_predict_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from model_predict import read_xmls, get_target_image_paths, InputData, EvalSummary correct_index_map = { "763a8z0136b6aae04_20181218_042832_-329078_380494.jpg": 0, "763a8z0136...
0.430866
0.286649
import glob import pandas as pd import argparse import networkx as nx from pathlib import Path def construct_network(states, minimum_weight, output): if states is None: # fmt: off STATES = [ "ak", "al", "ar", "az", "ca", "co", "ct", "dc", "de", "fl", "ga", "hi", "ia", "id",...
construct_block_network.py
import glob import pandas as pd import argparse import networkx as nx from pathlib import Path def construct_network(states, minimum_weight, output): if states is None: # fmt: off STATES = [ "ak", "al", "ar", "az", "ca", "co", "ct", "dc", "de", "fl", "ga", "hi", "ia", "id",...
0.345436
0.360827
import random import uuid from unittest.mock import Mock, PropertyMock, patch import pytest from common_test_utils import MockS3 from braket.aws import AwsQuantumTaskBatch, AwsSession from braket.circuits import Circuit from braket.tasks import GateModelQuantumTaskResult S3_TARGET = AwsSession.S3DestinationFolder("...
test/unit_tests/braket/aws/test_aws_quantum_task_batch.py
import random import uuid from unittest.mock import Mock, PropertyMock, patch import pytest from common_test_utils import MockS3 from braket.aws import AwsQuantumTaskBatch, AwsSession from braket.circuits import Circuit from braket.tasks import GateModelQuantumTaskResult S3_TARGET = AwsSession.S3DestinationFolder("...
0.723993
0.506836
from rest_framework.test import APIClient from django.core import mail from django.contrib.auth.models import User from drinks.models import UserIngredient, Ingredient, Book, BookUser, Profile from django.utils.timezone import now from .base import BaseTestCase class UserTestCase(BaseTestCase): def test_list_user...
api/drinks/tests/users.py
from rest_framework.test import APIClient from django.core import mail from django.contrib.auth.models import User from drinks.models import UserIngredient, Ingredient, Book, BookUser, Profile from django.utils.timezone import now from .base import BaseTestCase class UserTestCase(BaseTestCase): def test_list_user...
0.436862
0.139572
import numpy as np import torch import torch.nn as nn from tests.nn import test_constants from tharsis.nn import helper def test_layer_norm(): input_x = torch.randn( test_constants.N_BATCH, test_constants.N_SEQ, test_constants.N_INPUT) layer_norm_machine = helper.LayerNorm(...
tests/nn/test_helper.py
import numpy as np import torch import torch.nn as nn from tests.nn import test_constants from tharsis.nn import helper def test_layer_norm(): input_x = torch.randn( test_constants.N_BATCH, test_constants.N_SEQ, test_constants.N_INPUT) layer_norm_machine = helper.LayerNorm(...
0.753739
0.749798
from touchdown import ssh from touchdown.aws.ec2.keypair import KeyPair from touchdown.aws.iam import InstanceProfile from touchdown.aws.vpc import SecurityGroup, Subnet from touchdown.core import argument, errors, serializers from touchdown.core.plan import Plan, Present from touchdown.core.resource import Resource ...
touchdown/aws/ec2/instance.py
from touchdown import ssh from touchdown.aws.ec2.keypair import KeyPair from touchdown.aws.iam import InstanceProfile from touchdown.aws.vpc import SecurityGroup, Subnet from touchdown.core import argument, errors, serializers from touchdown.core.plan import Plan, Present from touchdown.core.resource import Resource ...
0.52756
0.111
from poppy.model import common AVAILABLE_PROTOCOLS = [ u'http', u'https' ] CERTIFICATE_OPTIONS = [ None, u'shared', u'san', u'sni', u'custom' ] class Domain(common.DictSerializableModel): def __init__(self, domain, protocol='http', certificate=None): self._...
poppy/model/helpers/domain.py
from poppy.model import common AVAILABLE_PROTOCOLS = [ u'http', u'https' ] CERTIFICATE_OPTIONS = [ None, u'shared', u'san', u'sni', u'custom' ] class Domain(common.DictSerializableModel): def __init__(self, domain, protocol='http', certificate=None): self._...
0.821796
0.190969
from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfConfigTDPLevelConsts: VP_CONFIG_TDPLEVEL_LEVEL_1 = "Level 1" VP_CONFIG_TDPLEVEL_LEVEL_2 = "Level 2" VP_CONFIG_TDPLEVEL_NORMAL = "Normal" VP_CONFIG_TDPLEVEL_PLATFORM_DEFA...
imcsdk/mometa/bios/BiosVfConfigTDPLevel.py
from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfConfigTDPLevelConsts: VP_CONFIG_TDPLEVEL_LEVEL_1 = "Level 1" VP_CONFIG_TDPLEVEL_LEVEL_2 = "Level 2" VP_CONFIG_TDPLEVEL_NORMAL = "Normal" VP_CONFIG_TDPLEVEL_PLATFORM_DEFA...
0.41834
0.222236
import struct def read_uchar(bytes, idx): val = struct.unpack_from(">B", bytes, idx) return val[0], idx + 1 def read_schar(bytes, idx): val = struct.unpack_from(">b", bytes, idx) return val[0], idx + 1 def read_uword(bytes, idx): val = struct.unpack_from(">H", bytes, idx) return val[0], idx +...
src/python/editor/rom.py
import struct def read_uchar(bytes, idx): val = struct.unpack_from(">B", bytes, idx) return val[0], idx + 1 def read_schar(bytes, idx): val = struct.unpack_from(">b", bytes, idx) return val[0], idx + 1 def read_uword(bytes, idx): val = struct.unpack_from(">H", bytes, idx) return val[0], idx +...
0.375248
0.29381
import numpy as np def rotation_matrix_to_quaternion(rotation): print(rotation.shape) print("dtype of rotation:{}".format(rotation.dtype)) trace = rotation[0, 0] + rotation[1, 1] + rotation[2, 2] s, w, x, y, z = 0.0, 0.0, 0.0, 0.0, 0.0 print("trace: {}".format(trace)) print("type of trace:{}".f...
datasets/test_quaternion.py
import numpy as np def rotation_matrix_to_quaternion(rotation): print(rotation.shape) print("dtype of rotation:{}".format(rotation.dtype)) trace = rotation[0, 0] + rotation[1, 1] + rotation[2, 2] s, w, x, y, z = 0.0, 0.0, 0.0, 0.0, 0.0 print("trace: {}".format(trace)) print("type of trace:{}".f...
0.260013
0.664772
from logging import getLogger from time import sleep from typing import Dict, List, Optional, Any from uuid import uuid4 import requests from azul import config logger = getLogger(__name__) class CollectionDataAccess: DEFAULT_MAX_BACKOFF_TIME = 60 def __init__(self, access_token:str): self.access_to...
src/azul/service/responseobjects/collection_data_access.py
from logging import getLogger from time import sleep from typing import Dict, List, Optional, Any from uuid import uuid4 import requests from azul import config logger = getLogger(__name__) class CollectionDataAccess: DEFAULT_MAX_BACKOFF_TIME = 60 def __init__(self, access_token:str): self.access_to...
0.678647
0.062303
import xml.etree.ElementTree as ET from .gateway import * CARTS_RESOURCE = "http://ec2-52-4-244-64.compute-1.amazonaws.com/konkershop/api/carts/" FIND_LAST_CART_TEMPLATE = CARTS_RESOURCE + "?filter[id_customer]=%s&sort=[id_DESC]&limit=1" GET_LAST_CART_TEMPLATE = CARTS_RESOURCE + "%s" def add_to_cart(customer_code,pro...
konker.samples/prestashop-cart-orchestrator/prestashop/repositories/carts.py
import xml.etree.ElementTree as ET from .gateway import * CARTS_RESOURCE = "http://ec2-52-4-244-64.compute-1.amazonaws.com/konkershop/api/carts/" FIND_LAST_CART_TEMPLATE = CARTS_RESOURCE + "?filter[id_customer]=%s&sort=[id_DESC]&limit=1" GET_LAST_CART_TEMPLATE = CARTS_RESOURCE + "%s" def add_to_cart(customer_code,pro...
0.213869
0.071819
from itertools import product import pytest import numpy as np from pypetting import ( GridSite, aspirate, dispense, mix, wash, move_liha, ) from pypetting.liha import _well_select FIRST = np.array([True] + 7 * [False]) COL96 = np.array(8 * [True]) grid_site = GridSite(40, 0, "MP 3Pos") LI...
test/test_liha.py
from itertools import product import pytest import numpy as np from pypetting import ( GridSite, aspirate, dispense, mix, wash, move_liha, ) from pypetting.liha import _well_select FIRST = np.array([True] + 7 * [False]) COL96 = np.array(8 * [True]) grid_site = GridSite(40, 0, "MP 3Pos") LI...
0.557845
0.571049
import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup from .exceptions import BadRequestError def get_stations(): url = 'https://coagmet.colostate.edu/station_index.php' response = requests.get(url) soup = BeautifulSoup(response.text, features='lxml') table = soup.find...
coagmet/stations.py
import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup from .exceptions import BadRequestError def get_stations(): url = 'https://coagmet.colostate.edu/station_index.php' response = requests.get(url) soup = BeautifulSoup(response.text, features='lxml') table = soup.find...
0.367157
0.238146
import operator from typing import Callable, Iterable, Sequence, Tuple, TypeVar from pants.base.deprecated import deprecated _T = TypeVar("_T") Filter = Callable[[_T], bool] def _extract_modifier(modified_param: str) -> Tuple[Callable[[bool], bool], str]: if modified_param.startswith("-"): return opera...
src/python/pants/util/filtering.py
import operator from typing import Callable, Iterable, Sequence, Tuple, TypeVar from pants.base.deprecated import deprecated _T = TypeVar("_T") Filter = Callable[[_T], bool] def _extract_modifier(modified_param: str) -> Tuple[Callable[[bool], bool], str]: if modified_param.startswith("-"): return opera...
0.906983
0.454714
from itertools import chain, count from typing import Optional from autofit.mapper.model_object import ModelObject class Plate: _ids = count() def __init__( self, name: Optional[str] = None ): """ Represents a dimension, such as number of observation...
autofit/mapper/variable.py
from itertools import chain, count from typing import Optional from autofit.mapper.model_object import ModelObject class Plate: _ids = count() def __init__( self, name: Optional[str] = None ): """ Represents a dimension, such as number of observation...
0.909611
0.158337
import time import requests import numpy as np import pandas as pd from tradingfeatures import apiBase class bitfinexBase(apiBase): def __init__(self): super(bitfinexBase, self).__init__( name = 'bitfinex', per_step = 120, sleep = 0.5, ) self.base_add...
tradingfeatures/apis/bitfinex/base.py
import time import requests import numpy as np import pandas as pd from tradingfeatures import apiBase class bitfinexBase(apiBase): def __init__(self): super(bitfinexBase, self).__init__( name = 'bitfinex', per_step = 120, sleep = 0.5, ) self.base_add...
0.518546
0.196306
from onegov.core.upgrade import upgrade_task from onegov.core.orm import Base, find_models from onegov.core.orm.abstract import Associable from onegov.core.orm.types import JSON from sqlalchemy import inspect, text from sqlalchemy.exc import NoInspectionAvailable @upgrade_task('Drop primary key from associated tables...
src/onegov/core/upgrades.py
from onegov.core.upgrade import upgrade_task from onegov.core.orm import Base, find_models from onegov.core.orm.abstract import Associable from onegov.core.orm.types import JSON from sqlalchemy import inspect, text from sqlalchemy.exc import NoInspectionAvailable @upgrade_task('Drop primary key from associated tables...
0.457864
0.211193
from time import time from simplejson import dumps from thingsboard_gateway.connectors.rest.rest_converter import RESTConverter, log from thingsboard_gateway.tb_utility.tb_utility import TBUtility class JsonRESTUplinkConverter(RESTConverter): def __init__(self, config): self.__config = config def...
thingsboard_gateway/connectors/rest/json_rest_uplink_converter.py
from time import time from simplejson import dumps from thingsboard_gateway.connectors.rest.rest_converter import RESTConverter, log from thingsboard_gateway.tb_utility.tb_utility import TBUtility class JsonRESTUplinkConverter(RESTConverter): def __init__(self, config): self.__config = config def...
0.293708
0.209773
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections import heapq import logging import json import zlib import click from treadmill import cli from treadmill import context from treadmill import zkname...
lib/python/treadmill/cli/admin/show.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections import heapq import logging import json import zlib import click from treadmill import cli from treadmill import context from treadmill import zkname...
0.571049
0.051106
MSVC_WARNINGS = [ "/W4", # Baseline reasonable warnings "/w14242", # 'identifier': conversion from 'type1' to 'type1', possible loss of data "/w14254", # 'operator': conversion from 'type1:field_bits' to 'type2:field_bits', possible loss of data "/w14263", # 'function': member function does not ove...
settings/copts.bzl
MSVC_WARNINGS = [ "/W4", # Baseline reasonable warnings "/w14242", # 'identifier': conversion from 'type1' to 'type1', possible loss of data "/w14254", # 'operator': conversion from 'type1:field_bits' to 'type2:field_bits', possible loss of data "/w14263", # 'function': member function does not ove...
0.553988
0.308261
from flask import render_template, request, Response from SharedPreferences import AnglesStorage from app import app import requests import urllib import math ipcamProtocol = 'http://' ipcamAddress = '192.168.127.12:8085' ipcamWebctl = '/decoder_control.cgi' ipcamVideostream = '/videostream.cgi' ipcamUser =...
site/app/views.py
from flask import render_template, request, Response from SharedPreferences import AnglesStorage from app import app import requests import urllib import math ipcamProtocol = 'http://' ipcamAddress = '192.168.127.12:8085' ipcamWebctl = '/decoder_control.cgi' ipcamVideostream = '/videostream.cgi' ipcamUser =...
0.505127
0.120672
import os import typing def _patch_cython_coverage(): ''' Monkey patch `Cython.Coverage` to also work with Cython packages. ''' import Cython.Coverage def _get_reverse_hierarchy(path: str) -> typing.Generator[str, None, None]: ''' Generator yielding reverse path hierarchy to simpl...
extras/python-bindings/util/coverage-report.py
import os import typing def _patch_cython_coverage(): ''' Monkey patch `Cython.Coverage` to also work with Cython packages. ''' import Cython.Coverage def _get_reverse_hierarchy(path: str) -> typing.Generator[str, None, None]: ''' Generator yielding reverse path hierarchy to simpl...
0.57069
0.514217
from dataclasses import dataclass from typing import Callable import torch import torch.nn as nn from fairseq.models import FairseqLanguageModel from fairseq.models.transformer import Embedding, TransformerDecoder from fairseq.tasks.language_modeling import LanguageModelingTask from torch import Tensor from .transfor...
diagnnose/models/fairseq_lm.py
from dataclasses import dataclass from typing import Callable import torch import torch.nn as nn from fairseq.models import FairseqLanguageModel from fairseq.models.transformer import Embedding, TransformerDecoder from fairseq.tasks.language_modeling import LanguageModelingTask from torch import Tensor from .transfor...
0.941828
0.320276
from .. import ast_funcs, conf from ..gen_utils import layout_comment as layout from . import any_block_help op_name2symbol = { 'Add': '+', 'Sub': '-', 'Mult': '*', 'Div': '/', 'Mod': '%', 'FloorDiv': '//', 'Pow': '**', 'BitAnd': '&', 'BitOr': '|', 'BitXor': '^', 'RShift': '...
superhelp/helpers/operator_help.py
from .. import ast_funcs, conf from ..gen_utils import layout_comment as layout from . import any_block_help op_name2symbol = { 'Add': '+', 'Sub': '-', 'Mult': '*', 'Div': '/', 'Mod': '%', 'FloorDiv': '//', 'Pow': '**', 'BitAnd': '&', 'BitOr': '|', 'BitXor': '^', 'RShift': '...
0.382949
0.248899
import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class GetConsumeGroupResult: """ A collection of values returned by getConsumeGroup. """ def __init__(__self__, eventhub_name=None, id=None, location=None, name=None, namespace_nam...
sdk/python/pulumi_azure/eventhub/get_consume_group.py
import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class GetConsumeGroupResult: """ A collection of values returned by getConsumeGroup. """ def __init__(__self__, eventhub_name=None, id=None, location=None, name=None, namespace_nam...
0.647241
0.049359
from repositories.CarRepository import CarRepository import datetime import string class CarService: def __init__(self): self.__car_repo = CarRepository() def add_car(self, car): self.__car_repo.add_car(car) def get_cars(self): return self.__car_repo.get_car() def get_car_by...
services/CarService.py
from repositories.CarRepository import CarRepository import datetime import string class CarService: def __init__(self): self.__car_repo = CarRepository() def add_car(self, car): self.__car_repo.add_car(car) def get_cars(self): return self.__car_repo.get_car() def get_car_by...
0.531453
0.265511
import re def initializeEnSentence(FREQDICT, sentence): words = sentence.strip().split() taggedSen = [] for word in words: if word in ["“", "”", '"']: taggedSen.append("''/" + FREQDICT["''"]) continue tag = "" lowerW = word.lower() if word in FREQD...
artagger/InitialTagger/InitialTagger4En.py
import re def initializeEnSentence(FREQDICT, sentence): words = sentence.strip().split() taggedSen = [] for word in words: if word in ["“", "”", '"']: taggedSen.append("''/" + FREQDICT["''"]) continue tag = "" lowerW = word.lower() if word in FREQD...
0.209955
0.186151
from __future__ import division from urllib2 import urlopen import json # 1 (std unit) = these many units MULTIPLIERS_TO_STD = { 'length': { 'cm': 0.01, 'm': 1, # std unit 'km': 1000, 'mi': 1609.34, 'ft': 0.3048 }, 'temp': { 'C': 1, # std un...
Numbers/unit.py
from __future__ import division from urllib2 import urlopen import json # 1 (std unit) = these many units MULTIPLIERS_TO_STD = { 'length': { 'cm': 0.01, 'm': 1, # std unit 'km': 1000, 'mi': 1609.34, 'ft': 0.3048 }, 'temp': { 'C': 1, # std un...
0.468547
0.153962
from django.conf import settings import importlib USER_SETTINGS = getattr(settings, 'DASHING', None) DEFAULTS = { 'REPOSITORY': 'https://cdn.rawgit.com/talpor/django-dashing-channel/' 'master/repositories.json', 'INSTALLED_WIDGETS': ('number', 'list', 'graph', 'clock', 'knob', 'map',), '...
dashing/settings.py
from django.conf import settings import importlib USER_SETTINGS = getattr(settings, 'DASHING', None) DEFAULTS = { 'REPOSITORY': 'https://cdn.rawgit.com/talpor/django-dashing-channel/' 'master/repositories.json', 'INSTALLED_WIDGETS': ('number', 'list', 'graph', 'clock', 'knob', 'map',), '...
0.489992
0.115811
r"""Public APIs of anyconfig module. .. versionchanged:: 0.10.2 - Re-structured APIs and split into sub modules - Added type hints .. versionchanged:: 0.9.9 - Removed the API 'find_loader' - Added new APIs :func:`find` and :func:`findall` to :func:`find parsers` (loaders and dumpers) to suppport to...
src/anyconfig/api/__init__.py
r"""Public APIs of anyconfig module. .. versionchanged:: 0.10.2 - Re-structured APIs and split into sub modules - Added type hints .. versionchanged:: 0.9.9 - Removed the API 'find_loader' - Added new APIs :func:`find` and :func:`findall` to :func:`find parsers` (loaders and dumpers) to suppport to...
0.826991
0.231147
# # s_evaluation_eco_cap [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_evaluation_eco_cap&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=EBEconomicCapital). # + import nu...
scripts/sources/s_evaluation_eco_cap.py
# # s_evaluation_eco_cap [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_evaluation_eco_cap&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=EBEconomicCapital). # + import nu...
0.741206
0.510985
import parasbolv as psv import matplotlib.pyplot as plt import numpy as np import random fig, ax = plt.subplots() ### Scatter plot np.random.seed(18012001) rng = np.random.default_rng(12345) x = rng.integers(low=0, high=600, size=30) y = rng.integers(low=0, high=600, size=30) plt.scatter(x, y, s=15, color...
gallery/10_integrated-plotting/10_integrated-plotting.py
import parasbolv as psv import matplotlib.pyplot as plt import numpy as np import random fig, ax = plt.subplots() ### Scatter plot np.random.seed(18012001) rng = np.random.default_rng(12345) x = rng.integers(low=0, high=600, size=30) y = rng.integers(low=0, high=600, size=30) plt.scatter(x, y, s=15, color...
0.434221
0.292444
from utils import loss_utils from settings import IMG_ROWS, IMG_COLS from keras.models import Sequential, Model,model_from_json from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers import Input, merge, UpSampling2D from keras.layers.convolutional import Convolution2D, MaxPooling2D from k...
models.py
from utils import loss_utils from settings import IMG_ROWS, IMG_COLS from keras.models import Sequential, Model,model_from_json from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers import Input, merge, UpSampling2D from keras.layers.convolutional import Convolution2D, MaxPooling2D from k...
0.751739
0.592608
import sys import os.path import yaml import json import collections import python_translate.translations class NotFoundResourceException(Exception): pass class InvalidResourceException(Exception): pass class Loader(object): """ Loader is the abstract class that all translation loaders are suppose...
python_translate/loaders.py
import sys import os.path import yaml import json import collections import python_translate.translations class NotFoundResourceException(Exception): pass class InvalidResourceException(Exception): pass class Loader(object): """ Loader is the abstract class that all translation loaders are suppose...
0.58059
0.189634
import inspect from ryu import cfg import webob.dec from ryu.lib import hub from routes import Mapper from routes.util import URLGenerator CONF = cfg.CONF CONF.register_cli_opts([ cfg.StrOpt('wsapi-host', default='', help='webapp listen host'), cfg.IntOpt('wsapi-port', default=8080, help='webapp listen por...
ryu/app/wsgi.py
import inspect from ryu import cfg import webob.dec from ryu.lib import hub from routes import Mapper from routes.util import URLGenerator CONF = cfg.CONF CONF.register_cli_opts([ cfg.StrOpt('wsapi-host', default='', help='webapp listen host'), cfg.IntOpt('wsapi-port', default=8080, help='webapp listen por...
0.47926
0.067948
from pipeline import Logger, TaskStatus from model.entities_api import EntitiesAPI import os import time import multiprocessing from multiprocessing.pool import ThreadPool import subprocess import shlex UPLOAD_TASK_NAME = 'Upload' INPUT_CHECK_TASK_NAME = 'InputParametersCheck' METADATA_TASK_NAME = 'MetadataValuesExtr...
workflows/pipe-templates/__SYSTEM/data_loader/src/sys-data-upload.py
from pipeline import Logger, TaskStatus from model.entities_api import EntitiesAPI import os import time import multiprocessing from multiprocessing.pool import ThreadPool import subprocess import shlex UPLOAD_TASK_NAME = 'Upload' INPUT_CHECK_TASK_NAME = 'InputParametersCheck' METADATA_TASK_NAME = 'MetadataValuesExtr...
0.151059
0.069479
from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from config.owf_mixins import mixins from .models impor...
ozone-framework-python-server/stacks/views.py
from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from config.owf_mixins import mixins from .models impor...
0.589126
0.179818
import json import os from abc import ABCMeta, abstractmethod from copy import copy from typing import Optional, Dict, Mapping, Type from urllib.parse import urlparse from thriftybuilder.common import MissingOptionalDependencyError class ChecksumRetriever(metaclass=ABCMeta): """ Retriever of mappings between...
thriftybuilder/storage.py
import json import os from abc import ABCMeta, abstractmethod from copy import copy from typing import Optional, Dict, Mapping, Type from urllib.parse import urlparse from thriftybuilder.common import MissingOptionalDependencyError class ChecksumRetriever(metaclass=ABCMeta): """ Retriever of mappings between...
0.842798
0.184033
import parl from parl import layers import paddle.fluid as fluid import numpy as np import gym from parl.utils import logger from parl.algorithms import DQN import random import collections LEARN_FREQ = 5 # 训练频率,不需要每一个step都learn,攒一些新增经验后再learn,提高效率 MEMORY_SIZE= int(20000) # replay memory的大小,越大越占用内存 MEMORY_WARMUP_SI...
lesson3_DQN.py
import parl from parl import layers import paddle.fluid as fluid import numpy as np import gym from parl.utils import logger from parl.algorithms import DQN import random import collections LEARN_FREQ = 5 # 训练频率,不需要每一个step都learn,攒一些新增经验后再learn,提高效率 MEMORY_SIZE= int(20000) # replay memory的大小,越大越占用内存 MEMORY_WARMUP_SI...
0.359477
0.396623
#1. 生成模拟数据集。 import tensorflow as tf import matplotlib.pyplot as plt import numpy as np data = [] label = [] np.random.seed(0) # 以原点为圆心,半径为1的圆把散点划分成红蓝两部分,并加入随机噪音。 for i in range(150): x1 = np.random.uniform(-1,1) x2 = np.random.uniform(0,2) if x1**2 + x2**2 <= 1: data.append([np.random.normal(x1...
2017.TensorFlow&Python/4.tf_deep_neural_network/n04_4_All_Optimizations&Regularization_For_Newer_Numpy.py
#1. 生成模拟数据集。 import tensorflow as tf import matplotlib.pyplot as plt import numpy as np data = [] label = [] np.random.seed(0) # 以原点为圆心,半径为1的圆把散点划分成红蓝两部分,并加入随机噪音。 for i in range(150): x1 = np.random.uniform(-1,1) x2 = np.random.uniform(0,2) if x1**2 + x2**2 <= 1: data.append([np.random.normal(x1...
0.464659
0.52208
from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest # pylint: disable=g-import-not-at-top import matplotlib matplotlib.use("agg") # switch backend for testing import numpy as np from open_spiel.python.egt import alpharank from open_spiel.pyth...
open_spiel/python/egt/alpharank_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest # pylint: disable=g-import-not-at-top import matplotlib matplotlib.use("agg") # switch backend for testing import numpy as np from open_spiel.python.egt import alpharank from open_spiel.pyth...
0.808937
0.500244
# ----------------------------------------------------------------------------- # Module Import # ----------------------------------------------------------------------------- import os import sys import requests # ----------------------------------------------------------------------------- # Class Definitions # --...
vagrancy/box_file.py
# ----------------------------------------------------------------------------- # Module Import # ----------------------------------------------------------------------------- import os import sys import requests # ----------------------------------------------------------------------------- # Class Definitions # --...
0.597843
0.358493
""" losses """ import mindspore as ms import mindspore.nn as nn import mindspore.ops as ops import mindspore.ops.operations as P from mindspore import Tensor from src.utils.tools import is_version_satisfied_1_2_0 class GeneratorLoss(nn.Cell): """ GeneratorLoss """ def __init__(self, netG, netD, args, mode):...
research/cv/STGAN/src/models/losses.py
""" losses """ import mindspore as ms import mindspore.nn as nn import mindspore.ops as ops import mindspore.ops.operations as P from mindspore import Tensor from src.utils.tools import is_version_satisfied_1_2_0 class GeneratorLoss(nn.Cell): """ GeneratorLoss """ def __init__(self, netG, netD, args, mode):...
0.8812
0.320901
from argparse import ArgumentParser, Namespace from idb.cli import ClientCommand from idb.common.types import HIDButtonType, IdbClient class TapCommand(ClientCommand): @property def description(self) -> str: return "Tap On the Screen" @property def name(self) -> str: return "tap" ...
idb/cli/commands/hid.py
from argparse import ArgumentParser, Namespace from idb.cli import ClientCommand from idb.common.types import HIDButtonType, IdbClient class TapCommand(ClientCommand): @property def description(self) -> str: return "Tap On the Screen" @property def name(self) -> str: return "tap" ...
0.894254
0.237709
import numpy as np import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') # Snowflake time of flight Have you ever watched a snowflake fall and thought, "How long has that snowflake been falling?" Here, we want to determine the time of flight for a snowflake. We'll start simple and add some complexity to m...
_build/jupyter_execute/module_01/snowflake.py
import numpy as np import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') # Snowflake time of flight Have you ever watched a snowflake fall and thought, "How long has that snowflake been falling?" Here, we want to determine the time of flight for a snowflake. We'll start simple and add some complexity to m...
0.882276
0.921534
import time from pynq import Overlay import numpy as np from pynq import Xlnk import struct from scipy.misc import imread import cv2 def readbinfile(filename, size): f = open(filename, "rb") z = [] for j in range(size): data = f.read(4) data_float = struct.unpack("f", data)[0] z.ap...
jupyter_notebooks/GTSRB/Traffic-signs-recognition.py
import time from pynq import Overlay import numpy as np from pynq import Xlnk import struct from scipy.misc import imread import cv2 def readbinfile(filename, size): f = open(filename, "rb") z = [] for j in range(size): data = f.read(4) data_float = struct.unpack("f", data)[0] z.ap...
0.298389
0.214568
import os import re import argparse import torch import pytorch_mask_rcnn as pmr def main(args): use_cuda = True dataset = args.dataset ckpt_path = args.ckpt_path data_dir = args.data_dir shuffle = args.shuffle device = torch.device("cuda" if torch.cuda.is_available() and use_cuda else "cpu"...
demo.py
import os import re import argparse import torch import pytorch_mask_rcnn as pmr def main(args): use_cuda = True dataset = args.dataset ckpt_path = args.ckpt_path data_dir = args.data_dir shuffle = args.shuffle device = torch.device("cuda" if torch.cuda.is_available() and use_cuda else "cpu"...
0.408159
0.255901
from __future__ import absolute_import, print_function import tornado.ioloop import tornado.httpserver from .. import controller, flow from . import app class Stop(Exception): pass class WebState(flow.State): def __init__(self): flow.State.__init__(self) class Options(object): attributes = [ ...
libmproxy/web/__init__.py
from __future__ import absolute_import, print_function import tornado.ioloop import tornado.httpserver from .. import controller, flow from . import app class Stop(Exception): pass class WebState(flow.State): def __init__(self): flow.State.__init__(self) class Options(object): attributes = [ ...
0.500977
0.121009
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from __future__ import print_function from typing import List, Optional import torch from torch import nn from torch.nn import functional as F import numpy as np class OrdinalLogisticRegressionBasedCDFEstim...
model/regressor.py
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from __future__ import print_function from typing import List, Optional import torch from torch import nn from torch.nn import functional as F import numpy as np class OrdinalLogisticRegressionBasedCDFEstim...
0.933862
0.318525
import os import sys import torch import argparse import numpy as np import torch.nn as nn import PIL.Image as Image from torchvision import models from torchvision import transforms from torch.nn import functional as F import cv2 import matplotlib as mpl import os os.environ['KMP_DUPLICATE_LIB_OK']='True' mpl.use('Ag...
image_method/predict.py
import os import sys import torch import argparse import numpy as np import torch.nn as nn import PIL.Image as Image from torchvision import models from torchvision import transforms from torch.nn import functional as F import cv2 import matplotlib as mpl import os os.environ['KMP_DUPLICATE_LIB_OK']='True' mpl.use('Ag...
0.538983
0.370482
from asyncio import sleep from random import uniform from nvxlira import Lira class LoadPageTask: ''' Задача по скачиванию http-страницы ''' def __init__(self, url, filename, repeatc=64): ''' url — url страницы, которую нужно скачать filename — имя файла, куда нужно сохранить скачанную страницу r...
filling/parse/pageloader.py
from asyncio import sleep from random import uniform from nvxlira import Lira class LoadPageTask: ''' Задача по скачиванию http-страницы ''' def __init__(self, url, filename, repeatc=64): ''' url — url страницы, которую нужно скачать filename — имя файла, куда нужно сохранить скачанную страницу r...
0.196094
0.152694
import strawberry import strawberry_django_jwt.mutations from tests.refresh_token import mixins from tests.refresh_token.mutations import Refresh from tests.refresh_token.testcases import AsyncCookieTestCase, CookieTestCase from tests.testcases import AsyncSchemaTestCase, SchemaTestCase class TokenAuthTests(mixins.T...
tests/refresh_token/test_mutations.py
import strawberry import strawberry_django_jwt.mutations from tests.refresh_token import mixins from tests.refresh_token.mutations import Refresh from tests.refresh_token.testcases import AsyncCookieTestCase, CookieTestCase from tests.testcases import AsyncSchemaTestCase, SchemaTestCase class TokenAuthTests(mixins.T...
0.494629
0.182863
# Copyright 2019 <NAME> # Licensed under the Apache License, Version 2.0 (the "License") import os import copy import argparse import torch import torch.nn as nn from pynn.net.hybrid import Hybrid parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--n-classes', type=int, required=True) parse...
pynn/bin/average_hybrid.py
# Copyright 2019 <NAME> # Licensed under the Apache License, Version 2.0 (the "License") import os import copy import argparse import torch import torch.nn as nn from pynn.net.hybrid import Hybrid parser = argparse.ArgumentParser(description='pynn') parser.add_argument('--n-classes', type=int, required=True) parse...
0.697094
0.054727
import sys import os import glob import numpy as np import cv2 import argparse import math # Helper Utilities def remove_contents( top ): for root, dirs, files in os.walk( top, topdown=False ): for name in files: os.remove( os.path.join( root, name ) ) for name in dirs: os.rmdir( os.path.joi...
examples/object_detector_training/deprecated_old_api/create_dir.py
import sys import os import glob import numpy as np import cv2 import argparse import math # Helper Utilities def remove_contents( top ): for root, dirs, files in os.walk( top, topdown=False ): for name in files: os.remove( os.path.join( root, name ) ) for name in dirs: os.rmdir( os.path.joi...
0.262369
0.116563
from numpy import ndarray class Trie(): ''' Objeto árvore Trie básica usada para contagem de palavras. Modelo utilizado para contagem de palavras apenas contendo letras maiúsculas e minúsculas, armazenando todos os caracteres que não pertençam a nenhum dos dois tipos como '?' ''' d...
Estruturas de Dados/Arvores/ArvoreTrie.py
from numpy import ndarray class Trie(): ''' Objeto árvore Trie básica usada para contagem de palavras. Modelo utilizado para contagem de palavras apenas contendo letras maiúsculas e minúsculas, armazenando todos os caracteres que não pertençam a nenhum dos dois tipos como '?' ''' d...
0.244453
0.23709
import networkx as nx import matplotlib.pyplot as plt E = nx.Graph() vertex = ['V1','V2','V3','V4','V5','V6'] for vertex in E.graph: E.add_node(vertex) E.add_edge('v1', 'v2') E.add_edge('v2', 'v3') E.add_edge('v3', 'v1') E.add_edge('v4', 'v5') E.add_edge('v6', 'v5') E.add_edge('v6', 'v4') G = nx.Graph() vertex...
SecondDelivery/grafos2.py
import networkx as nx import matplotlib.pyplot as plt E = nx.Graph() vertex = ['V1','V2','V3','V4','V5','V6'] for vertex in E.graph: E.add_node(vertex) E.add_edge('v1', 'v2') E.add_edge('v2', 'v3') E.add_edge('v3', 'v1') E.add_edge('v4', 'v5') E.add_edge('v6', 'v5') E.add_edge('v6', 'v4') G = nx.Graph() vertex...
0.17113
0.442396
from typing import List, Optional, Set from collections import Counter def part_1() -> int: draws: List[int] = [] boards: List[List[List[int]]] = [] with open('input.txt', 'r') as f: draws.extend(int(i) for i in f.readline().split(',')) board: List[List[int]] = [] for line in f: ...
aoc2021/day4/solution.py
from typing import List, Optional, Set from collections import Counter def part_1() -> int: draws: List[int] = [] boards: List[List[List[int]]] = [] with open('input.txt', 'r') as f: draws.extend(int(i) for i in f.readline().split(',')) board: List[List[int]] = [] for line in f: ...
0.708515
0.312363
# Copyright (c) 2018, NetApp, Inc. # Licensed under the terms of the Modified BSD License (also known as New or Revised or 3-Clause BSD) import sys import json from functools import wraps from flask import Flask, send_file, render_template, session, request import botocore, boto3 import logging import time import ma...
app.py
# Copyright (c) 2018, NetApp, Inc. # Licensed under the terms of the Modified BSD License (also known as New or Revised or 3-Clause BSD) import sys import json from functools import wraps from flask import Flask, send_file, render_template, session, request import botocore, boto3 import logging import time import ma...
0.551815
0.091585
import math from datetime import datetime, timedelta, date import calendar from .transformation import Transformation class ExtractBasic(Transformation): title = "Extract year from {field} into {output}" key = "Datetime minutes" fields = { "field": {"name": "Input", "type": "string", "help": "The...
data_scout/transformations/datetime.py
import math from datetime import datetime, timedelta, date import calendar from .transformation import Transformation class ExtractBasic(Transformation): title = "Extract year from {field} into {output}" key = "Datetime minutes" fields = { "field": {"name": "Input", "type": "string", "help": "The...
0.698535
0.455683
from flask import (Blueprint, render_template, redirect, flash, url_for, request) from flask import json,jsonify,render_template import pandas as pd import time from datetime import datetime from webapp.models import MyStock,Stock,DataItem,Comment from webapp.services import getHeaders,getXueqiuHe...
webapp/views/setting.py
from flask import (Blueprint, render_template, redirect, flash, url_for, request) from flask import json,jsonify,render_template import pandas as pd import time from datetime import datetime from webapp.models import MyStock,Stock,DataItem,Comment from webapp.services import getHeaders,getXueqiuHe...
0.322526
0.06663
from .Base import Object,Rotatable,Owned from Lib import Img,Vector from .Machines.Base import Machine,FixedMachine from Game.Registry import add_recipe from Game.Research import add_recipesearch from Game import FX from Engine.Items import Placeable,MultiSlot,Slot,ammos,resources from .Machines import MUI import math ...
Objects/War.py
from .Base import Object,Rotatable,Owned from Lib import Img,Vector from .Machines.Base import Machine,FixedMachine from Game.Registry import add_recipe from Game.Research import add_recipesearch from Game import FX from Engine.Items import Placeable,MultiSlot,Slot,ammos,resources from .Machines import MUI import math ...
0.362405
0.30793
import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECRET KEY SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HO...
pictor/settings.py
import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECRET KEY SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HO...
0.225161
0.04747
class ExternalDefinitionCreationOptions(object,IDisposable): """ An option class used for creating a new shared parameter definition,including options such as name,type,visibility, Guid description and modifiable flag. ExternalDefinitionCreationOptions(name: str,type: ParameterType) """ def Disp...
release/stubs.min/Autodesk/Revit/DB/__init___parts/ExternalDefinitionCreationOptions.py
class ExternalDefinitionCreationOptions(object,IDisposable): """ An option class used for creating a new shared parameter definition,including options such as name,type,visibility, Guid description and modifiable flag. ExternalDefinitionCreationOptions(name: str,type: ParameterType) """ def Disp...
0.70202
0.140101
from scipy.stats import binom from matplotlib import pyplot as plt import numpy as np from xgboost import XGBClassifier, XGBRegressor def get_pit(cdes: np.ndarray, z_grid: np.ndarray, z_test: np.ndarray) -> np.ndarray: """ Calculates PIT based on CDE cdes: a numpy array of conditional density estimates; ...
utils.py
from scipy.stats import binom from matplotlib import pyplot as plt import numpy as np from xgboost import XGBClassifier, XGBRegressor def get_pit(cdes: np.ndarray, z_grid: np.ndarray, z_test: np.ndarray) -> np.ndarray: """ Calculates PIT based on CDE cdes: a numpy array of conditional density estimates; ...
0.95267
0.840259
from environment import Environment import random class Agent: """Q learning Agent""" def __init__(self, epsilon=0.1, alpha=1.0): self.initialize_V() self.epsilon = epsilon self.alpha = alpha self.reset_possible_states() def initialize_V(self): """initializes State...
src/agent.py
from environment import Environment import random class Agent: """Q learning Agent""" def __init__(self, epsilon=0.1, alpha=1.0): self.initialize_V() self.epsilon = epsilon self.alpha = alpha self.reset_possible_states() def initialize_V(self): """initializes State...
0.731922
0.522202
import glob from time import time from preprocess_text import corpus from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation from nltk import word_tokenize from nltk.stem import WordNetLemmatizer import re NYT_CORPUS_PATH ...
src/lda_topic_extraction.py
import glob from time import time from preprocess_text import corpus from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation from nltk import word_tokenize from nltk.stem import WordNetLemmatizer import re NYT_CORPUS_PATH ...
0.475362
0.152316
import argparse import os import logging import time import hashlib import random import json from io import BytesIO from isis2json import isis2json from xylose.scielodocument import Journal from articlemetarpcclient import ArticleMetaRPCClient THROTTLE_TIME = 60*10 # 10 minutes def _config_logging(logging_level='...
monitor/monitor.py
import argparse import os import logging import time import hashlib import random import json from io import BytesIO from isis2json import isis2json from xylose.scielodocument import Journal from articlemetarpcclient import ArticleMetaRPCClient THROTTLE_TIME = 60*10 # 10 minutes def _config_logging(logging_level='...
0.494385
0.103749
import logging from typing import Callable, Any, Union, Dict, List, Optional logger = logging.getLogger(__name__) LMB = 1 MMB = 2 RMB = 3 class EventSubscription: callback: Callable[[Any], None] event_type: int subtype: Union[int, None] conditions: Dict[str, Any] kwargs: List[str] as_args:...
app/events/subscriptions.py
import logging from typing import Callable, Any, Union, Dict, List, Optional logger = logging.getLogger(__name__) LMB = 1 MMB = 2 RMB = 3 class EventSubscription: callback: Callable[[Any], None] event_type: int subtype: Union[int, None] conditions: Dict[str, Any] kwargs: List[str] as_args:...
0.734786
0.183246
from __future__ import print_function import time import json import datetime import sys from app.os_abstract import Os from activity import ActivityList, TimeEntry, Activity class OsFactory: browsers = ('Google Chrome', 'Mozilla Firefox', 'Microsoft Edge') def __init__(self): self.active_window_nam...
app/os_factory.py
from __future__ import print_function import time import json import datetime import sys from app.os_abstract import Os from activity import ActivityList, TimeEntry, Activity class OsFactory: browsers = ('Google Chrome', 'Mozilla Firefox', 'Microsoft Edge') def __init__(self): self.active_window_nam...
0.21215
0.058669
import pyaudio import threading from abc import abstractmethod from typing import Generator, List from .bases import AbstractStream, InputStreamMixin, OutputStreamMixin from .consts import DEFAULT_RATE, DEFAULT_CHUNK, DEFAULT_CHANNELS, DEFAULT_SAMPLE_FORMAT __all__ = ["PyAudioStream", "RecordingStream", "PlaybackStre...
zoombot/audio.py
import pyaudio import threading from abc import abstractmethod from typing import Generator, List from .bases import AbstractStream, InputStreamMixin, OutputStreamMixin from .consts import DEFAULT_RATE, DEFAULT_CHUNK, DEFAULT_CHANNELS, DEFAULT_SAMPLE_FORMAT __all__ = ["PyAudioStream", "RecordingStream", "PlaybackStre...
0.834508
0.190781
import csv import glob import os import random from abc import ABC, abstractmethod from typing import List, Callable, Union, Dict import numpy as np import pandas as pd import torch import tqdm from PIL import Image from torch.utils.data import Dataset, DataLoader from torch.nn import functional as F from src import ...
src/datasets.py
import csv import glob import os import random from abc import ABC, abstractmethod from typing import List, Callable, Union, Dict import numpy as np import pandas as pd import torch import tqdm from PIL import Image from torch.utils.data import Dataset, DataLoader from torch.nn import functional as F from src import ...
0.850096
0.298079
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd from dash_docs.reusable_components import Section, Chapter from dash_docs import styles from dash_docs import tools from dash_docs import reusable_components as rc examples = tools.load_examples(__file__) preamble ...
dash_docs/chapters/dash_datatable/index.py
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd from dash_docs.reusable_components import Section, Chapter from dash_docs import styles from dash_docs import tools from dash_docs import reusable_components as rc examples = tools.load_examples(__file__) preamble ...
0.658527
0.549399
import json import requests as req from app.api.helpers.service import Gis as gs from app.api.base.base_sql import Sql from app.api.base import base_name as names def get_from_google(query): """ :param query: достопримечательности+город :return: list с точками """ key = "AIzaSyDMIfc6_9K7574xu18dG6a...
backend/app/api/src/touches_from_api.py
import json import requests as req from app.api.helpers.service import Gis as gs from app.api.base.base_sql import Sql from app.api.base import base_name as names def get_from_google(query): """ :param query: достопримечательности+город :return: list с точками """ key = "AIzaSyDMIfc6_9K7574xu18dG6a...
0.315314
0.125413
import math import matplotlib.pyplot as plt import numpy as np import pytest from kneed.data_generator import DataGenerator as dg from kneed.knee_locator import KneeLocator from kneed.shape_detector import find_shape @pytest.mark.parametrize("interp_method", ["interp1d", "polynomial"]) def test_figure2(interp_method)...
tests/test_sample.py
import math import matplotlib.pyplot as plt import numpy as np import pytest from kneed.data_generator import DataGenerator as dg from kneed.knee_locator import KneeLocator from kneed.shape_detector import find_shape @pytest.mark.parametrize("interp_method", ["interp1d", "polynomial"]) def test_figure2(interp_method)...
0.813238
0.660911
import csv import pymysql import requests import re from lxml import html import time import urllib3 from requests.adapters import HTTPAdapter # 请求头 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 " "Safari/537.36 " } # 登...
spider/test/douban_movie_info.py
import csv import pymysql import requests import re from lxml import html import time import urllib3 from requests.adapters import HTTPAdapter # 请求头 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 " "Safari/537.36 " } # 登...
0.078855
0.07343
from slackbot.bot import respond_to, listen_to, default_reply import re # 外部.py(自作モジュール)の読み込み from plugins.modules.weather_module import WeatherModule from plugins.modules.apiai_module import ApiaiModule # 自作モジュールのインスタンス化 wm = WeatherModule() am = ApiaiModule() info="""[とりせつ] ``` 私は成長中です.いろんな機能を習得...
plugins/reply_funcs.py
from slackbot.bot import respond_to, listen_to, default_reply import re # 外部.py(自作モジュール)の読み込み from plugins.modules.weather_module import WeatherModule from plugins.modules.apiai_module import ApiaiModule # 自作モジュールのインスタンス化 wm = WeatherModule() am = ApiaiModule() info="""[とりせつ] ``` 私は成長中です.いろんな機能を習得...
0.26588
0.666822
from django.http import HttpResponse, JsonResponse, FileResponse from django.shortcuts import render,redirect,reverse from django.contrib.auth.decorators import login_required from dzkd.settings import BASE_DIR import re import smtplib from email.mime.text import MIMEText from .models import * import json import qrcode...
index/views.py
from django.http import HttpResponse, JsonResponse, FileResponse from django.shortcuts import render,redirect,reverse from django.contrib.auth.decorators import login_required from dzkd.settings import BASE_DIR import re import smtplib from email.mime.text import MIMEText from .models import * import json import qrcode...
0.261425
0.074366
from typing import Any from dltb.base.observer import Observable, change class Config(Observable, method='configChanged', changes={'config_changed'}): """A :py:class:Config object provides configuration data. It is an :py:class:Observable, allowing :py:class:Engine and user interfaces to be notified on ...
base/config.py
from typing import Any from dltb.base.observer import Observable, change class Config(Observable, method='configChanged', changes={'config_changed'}): """A :py:class:Config object provides configuration data. It is an :py:class:Observable, allowing :py:class:Engine and user interfaces to be notified on ...
0.8956
0.242991
__all__ = ['Client'] import asyncio import base64 import binascii import gzip import hashlib import json import random import re import socket import time import uuid from typing import ClassVar, Dict, List, Literal, Optional, Tuple, Union import aiohttp import cv2 as cv import numpy as np from bs4 import BeautifulSo...
aiotieba/api.py
__all__ = ['Client'] import asyncio import base64 import binascii import gzip import hashlib import json import random import re import socket import time import uuid from typing import ClassVar, Dict, List, Literal, Optional, Tuple, Union import aiohttp import cv2 as cv import numpy as np from bs4 import BeautifulSo...
0.438064
0.059401
import pandas as pd import pymongo from bokeh.plotting import cursession, figure, output_server, push from bokeh.models.formatters import DatetimeTickFormatter, PrintfTickFormatter from bokeh import embed from json import load from urllib.request import urlopen import time client = pymongo.MongoClient() db = client['b...
app/run_charts_performance.py
import pandas as pd import pymongo from bokeh.plotting import cursession, figure, output_server, push from bokeh.models.formatters import DatetimeTickFormatter, PrintfTickFormatter from bokeh import embed from json import load from urllib.request import urlopen import time client = pymongo.MongoClient() db = client['b...
0.505615
0.251401
import base64 import hashlib import json import re from datetime import datetime import pytz from dateutil import parser from connaisseur.exceptions import ( InvalidTrustDataFormatError, NoSuchClassError, NotFoundException, ValidationError, WrongKeyError, ) from connaisseur.trust_root import Trust...
connaisseur/validators/notaryv1/trust_data.py
import base64 import hashlib import json import re from datetime import datetime import pytz from dateutil import parser from connaisseur.exceptions import ( InvalidTrustDataFormatError, NoSuchClassError, NotFoundException, ValidationError, WrongKeyError, ) from connaisseur.trust_root import Trust...
0.777215
0.221645