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 os, sys import numpy as np here = os.path.abspath(os.path.dirname(__file__)) CODE_SUB_DIR = os.path.abspath(os.path.join(here, "..", "..")) print(CODE_SUB_DIR) sys.path.append(CODE_SUB_DIR) from at_speech import SLLRLiblinear, SLLRSag, ThinResnet34Classifier from at_speech.data_space.raw_data_space import Raw...
AutoDL_sample_code_submission/at_speech/policy_space/model_executor.py
import os, sys import numpy as np here = os.path.abspath(os.path.dirname(__file__)) CODE_SUB_DIR = os.path.abspath(os.path.join(here, "..", "..")) print(CODE_SUB_DIR) sys.path.append(CODE_SUB_DIR) from at_speech import SLLRLiblinear, SLLRSag, ThinResnet34Classifier from at_speech.data_space.raw_data_space import Raw...
0.217338
0.127029
from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class V3utilsApi(object): """ NOTE: This class is auto generated by the swagger code gen...
whoville/cloudbreak/apis/v3utils_api.py
from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class V3utilsApi(object): """ NOTE: This class is auto generated by the swagger code gen...
0.601711
0.07221
# Step1: preprocess_data.py import os file_input_data = '../../umap_dataset/data/whole_annotation_data_336_modified_taxonomy.json' content_features = 1 structural_features = 1 sentiment_features = 1 conversational_features = 1 feature_normalization = 0 model_name = 'cnn_base' max_sequence_length = 50 max_num_...
user_intent_prediction/model_cnn_base/script_cnn_base.py
# Step1: preprocess_data.py import os file_input_data = '../../umap_dataset/data/whole_annotation_data_336_modified_taxonomy.json' content_features = 1 structural_features = 1 sentiment_features = 1 conversational_features = 1 feature_normalization = 0 model_name = 'cnn_base' max_sequence_length = 50 max_num_...
0.5794
0.299086
import subprocess import os from spotdl.encode import EncoderBase from spotdl.encode.exceptions import EncoderNotFoundError from spotdl.encode.exceptions import FFmpegNotFoundError import logging logger = logging.getLogger(__name__) # Key: from format # Subkey: to format RULES = { "m4a": { "mp3": "-code...
spotdl/encode/encoders/ffmpeg.py
import subprocess import os from spotdl.encode import EncoderBase from spotdl.encode.exceptions import EncoderNotFoundError from spotdl.encode.exceptions import FFmpegNotFoundError import logging logger = logging.getLogger(__name__) # Key: from format # Subkey: to format RULES = { "m4a": { "mp3": "-code...
0.428831
0.12787
from django.db.models import Q, F from rest_framework import viewsets, serializers from rest_framework.filters import SearchFilter from rest_framework.response import Response from rest_framework.views import APIView from models import Recipe, Ingredient def search_by_time_ingredients(ingredients, time, queryset): ...
recipe-search/recipe/serializers.py
from django.db.models import Q, F from rest_framework import viewsets, serializers from rest_framework.filters import SearchFilter from rest_framework.response import Response from rest_framework.views import APIView from models import Recipe, Ingredient def search_by_time_ingredients(ingredients, time, queryset): ...
0.749821
0.199016
__author__ = 'buec' import xml.etree.ElementTree as et from pyspeechgrammar import model class SRGSXMLSerializer: def create_grammar_element(self, grammar): grammar_element = et.Element('grammar') for rule in grammar.rules: rule_element = self.create_rule_element(rule) ...
pyspeechgrammar/srgs_xml/serialize.py
__author__ = 'buec' import xml.etree.ElementTree as et from pyspeechgrammar import model class SRGSXMLSerializer: def create_grammar_element(self, grammar): grammar_element = et.Element('grammar') for rule in grammar.rules: rule_element = self.create_rule_element(rule) ...
0.483892
0.197696
from typing import Iterator, List, Union, Optional import numpy as np import logging from syne_tune.optimizer.schedulers.searchers.bayesopt.tuning_algorithms.base_classes \ import CandidateGenerator from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.common \ import Configuration, ConfigurationFil...
syne_tune/optimizer/schedulers/searchers/bayesopt/tuning_algorithms/common.py
from typing import Iterator, List, Union, Optional import numpy as np import logging from syne_tune.optimizer.schedulers.searchers.bayesopt.tuning_algorithms.base_classes \ import CandidateGenerator from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.common \ import Configuration, ConfigurationFil...
0.864153
0.342599
import re import requests import time import sys from random import randint from urlparse import urlparse headers = {"Connection": "keep-alive", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.292...
FogOfWar/fogofweb.py
import re import requests import time import sys from random import randint from urlparse import urlparse headers = {"Connection": "keep-alive", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.292...
0.097005
0.085251
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('diabetes.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 8].values #taking care of missing data from sklearn.preprocessing import Imputer imputer = Imputer(missing...
decision_tree.py
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('diabetes.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 8].values #taking care of missing data from sklearn.preprocessing import Imputer imputer = Imputer(missing...
0.764276
0.67698
from .____init___6 import * import typing import System.IO import System.Collections.Generic import System import QuantConnect.Indicators import QuantConnect.Data.Market import QuantConnect.Data import QuantConnect import Python.Runtime import datetime class IndicatorExtensions(System.object): """ Provides extens...
Algorithm.Python/stubs/QuantConnect/Indicators/____init___5.py
from .____init___6 import * import typing import System.IO import System.Collections.Generic import System import QuantConnect.Indicators import QuantConnect.Data.Market import QuantConnect.Data import QuantConnect import Python.Runtime import datetime class IndicatorExtensions(System.object): """ Provides extens...
0.853547
0.324329
class Solution: def numberToWords(self, num): """ :type num: int :rtype: str """ # 维护一个数字到英语的转换字典 self.IntEng = { "0": 'Zero', "1": 'One', "2": 'Two', "3": 'Three', "4": 'Four', "5": 'Five', ...
LeetCode/2019-02-04-273-Integer-to-English-Words.py
class Solution: def numberToWords(self, num): """ :type num: int :rtype: str """ # 维护一个数字到英语的转换字典 self.IntEng = { "0": 'Zero', "1": 'One', "2": 'Two', "3": 'Three', "4": 'Four', "5": 'Five', ...
0.487551
0.548794
# IMPORTOWANIE from pylab import * import ephem as ep # OBSERVATEUR obs = ep.Observer() # TUNIS obs.lon, obs.lat, obs.elev = '10.08', '36.4', 100.0 obs.name= "SAT-TUNIS" # NOUS CRÉONS UN OBJET # on vérifie si c'est sous l'horizon soleil = ep.Sun() lune = ep.Moon() venus = ep.Venus() mars = ep.Mars() jupiter = ep.Jupit...
docs/.src/programs/planet_conj.py
# IMPORTOWANIE from pylab import * import ephem as ep # OBSERVATEUR obs = ep.Observer() # TUNIS obs.lon, obs.lat, obs.elev = '10.08', '36.4', 100.0 obs.name= "SAT-TUNIS" # NOUS CRÉONS UN OBJET # on vérifie si c'est sous l'horizon soleil = ep.Sun() lune = ep.Moon() venus = ep.Venus() mars = ep.Mars() jupiter = ep.Jupit...
0.127544
0.242183
import ctypes import os from typing import List, Dict, Union import numpy as np from jinja2 import Template from deep500.lv0.operators.cmake_wrapper import cmake, try_mkdirs from deep500.lv0.operators.op_compiler import CompilableOp from deep500.utils.tensor_desc import TensorDescriptor from deep500.lv0.operators.ope...
deep500/frameworks/reference/custom_operators/base.py
import ctypes import os from typing import List, Dict, Union import numpy as np from jinja2 import Template from deep500.lv0.operators.cmake_wrapper import cmake, try_mkdirs from deep500.lv0.operators.op_compiler import CompilableOp from deep500.utils.tensor_desc import TensorDescriptor from deep500.lv0.operators.ope...
0.569134
0.447219
import os from pathlib import Path import cloudinary import cloudinary.api import cloudinary.uploader import sentry_sdk from dotenv import load_dotenv from sentry_sdk.integrations.django import DjangoIntegration load_dotenv() # take environment variables from .env. BASE_DIR = Path(__file__).resolve()....
Project/settings.py
import os from pathlib import Path import cloudinary import cloudinary.api import cloudinary.uploader import sentry_sdk from dotenv import load_dotenv from sentry_sdk.integrations.django import DjangoIntegration load_dotenv() # take environment variables from .env. BASE_DIR = Path(__file__).resolve()....
0.186169
0.053576
import pprint import re # noqa: F401 import six from swagger_client.configuration import Configuration class CellSiteChannel(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): Th...
Wigle/python-client/swagger_client/models/cell_site_channel.py
import pprint import re # noqa: F401 import six from swagger_client.configuration import Configuration class CellSiteChannel(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): Th...
0.772616
0.192862
import math import os import digitalio import board import time from adafruit_rgb_display.rgb import color565 import adafruit_rgb_display.st7789 as st7789 from PIL import Image, ImageDraw, ImageFont from fonts.ttf import RobotoMedium import busio import adafruit_vl53l0x i2c = busio.I2C(board.SCL, board.SDA) vl53 = ad...
main.py
import math import os import digitalio import board import time from adafruit_rgb_display.rgb import color565 import adafruit_rgb_display.st7789 as st7789 from PIL import Image, ImageDraw, ImageFont from fonts.ttf import RobotoMedium import busio import adafruit_vl53l0x i2c = busio.I2C(board.SCL, board.SDA) vl53 = ad...
0.419291
0.199347
import random import numpy as np from scipy.stats import norm import time import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.gridspec as gridspec # From Theano tutorial - MNIST dataset from logistic_sgd import load_data import theano import theano.tensor as T start_time = time.time() n_la...
hard-gists/651afb13d45e4c587f63/snippet.py
import random import numpy as np from scipy.stats import norm import time import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.gridspec as gridspec # From Theano tutorial - MNIST dataset from logistic_sgd import load_data import theano import theano.tensor as T start_time = time.time() n_la...
0.734691
0.479321
from django.shortcuts import render from django.http import HttpResponse, JsonResponse import os import json from bs4 import BeautifulSoup import requests import re import datetime from mp.models import Config def get_one(request): myconfig = Config.objects.all().first() if myconfig.apichange: res = re...
zfnweb/one/views.py
from django.shortcuts import render from django.http import HttpResponse, JsonResponse import os import json from bs4 import BeautifulSoup import requests import re import datetime from mp.models import Config def get_one(request): myconfig = Config.objects.all().first() if myconfig.apichange: res = re...
0.099361
0.034521
import uuid import django.db.models from django.core.exceptions import ValidationError from django.forms import CharField from django.utils.translation import gettext_lazy as _ import shortuuid def short_uuid4(): return shortuuid.encode(uuid.uuid4()) def decode(value): """Decode the value from ShortUUID t...
native_shortuuid/fields.py
import uuid import django.db.models from django.core.exceptions import ValidationError from django.forms import CharField from django.utils.translation import gettext_lazy as _ import shortuuid def short_uuid4(): return shortuuid.encode(uuid.uuid4()) def decode(value): """Decode the value from ShortUUID t...
0.542379
0.135032
import os from functools import lru_cache from aws_cdk.aws_efs import IAccessPoint from aws_cdk.aws_lambda import Code, Runtime, FileSystem as LambdaFileSystem, Function from aws_cdk.aws_s3 import Bucket from aws_cdk.core import Stack, Duration from aws_cdk.lambda_layer_awscli import AwsCliLayer from b_cfn_s3_large_d...
b_cfn_s3_large_deployment/function.py
import os from functools import lru_cache from aws_cdk.aws_efs import IAccessPoint from aws_cdk.aws_lambda import Code, Runtime, FileSystem as LambdaFileSystem, Function from aws_cdk.aws_s3 import Bucket from aws_cdk.core import Stack, Duration from aws_cdk.lambda_layer_awscli import AwsCliLayer from b_cfn_s3_large_d...
0.417628
0.048812
from torch.nn import functional as F from dassl.engine import TRAINER_REGISTRY, TrainerX from dassl.metrics import compute_accuracy from torch.cuda.amp import autocast from dassl.utils import count_num_param from dassl.optim import build_optimizer, build_lr_scheduler from dassl.modeling import build_backbone @TRAINE...
dassl/engine/dg/rsc.py
from torch.nn import functional as F from dassl.engine import TRAINER_REGISTRY, TrainerX from dassl.metrics import compute_accuracy from torch.cuda.amp import autocast from dassl.utils import count_num_param from dassl.optim import build_optimizer, build_lr_scheduler from dassl.modeling import build_backbone @TRAINE...
0.809803
0.308333
from discord.ext.commands import group import math import discord class Math: def __init__(self, bot): self.bot = bot @group(invoke_without_command=True, aliases=["maths"]) async def math(self, ctx): """Various mathematical functions, collected for your enjoyment.""" if ctx.invoke...
cogs/math.py
from discord.ext.commands import group import math import discord class Math: def __init__(self, bot): self.bot = bot @group(invoke_without_command=True, aliases=["maths"]) async def math(self, ctx): """Various mathematical functions, collected for your enjoyment.""" if ctx.invoke...
0.718002
0.286609
from PySide2 import QtCore qt_resource_data = b"\ \x00\x00\x08\xd9\ \x89\ PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\ \x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\ \x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\ \x01IR$\xf0\x00\x00\x05\xf1iTXtXML\ :com.adobe.xmp\x00\x00\ \x00\x00\x00<?xpacket beg\ in=\...
conversor_divisor/resources_cd_rc.py
from PySide2 import QtCore qt_resource_data = b"\ \x00\x00\x08\xd9\ \x89\ PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\ \x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\ \x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\ \x01IR$\xf0\x00\x00\x05\xf1iTXtXML\ :com.adobe.xmp\x00\x00\ \x00\x00\x00<?xpacket beg\ in=\...
0.270288
0.279853
import benchmarkstt.docblock as docblock from textwrap import dedent import pytest def test_text(): txt = " \t \t\n\n\t " assert docblock.process_rst(txt, 'text') == '' txt = ''' .. code-block:: text Some block In samem block Still included Not anymore ''' print(...
tests/benchmarkstt/test_docblock.py
import benchmarkstt.docblock as docblock from textwrap import dedent import pytest def test_text(): txt = " \t \t\n\n\t " assert docblock.process_rst(txt, 'text') == '' txt = ''' .. code-block:: text Some block In samem block Still included Not anymore ''' print(...
0.372277
0.486758
import numpy as np import pandas as pd import sys import matplotlib matplotlib.use("pgf") import time from matplotlib import pyplot as plt from sklearn.model_selection import GridSearchCV, TimeSeriesSplit from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error, mean_absolute_error ...
src/health_lstm.py
import numpy as np import pandas as pd import sys import matplotlib matplotlib.use("pgf") import time from matplotlib import pyplot as plt from sklearn.model_selection import GridSearchCV, TimeSeriesSplit from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error, mean_absolute_error ...
0.70912
0.322033
import configargparse from pathlib import Path from icalendar import Calendar, Event import datetime import os import requests parser = configargparse.ArgParser(default_config_files=['~/.config/calreader.ini'],description=""" Downloads a webcal file and schedules an external file to run at the beginn...
calreader2.py
import configargparse from pathlib import Path from icalendar import Calendar, Event import datetime import os import requests parser = configargparse.ArgParser(default_config_files=['~/.config/calreader.ini'],description=""" Downloads a webcal file and schedules an external file to run at the beginn...
0.255251
0.159512
import pprint import re # noqa: F401 import six from swagger_client.configuration import Configuration class TpdmStaffTeacherPreparationProviderAssociation(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes:...
src/v5.1/resources/swagger_client/models/tpdm_staff_teacher_preparation_provider_association.py
import pprint import re # noqa: F401 import six from swagger_client.configuration import Configuration class TpdmStaffTeacherPreparationProviderAssociation(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes:...
0.64791
0.102125
import io import typing as t from django_docker_helpers.config.backends.base import BaseParser from django_docker_helpers.config.exceptions import KVStorageValueIsEmpty from .yaml_parser import YamlParser class RedisParser(BaseParser): """ Reads a whole config bundle from a redis key and provides the unifie...
django_docker_helpers/config/backends/redis_parser.py
import io import typing as t from django_docker_helpers.config.backends.base import BaseParser from django_docker_helpers.config.exceptions import KVStorageValueIsEmpty from .yaml_parser import YamlParser class RedisParser(BaseParser): """ Reads a whole config bundle from a redis key and provides the unifie...
0.817975
0.123102
import numpy as np from time import time from math import sqrt, ceil, floor, log import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import scipy.integrate as integrate # find the primes up to and including limit def sieve_of_eratosthenes(limit): limit = floor(limit) possible_prim...
Prototypes/Graph Plots/prime_counting_function_plot.py
import numpy as np from time import time from math import sqrt, ceil, floor, log import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import scipy.integrate as integrate # find the primes up to and including limit def sieve_of_eratosthenes(limit): limit = floor(limit) possible_prim...
0.806472
0.49585
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = [ 'GetVantagePointsResult', 'AwaitableGetVantagePointsResult', 'get_vantage_points', ] @pulumi.output_t...
sdk/python/pulumi_oci/healthchecks/get_vantage_points.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = [ 'GetVantagePointsResult', 'AwaitableGetVantagePointsResult', 'get_vantage_points', ] @pulumi.output_t...
0.778607
0.17522
import arcpy import os.path import os import sys from pprint import pprint import pdb records = [108814,109019,116056,116097,123383,167,191,203,210,290,306,310,321,406,414,422,432,440,514,518,56995,56997,57000,57002,57004,57172,57174,57177,57178,57181,57182,57186,57241,57242,57440,57694,57695,57699,57702,58041,58042,...
defineProjections.py
import arcpy import os.path import os import sys from pprint import pprint import pdb records = [108814,109019,116056,116097,123383,167,191,203,210,290,306,310,321,406,414,422,432,440,514,518,56995,56997,57000,57002,57004,57172,57174,57177,57178,57181,57182,57186,57241,57242,57440,57694,57695,57699,57702,58041,58042,...
0.221098
0.064594
from digitalsky_provider.models import DigitalSkyLog from gcs_operations.models import CloudFile, FlightPlan, FlightOperation, Transaction, FlightPermission, FlightLog from pki_framework.models import AerobridgeCredential from registry.models import Person, Address, Activity, Authorization, Operator, Contact, Test, Typ...
tests/test_models/test_models_delete.py
from digitalsky_provider.models import DigitalSkyLog from gcs_operations.models import CloudFile, FlightPlan, FlightOperation, Transaction, FlightPermission, FlightLog from pki_framework.models import AerobridgeCredential from registry.models import Person, Address, Activity, Authorization, Operator, Contact, Test, Typ...
0.606848
0.507141
from constants import EOS_TOKEN, MAX_LENGTH, DEVICE import numpy as np import torch class Lang: def __init__(self, name): self.name = name self.word2index = {} self.word2count = {} self.index2word = {0: "SOS", 1: "EOS"} self.n_words = 2 # Count SOS and EOS def addSe...
src/Learning/preprocessing.py
from constants import EOS_TOKEN, MAX_LENGTH, DEVICE import numpy as np import torch class Lang: def __init__(self, name): self.name = name self.word2index = {} self.word2count = {} self.index2word = {0: "SOS", 1: "EOS"} self.n_words = 2 # Count SOS and EOS def addSe...
0.516352
0.322206
import sys from config import * INT_MIN = -sys.maxsize - 1 def reversed_kronecker(cell_1: int, cell_2: int): """ This function determines the interaction between cell_1 and cell_2. Here were are going to implement a reversed Kronecker Delta function ie. if the two cells are the same, they will not intera...
research/cpm-vqe/interaction_helper.py
import sys from config import * INT_MIN = -sys.maxsize - 1 def reversed_kronecker(cell_1: int, cell_2: int): """ This function determines the interaction between cell_1 and cell_2. Here were are going to implement a reversed Kronecker Delta function ie. if the two cells are the same, they will not intera...
0.804675
0.866923
import re from calendar import monthrange from datetime import datetime from bs4 import BeautifulSoup from requests import get from .console import console from .logger import logger from .sanitize import sanitize_metar, sanitize_taf TODAY = datetime.now() OGIMET_LIMIT_MESAGE = "#Sorry, Your quota limit for slow qu...
tafver_metars/download.py
import re from calendar import monthrange from datetime import datetime from bs4 import BeautifulSoup from requests import get from .console import console from .logger import logger from .sanitize import sanitize_metar, sanitize_taf TODAY = datetime.now() OGIMET_LIMIT_MESAGE = "#Sorry, Your quota limit for slow qu...
0.347094
0.177882
from operator import itemgetter # 3rd party import numpy from domdf_python_tools.paths import PathPlus # ========================== print("Part One") # ========================== lines = PathPlus("input.txt").read_lines() earliest = int(lines[0]) buses = sorted(map(int, filter(str.isdigit, lines[1].split(',')))) p...
13/code.py
from operator import itemgetter # 3rd party import numpy from domdf_python_tools.paths import PathPlus # ========================== print("Part One") # ========================== lines = PathPlus("input.txt").read_lines() earliest = int(lines[0]) buses = sorted(map(int, filter(str.isdigit, lines[1].split(',')))) p...
0.544801
0.344251
def autoencoder (epoch, batch, latent, encoder_o, encoder_i, \ decoder_i, decoder_o, train_percent, lam, norm_order, loss_plot): """ This module is autoencoder neural network which gets input data and reduces the dimension and returns similar data to the input. Data compression is useful for future...
autoencoder.py
def autoencoder (epoch, batch, latent, encoder_o, encoder_i, \ decoder_i, decoder_o, train_percent, lam, norm_order, loss_plot): """ This module is autoencoder neural network which gets input data and reduces the dimension and returns similar data to the input. Data compression is useful for future...
0.919995
0.908374
# 利用华为ups检测机房是否停电 # 停电后发送企业微信告警并对主要服务器关机 import sys import os import time import ssl import json import http.cookiejar import paramiko from urllib import parse, request # ----------------------企业微信配置开始------------------------------------ corpid = '你自己的pid' corpsecret = '你自己的key' wx_url = 'https://qyapi.weixin.q...
web_login.py
# 利用华为ups检测机房是否停电 # 停电后发送企业微信告警并对主要服务器关机 import sys import os import time import ssl import json import http.cookiejar import paramiko from urllib import parse, request # ----------------------企业微信配置开始------------------------------------ corpid = '你自己的pid' corpsecret = '你自己的key' wx_url = 'https://qyapi.weixin.q...
0.164852
0.110136
import numpy as np import pandas as pd from math import floor import sys from .erorrs import NotBinaryData, NoSuchColumn def warn(*args, **kwargs): pass import warnings warnings.warn = warn class ICOTE def __init__(self, binary_columns : list = None, seed : 'int > 0' = 42) -> None: ''' ...
crucio/ICOTE.py
import numpy as np import pandas as pd from math import floor import sys from .erorrs import NotBinaryData, NoSuchColumn def warn(*args, **kwargs): pass import warnings warnings.warn = warn class ICOTE def __init__(self, binary_columns : list = None, seed : 'int > 0' = 42) -> None: ''' ...
0.457621
0.403802
import numpy as np import pandas as pd from netfile.ipeds_file import IpedsFile from database.ipeds_grad_rates import IpedsGraduationRate from database.date_dimension import DateRow from database.ipeds_demographic_dimension import IpedsDemographicDimension class GraduationRateFile(IpedsFile): def __init__(self, ...
netfile/graduation_rate_file.py
import numpy as np import pandas as pd from netfile.ipeds_file import IpedsFile from database.ipeds_grad_rates import IpedsGraduationRate from database.date_dimension import DateRow from database.ipeds_demographic_dimension import IpedsDemographicDimension class GraduationRateFile(IpedsFile): def __init__(self, ...
0.219505
0.128689
import getpass import pyaes import sqlite3 import hashlib import string import random conn = None _name_lock = None class Key: _k = None @staticmethod def set(key: bytes): if key is None: Key._k = None return Key._k = list(key) for i in range(len(Key._k))...
mysecure.py
import getpass import pyaes import sqlite3 import hashlib import string import random conn = None _name_lock = None class Key: _k = None @staticmethod def set(key: bytes): if key is None: Key._k = None return Key._k = list(key) for i in range(len(Key._k))...
0.241042
0.056159
from typing import Dict, List, Optional, Union import torch import torch.nn as nn import torch.nn.functional as F __all__ = [ "build_act", "ConvLayer", "LinearLayer", "SELayer", "DsConvLayer", "InvertedBlock", "SeInvertedBlock", "ResidualBlock", "OpSequential", ] def build_norm(n...
netaug/models/base/layers.py
from typing import Dict, List, Optional, Union import torch import torch.nn as nn import torch.nn.functional as F __all__ = [ "build_act", "ConvLayer", "LinearLayer", "SELayer", "DsConvLayer", "InvertedBlock", "SeInvertedBlock", "ResidualBlock", "OpSequential", ] def build_norm(n...
0.967271
0.409044
import os import sys import csv import re from math import ceil from typing import Union import pandas as pd import dask.dataframe as dd import argparse from timeit import default_timer as timer from enum import Enum from PIL import Image from pathlib import Path from collections import namedtuple from misc import re...
etl.py
import os import sys import csv import re from math import ceil from typing import Union import pandas as pd import dask.dataframe as dd import argparse from timeit import default_timer as timer from enum import Enum from PIL import Image from pathlib import Path from collections import namedtuple from misc import re...
0.536313
0.201931
import socket from sshuttle.firewall import subnet_weight from sshuttle.linux import nft, nft_get_handle, nonfatal from sshuttle.methods import BaseMethod class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle at the same t...
lib/python/lib/python3.6/site-packages/sshuttle-0.78.5.dev35+gaaa6684-py3.6.egg/sshuttle/methods/nft.py
import socket from sshuttle.firewall import subnet_weight from sshuttle.linux import nft, nft_get_handle, nonfatal from sshuttle.methods import BaseMethod class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle at the same t...
0.379378
0.131034
import pandas import scipy import numpy def identity(x): return x def rolling_apply(df, window_size, f, trim=True, **kargs): ''' A function that will apply a window wise operation to the rows of a dataframe, df. input: df - a pandas dataframe window_size...
transformations.py
import pandas import scipy import numpy def identity(x): return x def rolling_apply(df, window_size, f, trim=True, **kargs): ''' A function that will apply a window wise operation to the rows of a dataframe, df. input: df - a pandas dataframe window_size...
0.764496
0.723926
""" Turing machine internals testing module """ from __future__ import unicode_literals, print_function from turing import (TMSyntaxError, TMLocked, tokenizer, raw_rule_generator, sequence_cant_have, evaluate_symbol_query, TuringMachine) from pytest import raises, mark p = mark.parametrize class ...
test_turing.py
""" Turing machine internals testing module """ from __future__ import unicode_literals, print_function from turing import (TMSyntaxError, TMLocked, tokenizer, raw_rule_generator, sequence_cant_have, evaluate_symbol_query, TuringMachine) from pytest import raises, mark p = mark.parametrize class ...
0.747063
0.645288
import glob import threading import subprocess from pathlib import Path from typing import * from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm from .utils import progress_save EXTRACT_SCRIPT = (Path(__file__).parent / "extract.py").resolve() assert EXTRACT_SCRIPT.exists() def main(): with p...
script/compile_all.py
import glob import threading import subprocess from pathlib import Path from typing import * from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm from .utils import progress_save EXTRACT_SCRIPT = (Path(__file__).parent / "extract.py").resolve() assert EXTRACT_SCRIPT.exists() def main(): with p...
0.303938
0.163245
from smtplib import SMTP from abc import ABCMeta, abstractmethod from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class EMailManager: __metaclass__ = ABCMeta @abstractmethod def __init__(self): raise NotImplemented @abstractmethod def __enter__(self): ...
notifier.py
from smtplib import SMTP from abc import ABCMeta, abstractmethod from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class EMailManager: __metaclass__ = ABCMeta @abstractmethod def __init__(self): raise NotImplemented @abstractmethod def __enter__(self): ...
0.474875
0.084568
import pygame from pygame.locals import * from snake_classes import * from constantes import * import time global t0 t0 = time.time() pygame.init() fenetre = pygame.display.set_mode((window_side,window_side+50)) fenetre.fill(WHITE) pygame.display.set_caption(titre_fenetre) grid = Grid(fenetre) grid.display() sna...
Snake.py
import pygame from pygame.locals import * from snake_classes import * from constantes import * import time global t0 t0 = time.time() pygame.init() fenetre = pygame.display.set_mode((window_side,window_side+50)) fenetre.fill(WHITE) pygame.display.set_caption(titre_fenetre) grid = Grid(fenetre) grid.display() sna...
0.206334
0.169372
from ..constants import ( COLOR_CANVAS_DARK, COLOR_CANVAS_LIGHT, COLOR_GRID_LIGHT, COLOR_GRID_DARK, COLOR_PLOT_TEXT_LIGHT, COLOR_PLOT_TEXT_DARK, COLOR_SLIDER_BORDER_DARK, COLOR_SLIDER_BORDER_LIGHT, COLOR_SLIDER_TICK_DARK, COLOR_SLIDER_TICK_LIGHT, COLOR_ZERO_LINE_LIGHT, CO...
src/pyskindose/plotting/plot_settings.py
from ..constants import ( COLOR_CANVAS_DARK, COLOR_CANVAS_LIGHT, COLOR_GRID_LIGHT, COLOR_GRID_DARK, COLOR_PLOT_TEXT_LIGHT, COLOR_PLOT_TEXT_DARK, COLOR_SLIDER_BORDER_DARK, COLOR_SLIDER_BORDER_LIGHT, COLOR_SLIDER_TICK_DARK, COLOR_SLIDER_TICK_LIGHT, COLOR_ZERO_LINE_LIGHT, CO...
0.778776
0.18866
from datetime import datetime, timedelta from flask import Blueprint, current_app, abort, request, jsonify from flask_jwt_extended import ( create_access_token, jwt_required, jwt_optional, get_jwt_identity) from .. import db from ..models import User from ..providers import ProviderError from ..utils import valid...
app/controllers/auth.py
from datetime import datetime, timedelta from flask import Blueprint, current_app, abort, request, jsonify from flask_jwt_extended import ( create_access_token, jwt_required, jwt_optional, get_jwt_identity) from .. import db from ..models import User from ..providers import ProviderError from ..utils import valid...
0.652241
0.101278
from __future__ import unicode_literals from django.db import migrations, models import assets.asset_helpers import django.core.files.storage class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Asset', fields=[ ...
assets/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import assets.asset_helpers import django.core.files.storage class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Asset', fields=[ ...
0.524151
0.121113
from aliyunsdkcore.request import RpcRequest from aliyunsdkvpc.endpoint import endpoint_data class ListVirtualPhysicalConnectionsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Vpc', '2016-04-28', 'ListVirtualPhysicalConnections','vpc') self.set_method('POST') if hasattr(self, "endpoint_m...
aliyun-python-sdk-vpc/aliyunsdkvpc/request/v20160428/ListVirtualPhysicalConnectionsRequest.py
from aliyunsdkcore.request import RpcRequest from aliyunsdkvpc.endpoint import endpoint_data class ListVirtualPhysicalConnectionsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Vpc', '2016-04-28', 'ListVirtualPhysicalConnections','vpc') self.set_method('POST') if hasattr(self, "endpoint_m...
0.387459
0.052887
import scrapy import time import psycopg2 import json import requests from scrapy_djangoitem import DjangoItem from home.models import Publisher from scrapy_djangoitem import DjangoItem from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait fr...
facebbok/facebbok/spiders/FBCrawlerWithDBCheck.py
import scrapy import time import psycopg2 import json import requests from scrapy_djangoitem import DjangoItem from home.models import Publisher from scrapy_djangoitem import DjangoItem from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait fr...
0.167355
0.050565
from __future__ import division import numpy as np from astropy.io import fits from math import fsum from warnings import warn # TODO: Investigate using scipy.fftpack instead? def pad_and_rfft_image(img, newshape): """ Pads the psf array to the size described by imgshape, then run rfft to put it in Fourie...
psfMC/utils.py
from __future__ import division import numpy as np from astropy.io import fits from math import fsum from warnings import warn # TODO: Investigate using scipy.fftpack instead? def pad_and_rfft_image(img, newshape): """ Pads the psf array to the size described by imgshape, then run rfft to put it in Fourie...
0.611614
0.579757
import pandas as pd from flask import Blueprint, request, jsonify from src.extraction.data_management import Data from src.metrics.cust_metric import get_auc_score from src.predict import make_prediction, get_models_list from src import __version__ as _version from api.config import get_logger from api.validation impo...
api/controller.py
import pandas as pd from flask import Blueprint, request, jsonify from src.extraction.data_management import Data from src.metrics.cust_metric import get_auc_score from src.predict import make_prediction, get_models_list from src import __version__ as _version from api.config import get_logger from api.validation impo...
0.69035
0.165998
import asyncio import logging import random import re import textwrap from typing import Any, Dict import aiohttp import async_timeout import discord from discord.ext.commands import AutoShardedBot, Context, command, bot_has_permissions from bot.converters import Snake from bot.decorators import locked from bot.utils...
bot/cogs/snakes.py
import asyncio import logging import random import re import textwrap from typing import Any, Dict import aiohttp import async_timeout import discord from discord.ext.commands import AutoShardedBot, Context, command, bot_has_permissions from bot.converters import Snake from bot.decorators import locked from bot.utils...
0.67971
0.124372
from __future__ import print_function from __future__ import division import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection # test modelselection works with validation dataset def test_modelselection_...
h2o-py/tests/testdir_algos/modelselection/pyunit_PUBDEV_8235_modelselection_gaussian_validation.py
from __future__ import print_function from __future__ import division import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection # test modelselection works with validation dataset def test_modelselection_...
0.419291
0.231973
from unittest import TestSuite import mock from requests import HTTPError from contacthub.workspace import Workspace from contacthub._api_manager._api_customer import _CustomerAPIManager from tests.utility import FakeHTTPResponse class TestCustomerAPIManager(TestSuite): @classmethod def setUp(cls): ...
tests/test_api_customer.py
from unittest import TestSuite import mock from requests import HTTPError from contacthub.workspace import Workspace from contacthub._api_manager._api_customer import _CustomerAPIManager from tests.utility import FakeHTTPResponse class TestCustomerAPIManager(TestSuite): @classmethod def setUp(cls): ...
0.504394
0.218732
import tensorflow as tf from typing import Optional, Tuple, Any from utils.tfutils import get_activation, apply_noise from .cell_utils import ugrnn class UGRNNCell(tf.compat.v1.nn.rnn_cell.RNNCell): def __init__(self, units: int, activation: str, name: str, recurrent_noise: tf.Tensor): self._units = uni...
budget-rnn/src/layers/cells/standard_rnn_cells.py
import tensorflow as tf from typing import Optional, Tuple, Any from utils.tfutils import get_activation, apply_noise from .cell_utils import ugrnn class UGRNNCell(tf.compat.v1.nn.rnn_cell.RNNCell): def __init__(self, units: int, activation: str, name: str, recurrent_noise: tf.Tensor): self._units = uni...
0.943387
0.298528
import numpy as np import gym from gym import spaces from path_following.envs.envUtils import utils from colorama import Fore, Style class Tool5D(gym.Env): metadata = {'render.modes': ['human', 'rgb_array']} def __init__(self): super(Tool5D, self).__init__() "Initialize environment variables...
path_following/envs/tcp_Tool5D.py
import numpy as np import gym from gym import spaces from path_following.envs.envUtils import utils from colorama import Fore, Style class Tool5D(gym.Env): metadata = {'render.modes': ['human', 'rgb_array']} def __init__(self): super(Tool5D, self).__init__() "Initialize environment variables...
0.49707
0.374104
import os import numpy as np import tensorflow.keras.backend as K from sklearn.base import BaseEstimator, TransformerMixin from tensorflow.keras import regularizers from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.layers import Dense, Input from tensorflow.keras.models import Model class Au...
code/ae.py
import os import numpy as np import tensorflow.keras.backend as K from sklearn.base import BaseEstimator, TransformerMixin from tensorflow.keras import regularizers from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.layers import Dense, Input from tensorflow.keras.models import Model class Au...
0.68056
0.208179
import re import time import string import itertools as it import numpy as np import numba as nb class ParserException (Exception): """ Class to represent parser's exceptions """ @nb.vectorize(nopython = True, cache = True) def np_bitwise_maj (x, y, z): """ Bitwise MAJ function """ return (x & y) | (x &...
parser.py
import re import time import string import itertools as it import numpy as np import numba as nb class ParserException (Exception): """ Class to represent parser's exceptions """ @nb.vectorize(nopython = True, cache = True) def np_bitwise_maj (x, y, z): """ Bitwise MAJ function """ return (x & y) | (x &...
0.585338
0.413536
import ast import operator from peval.tools import Dispatcher, immutableadict, ast_equal, replace_fields from peval.core.gensym import GenSym from peval.core.reify import KnownValue, is_known_value, reify from peval.wisdom import is_pure, get_signature from peval.core.callable import inspect_callable from peval.tools ...
peval/core/expression.py
import ast import operator from peval.tools import Dispatcher, immutableadict, ast_equal, replace_fields from peval.core.gensym import GenSym from peval.core.reify import KnownValue, is_known_value, reify from peval.wisdom import is_pure, get_signature from peval.core.callable import inspect_callable from peval.tools ...
0.63023
0.356615
from leapp.libraries.common import multipathutil _regexes = ('vendor', 'product', 'revision', 'product_blacklist', 'devnode', 'wwid', 'property', 'protocol') def _update_config(need_foreign, need_allow_usb, config): if not (need_foreign or need_allow_usb or config.invalid_regexes_exist): retu...
repos/system_upgrade/el8toel9/actors/multipathconfupdate/libraries/multipathconfupdate.py
from leapp.libraries.common import multipathutil _regexes = ('vendor', 'product', 'revision', 'product_blacklist', 'devnode', 'wwid', 'property', 'protocol') def _update_config(need_foreign, need_allow_usb, config): if not (need_foreign or need_allow_usb or config.invalid_regexes_exist): retu...
0.206414
0.118717
from arrays import Array import warnings class Array2D(Array): def __init__(self, r, c): self.capacity = r self.__arr = Array2D.__create_arr(r, c) def __create_arr(r, c): arr = [] for i in range(r): arr.append(Array(c)) return arr def __getitem__(self,...
influence/array/multiarray.py
from arrays import Array import warnings class Array2D(Array): def __init__(self, r, c): self.capacity = r self.__arr = Array2D.__create_arr(r, c) def __create_arr(r, c): arr = [] for i in range(r): arr.append(Array(c)) return arr def __getitem__(self,...
0.447943
0.190705
from .utils import serializable_dict class Change(object): def __init__(self, key, value, old_value=None, **kwargs): self.key = key self.value = value self.old_value = old_value self.metadata = kwargs or {} def __repr__(self): return serializable_dict(self.__dict__) ...
kronos/diff.py
from .utils import serializable_dict class Change(object): def __init__(self, key, value, old_value=None, **kwargs): self.key = key self.value = value self.old_value = old_value self.metadata = kwargs or {} def __repr__(self): return serializable_dict(self.__dict__) ...
0.77552
0.169269
import ast import astor import sys from x2paddle.project_convertor.pytorch.mapper import * import copy import os.path as osp from .utils import get_dep_file_path class DepInfo: """ 依赖包信息。 PT_FROM代表pytorch from信息的字符串,例如:torch; PD_FROM代表paddle from信息的字符串,例如:paddle; PT_IMPORT代表pytorch import信息系的字符串,...
x2paddle/project_convertor/pytorch/ast_update.py
import ast import astor import sys from x2paddle.project_convertor.pytorch.mapper import * import copy import os.path as osp from .utils import get_dep_file_path class DepInfo: """ 依赖包信息。 PT_FROM代表pytorch from信息的字符串,例如:torch; PD_FROM代表paddle from信息的字符串,例如:paddle; PT_IMPORT代表pytorch import信息系的字符串,...
0.342242
0.204521
from unittest import TestCase from nistbeacon.nistbeaconcrypto import NistBeaconCrypto from unittest.mock import ( Mock, patch, ) class TestNistBeaconCrypto(TestCase): @classmethod def setUpClass(cls): cls.verifier2013 = "_VERIFIER_20130905" cls.verifier2013_timestamp = 1378395540 ...
tests/unit/nistbeacon/test_nistbeaconcrypto.py
from unittest import TestCase from nistbeacon.nistbeaconcrypto import NistBeaconCrypto from unittest.mock import ( Mock, patch, ) class TestNistBeaconCrypto(TestCase): @classmethod def setUpClass(cls): cls.verifier2013 = "_VERIFIER_20130905" cls.verifier2013_timestamp = 1378395540 ...
0.820073
0.537041
r""" ================ Error Middleware ================ .. versionadded:: 0.2.0 Middleware to handle errors in aiohttp applications. Usage ===== .. code-block:: python import re from aiohttp import web from aiohttp_middlewares import error_context, error_middleware # Default error handler asy...
aiohttp_middlewares/error.py
r""" ================ Error Middleware ================ .. versionadded:: 0.2.0 Middleware to handle errors in aiohttp applications. Usage ===== .. code-block:: python import re from aiohttp import web from aiohttp_middlewares import error_context, error_middleware # Default error handler asy...
0.871721
0.157947
from random import uniform, choice from tqdm import tqdm from functools import partial from p_tqdm import p_map from .backtest import backtest from .utils.getters import get_strategy from numpy import isnan, nan import warnings warnings.simplefilter(action='ignore', category=Warning) def populate(size, config_range):...
yuzu/optimize.py
from random import uniform, choice from tqdm import tqdm from functools import partial from p_tqdm import p_map from .backtest import backtest from .utils.getters import get_strategy from numpy import isnan, nan import warnings warnings.simplefilter(action='ignore', category=Warning) def populate(size, config_range):...
0.371023
0.273356
import gym import logging from d4rl.pointmaze import waypoint_controller from d4rl.pointmaze import maze_model import numpy as np import pickle import gzip import h5py import argparse # python scripts/generate_maze2d_datasets.py --env-name maze2d-open-v0 --fixed-target # python scripts/generate_maze2d_datasets.py --en...
scripts/generate_maze2d_datasets.py
import gym import logging from d4rl.pointmaze import waypoint_controller from d4rl.pointmaze import maze_model import numpy as np import pickle import gzip import h5py import argparse # python scripts/generate_maze2d_datasets.py --env-name maze2d-open-v0 --fixed-target # python scripts/generate_maze2d_datasets.py --en...
0.368292
0.243401
import pytest from main import process_and_cleanup # Testing the base parsing for if/else def test_cleanup_graph_base_if(): graph = process_and_cleanup("TestFiles/pytest/if_normal_test_file.COB") assert graph.get_size() == 3 # Testing simple branches for if/else def test_cleanup_graph_base_if_left_branch():...
src/Test/test_cleanup_graph.py
import pytest from main import process_and_cleanup # Testing the base parsing for if/else def test_cleanup_graph_base_if(): graph = process_and_cleanup("TestFiles/pytest/if_normal_test_file.COB") assert graph.get_size() == 3 # Testing simple branches for if/else def test_cleanup_graph_base_if_left_branch():...
0.304145
0.592018
# # Explore highly co-expressed genes # In the previous [notebook](2_explore_corr_of_genes.ipynb) we observed that using 39 samples with 201 PAO1-specific genes, that the correlation of accessory-accessory genes is higher compared to the correlation of core-core and core-accessory genes. # # Based on this finding, we...
archive/pilot_experiment/nbconverted/4_explore_coExpressed_genes.py
# # Explore highly co-expressed genes # In the previous [notebook](2_explore_corr_of_genes.ipynb) we observed that using 39 samples with 201 PAO1-specific genes, that the correlation of accessory-accessory genes is higher compared to the correlation of core-core and core-accessory genes. # # Based on this finding, we...
0.79166
0.69246
import os from os import listdir from os.path import isfile, join import numpy as np import skimage import skimage.io as io from PIL import Image import matplotlib.pyplot as plt lfsize = [372, 540, 8, 8] def normalize_lf(lf): return 2.0*(lf-0.5) def denormalize_lf(lf): return lf/2.0+0.5 def read_eslf(filena...
lfutil.py
import os from os import listdir from os.path import isfile, join import numpy as np import skimage import skimage.io as io from PIL import Image import matplotlib.pyplot as plt lfsize = [372, 540, 8, 8] def normalize_lf(lf): return 2.0*(lf-0.5) def denormalize_lf(lf): return lf/2.0+0.5 def read_eslf(filena...
0.197135
0.373219
import re def le_assinatura(): ''' A função lê os valores dos traços linguísticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos. Returns: (list): Retorna uma lista com todos os dados digitados pelo usuário. ''' print("Bem-vindo ao detector automático d...
Parte 1/Semana 9/CohPiah.py
import re def le_assinatura(): ''' A função lê os valores dos traços linguísticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos. Returns: (list): Retorna uma lista com todos os dados digitados pelo usuário. ''' print("Bem-vindo ao detector automático d...
0.501953
0.505798
import os, glob, re import argparse import uuid import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, Dataset from torch.utils.data.dataloader import default_collate from torchvision import transforms import torchvision import matplotli...
som-diffusion/finetune_ae.py
import os, glob, re import argparse import uuid import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, Dataset from torch.utils.data.dataloader import default_collate from torchvision import transforms import torchvision import matplotli...
0.855142
0.286104
import argparse from glob import glob from itertools import chain import logging import math import os import re import sys from time import sleep from prettytable import PrettyTable import pytz import yaml from investing import __version__ from investing import conf, InvestingLogging from investing.data import Portfol...
launcher.py
import argparse from glob import glob from itertools import chain import logging import math import os import re import sys from time import sleep from prettytable import PrettyTable import pytz import yaml from investing import __version__ from investing import conf, InvestingLogging from investing.data import Portfol...
0.494385
0.180612
import asyncio from datetime import datetime import re import sys from io import StringIO from aiogram import Bot, Dispatcher from aiogram.dispatcher.filters import Filter from aiogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery from aiogram.utils.exceptions import MessageNotModifie...
cw3_kamikadze_bot.py
import asyncio from datetime import datetime import re import sys from io import StringIO from aiogram import Bot, Dispatcher from aiogram.dispatcher.filters import Filter from aiogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery from aiogram.utils.exceptions import MessageNotModifie...
0.355439
0.117876
__version__ = '0.0.1' # Helix ALM REST API: http://help.seapine.com/helixalm/rest-api/index.html API_PATH = { # Projects Requests for retrieving and switching projects. 'projects': '/projects', # Security Requ...
helixalm/const.py
__version__ = '0.0.1' # Helix ALM REST API: http://help.seapine.com/helixalm/rest-api/index.html API_PATH = { # Projects Requests for retrieving and switching projects. 'projects': '/projects', # Security Requ...
0.436382
0.068475
import substratools as tools import os import keras from keras import backend as K from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D # input image dimensions img_rows, img_cols = 28, 28 input_shape = (img_rows, img_cols, 1) num_classes = ...
examples/mnist/assets/algo_cnn/algo.py
import substratools as tools import os import keras from keras import backend as K from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D # input image dimensions img_rows, img_cols = 28, 28 input_shape = (img_rows, img_cols, 1) num_classes = ...
0.837221
0.341761
import os from collections import defaultdict import threading from tempfile import NamedTemporaryFile try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse try: from functools import lru_cache # python 3 except ImportError: from cachetools.func import lru_cache impo...
gbdxtools/rda/fetch/conc/libcurl/select.py
import os from collections import defaultdict import threading from tempfile import NamedTemporaryFile try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse try: from functools import lru_cache # python 3 except ImportError: from cachetools.func import lru_cache impo...
0.205894
0.095392
import pytest from django.test import TestCase, override_settings from .utils import MIDDLEWARES_FOR_TESTING class TestResponseFunctionWithoutUser(TestCase): def test_middleware_simple_get_request(self): try: self.client.get('/restframework/simple/') except Exception as e: ...
tests/test_restframework_response.py
import pytest from django.test import TestCase, override_settings from .utils import MIDDLEWARES_FOR_TESTING class TestResponseFunctionWithoutUser(TestCase): def test_middleware_simple_get_request(self): try: self.client.get('/restframework/simple/') except Exception as e: ...
0.279828
0.197039
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from random import shuffle, randint from six.moves import range from itertools import product from . import ( BaseMazeGame, WithWaterAndBlocksMixin, RewardOnE...
py/mazebase/games/goal_based_games.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from random import shuffle, randint from six.moves import range from itertools import product from . import ( BaseMazeGame, WithWaterAndBlocksMixin, RewardOnE...
0.750004
0.238002
from pyox.oozie import Oozie from pyox.client import ServiceError import argparse import sys import os import json from datetime import datetime def oozie_start_command(client,argv): cmdparser = argparse.ArgumentParser(prog='pyox oozie start',description='start') cmdparser.add_argument( '-p','--property', ...
pyox/oozie_command.py
from pyox.oozie import Oozie from pyox.client import ServiceError import argparse import sys import os import json from datetime import datetime def oozie_start_command(client,argv): cmdparser = argparse.ArgumentParser(prog='pyox oozie start',description='start') cmdparser.add_argument( '-p','--property', ...
0.176814
0.060418
from pathlib import Path import json import torch from torch.utils.data import Dataset from collections import defaultdict from lib.image import imread, imread_to_gray from torchvision import transforms def transpose_dict(d): dt = defaultdict(list) for k, v in d.items(): dt[v].append(k) return dt...
lib/datasets.py
from pathlib import Path import json import torch from torch.utils.data import Dataset from collections import defaultdict from lib.image import imread, imread_to_gray from torchvision import transforms def transpose_dict(d): dt = defaultdict(list) for k, v in d.items(): dt[v].append(k) return dt...
0.77949
0.315921
from __future__ import annotations import dataclasses import os import typing as t from .io import ( read_text_file, ) from .util import ( ANSIBLE_TEST_TARGET_ROOT, ) from .util_common import ( ShellScriptTemplate, set_shebang, ) from .core_ci import ( SshKey, ) @dataclasses.dataclass class B...
venv/lib/python3.8/site-packages/ansible_test/_internal/bootstrap.py
from __future__ import annotations import dataclasses import os import typing as t from .io import ( read_text_file, ) from .util import ( ANSIBLE_TEST_TARGET_ROOT, ) from .util_common import ( ShellScriptTemplate, set_shebang, ) from .core_ci import ( SshKey, ) @dataclasses.dataclass class B...
0.802207
0.09899
from typing import TypeVar, Generic, Callable, Optional, Tuple import math from algo1 import Array from linkedlist import LinkedList import linkedlist K = TypeVar('K') V = TypeVar('V') W = TypeVar('W') class Dic(Generic[K, V]): """ The dictionary class """ def __init__(self, _size : int, ...
libdic.py
from typing import TypeVar, Generic, Callable, Optional, Tuple import math from algo1 import Array from linkedlist import LinkedList import linkedlist K = TypeVar('K') V = TypeVar('V') W = TypeVar('W') class Dic(Generic[K, V]): """ The dictionary class """ def __init__(self, _size : int, ...
0.934223
0.416263
from cvxpy.atoms import (bmat, cumsum, diag, kron, conv, abs, reshape, trace, upper_tri, conj, imag, real, norm1, norm_inf, Pnorm, sigma_max, lambda_max, lambda_sum_largest, log_det, QuadForm, Ma...
cvxpy/reductions/complex2real/atom_canonicalizers/__init__.py
from cvxpy.atoms import (bmat, cumsum, diag, kron, conv, abs, reshape, trace, upper_tri, conj, imag, real, norm1, norm_inf, Pnorm, sigma_max, lambda_max, lambda_sum_largest, log_det, QuadForm, Ma...
0.675551
0.403684
import decimal import pickle import tempfile from heapq import heappop, heappush import numpy as np from gwas import Gwas from pvalue_handler import PvalueHandler from vcf import Vcf def test_convert_pval_to_neg_log10(): p_value_handler = PvalueHandler() assert p_value_handler.neg_log_of_decimal(decimal.Dec...
test/test_vcf.py
import decimal import pickle import tempfile from heapq import heappop, heappush import numpy as np from gwas import Gwas from pvalue_handler import PvalueHandler from vcf import Vcf def test_convert_pval_to_neg_log10(): p_value_handler = PvalueHandler() assert p_value_handler.neg_log_of_decimal(decimal.Dec...
0.558327
0.519399
import numpy as np from ..core.utils import indices_len, fix_loc, filter_cols from ..table.module import TableModule from ..table.table import Table import numexpr as ne def make_local(df, px): arr = df.to_array() result = {} class _Aux: pass aux = _Aux() for i, n in enumerate(df.columns): ...
progressivis/linalg/nexpr.py
import numpy as np from ..core.utils import indices_len, fix_loc, filter_cols from ..table.module import TableModule from ..table.table import Table import numexpr as ne def make_local(df, px): arr = df.to_array() result = {} class _Aux: pass aux = _Aux() for i, n in enumerate(df.columns): ...
0.355216
0.257018
import argparse from datetime import datetime import numpy as np import seaborn as sns from matplotlib import pyplot as plt from make_table import get_table def get_schoopy_plot(table, error_bars=True): fig, ax = plt.subplots(figsize=(20, 9)) models = set(table.model) test_datas = set(table.test_data) ...
deepthinking/data_analysis/make_schoop.py
import argparse from datetime import datetime import numpy as np import seaborn as sns from matplotlib import pyplot as plt from make_table import get_table def get_schoopy_plot(table, error_bars=True): fig, ax = plt.subplots(figsize=(20, 9)) models = set(table.model) test_datas = set(table.test_data) ...
0.493164
0.499878
import ctypes from ctypes import wintypes from . import com from . import winapi from .wintype import HRESULT, BSTR, CIMTYPE _In_ = 1 _Out_ = 2 IWbemObjectSink_Indicate_Idx = 3 IWbemObjectSink_SetStatus_Idx = 4 class IWbemObjectSink(com.IUnknown): def Indicate(self, object_count, obj_array): protot...
cwmi/wmi.py
import ctypes from ctypes import wintypes from . import com from . import winapi from .wintype import HRESULT, BSTR, CIMTYPE _In_ = 1 _Out_ = 2 IWbemObjectSink_Indicate_Idx = 3 IWbemObjectSink_SetStatus_Idx = 4 class IWbemObjectSink(com.IUnknown): def Indicate(self, object_count, obj_array): protot...
0.331552
0.100437
import numpy as np import torch from tqdm import tqdm import os from warnings import warn from nsgt import NSGT_sliced, LogScale, LinScale, MelScale, OctScale, SndReader, BarkScale, VQLogScale from nsgt_orig import NSGT_sliced as NSGT_sliced_old import time from argparse import ArgumentParser parser = ArgumentParser(...
examples/benchmark.py
import numpy as np import torch from tqdm import tqdm import os from warnings import warn from nsgt import NSGT_sliced, LogScale, LinScale, MelScale, OctScale, SndReader, BarkScale, VQLogScale from nsgt_orig import NSGT_sliced as NSGT_sliced_old import time from argparse import ArgumentParser parser = ArgumentParser(...
0.466846
0.121869
from utils import update_model, save_simple_metrics_report, get_model_performance_test_set from sklearn.model_selection import train_test_split, cross_validate, GridSearchCV from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.ensemble import GradientBoostingRegressor import logg...
src/train.py
from utils import update_model, save_simple_metrics_report, get_model_performance_test_set from sklearn.model_selection import train_test_split, cross_validate, GridSearchCV from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.ensemble import GradientBoostingRegressor import logg...
0.494873
0.336195
import pytest import os import numpy as np from numpy.linalg import eigvalsh from openfermion import QubitOperator, InteractionOperator, get_sparse_operator, get_ground_state from zquantum.core.openfermion import save_qubit_operator_set, load_qubit_operator_set, save_interaction_operator, load_interaction_operator, l...
steps/operators_test.py
import pytest import os import numpy as np from numpy.linalg import eigvalsh from openfermion import QubitOperator, InteractionOperator, get_sparse_operator, get_ground_state from zquantum.core.openfermion import save_qubit_operator_set, load_qubit_operator_set, save_interaction_operator, load_interaction_operator, l...
0.259263
0.406214
import numpy as np import scipy as sp class Quad_Sampler(object): """ Class for drawing samples from an arbitrary one-dimensional probability distribution using numerical integration and interpolation. In general this will be superior to more sophisticated sampling methods for 1D problems. Assu...
mst_ida/analysis/samplers.py
import numpy as np import scipy as sp class Quad_Sampler(object): """ Class for drawing samples from an arbitrary one-dimensional probability distribution using numerical integration and interpolation. In general this will be superior to more sophisticated sampling methods for 1D problems. Assu...
0.892457
0.697467
"""Export current configuration of an Anthos cluster.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.anthos import anthoscli_backend from googlecloudsdk.command_lib.anthos import...
lib/surface/anthos/export.py
"""Export current configuration of an Anthos cluster.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.anthos import anthoscli_backend from googlecloudsdk.command_lib.anthos import...
0.719679
0.167015
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from parameters import param_keys #ToDo : explore idea to give parameter as placeholder to varying size in # validation. Think is not possible, because batch size is defined when val #...
modules/iterators/train_iterator.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from parameters import param_keys #ToDo : explore idea to give parameter as placeholder to varying size in # validation. Think is not possible, because batch size is defined when val #...
0.786664
0.184694
import pytest import numpy as np import jax import pyscf from pyscfad import gto from pyscfad.lib import numpy as jnp TOL_VAL = 1e-12 TOL_NUC = 1e-10 TOL_CS = 1e-10 TOL_EXP = 1e-9 TOL_NUC2 = 5e-9 TEST_SET = ["int1e_ovlp", "int1e_kin", "int1e_nuc", "int1e_rinv",] TEST_SET_ECP = ["ECPscalar"] TEST_SET_NUC =...
pyscfad/gto/test/test_int1e.py
import pytest import numpy as np import jax import pyscf from pyscfad import gto from pyscfad.lib import numpy as jnp TOL_VAL = 1e-12 TOL_NUC = 1e-10 TOL_CS = 1e-10 TOL_EXP = 1e-9 TOL_NUC2 = 5e-9 TEST_SET = ["int1e_ovlp", "int1e_kin", "int1e_nuc", "int1e_rinv",] TEST_SET_ECP = ["ECPscalar"] TEST_SET_NUC =...
0.28279
0.433142