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
def extractAllaboutmynothingsBlogspotCom(item): ''' Parser for 'allaboutmynothings.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Yasashii Shinjitsu to Seiryaku Kekkon', 'Ya...
WebMirror/management/rss_parser_funcs/feed_parse_extractAllaboutmynothingsBlogspotCom.py
def extractAllaboutmynothingsBlogspotCom(item): ''' Parser for 'allaboutmynothings.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Yasashii Shinjitsu to Seiryaku Kekkon', 'Ya...
0.135118
0.13707
from numpy import * from scipy.misc import imsave def quartic_kernel(x): if not (-1.0 < x < 1.0): return 0.0 return 15.0 / 16.0 * (1 - x ** 2) ** 2 class Gradient: def __init__(self): self.colors = [] self.steps = [] def add_color(self, color, step): self.colors.appe...
utils/gencolormaps.py
from numpy import * from scipy.misc import imsave def quartic_kernel(x): if not (-1.0 < x < 1.0): return 0.0 return 15.0 / 16.0 * (1 - x ** 2) ** 2 class Gradient: def __init__(self): self.colors = [] self.steps = [] def add_color(self, color, step): self.colors.appe...
0.583678
0.417717
import os import codecs import operator import json import itertools import numpy as np def load_data(dataset='unknown', location='./data/', maxlen=None, seed=1234, limit_cls=1000): """ Loads a dataset. Expects dataset to exist in 'location' directory as ...
dataset.py
import os import codecs import operator import json import itertools import numpy as np def load_data(dataset='unknown', location='./data/', maxlen=None, seed=1234, limit_cls=1000): """ Loads a dataset. Expects dataset to exist in 'location' directory as ...
0.609059
0.527073
import numpy as np import math import extendedMD.dtwdist as dtwdist def prune_motifs_with_mdl(ts, motif_dic_list, r): """ This function returns the most relevant motifs from the original list of motif extracted from the emd algorithm, based on the computed MDL cost and avoiding overlapping motifs :pa...
extendedMD/pruning.py
import numpy as np import math import extendedMD.dtwdist as dtwdist def prune_motifs_with_mdl(ts, motif_dic_list, r): """ This function returns the most relevant motifs from the original list of motif extracted from the emd algorithm, based on the computed MDL cost and avoiding overlapping motifs :pa...
0.723212
0.736211
from django.shortcuts import render, redirect from proofs.models import Proposition, Proof from .forms import MajorSubmissionForm from .typeChecker import * from django.urls import reverse def home(request): concobj = [] conclusions = Proof.objects.all() for obj in conclusions: concobj.append(obj.conclusion) re...
deductivereasoning/proofs/views.py
from django.shortcuts import render, redirect from proofs.models import Proposition, Proof from .forms import MajorSubmissionForm from .typeChecker import * from django.urls import reverse def home(request): concobj = [] conclusions = Proof.objects.all() for obj in conclusions: concobj.append(obj.conclusion) re...
0.373876
0.153803
import torch import torch.nn as nn import numpy as np from utils import softminus import math import numbers from torch.nn import functional as F class SubNet(nn.ModuleList): def __init__(self, list): super(SubNet, self).__init__(list) def forward(self, input): output = input for l in...
source/segment/nnmf.py
import torch import torch.nn as nn import numpy as np from utils import softminus import math import numbers from torch.nn import functional as F class SubNet(nn.ModuleList): def __init__(self, list): super(SubNet, self).__init__(list) def forward(self, input): output = input for l in...
0.950365
0.578151
from thetae import Forecast from thetae.util import localized_date_to_utc from datetime import timedelta import requests import pandas as pd default_model_name = 'Climacell' def get_climacell_forecast(stid, lat, lon, api_key, forecast_date): # Retrieve data api_url = 'https://api.climacell.co/v3/weather/for...
thetae/data_parsers/climacell.py
from thetae import Forecast from thetae.util import localized_date_to_utc from datetime import timedelta import requests import pandas as pd default_model_name = 'Climacell' def get_climacell_forecast(stid, lat, lon, api_key, forecast_date): # Retrieve data api_url = 'https://api.climacell.co/v3/weather/for...
0.651577
0.259521
import telethon from telethon import TelegramClient from telethon.tl.functions.channels import JoinChannelRequest from redis import Redis import random, json, pymysql import asyncio from my_db import DbHelper #实例化一个redis redis_obj = Redis(host='localhost',port=6379,password='<PASSWORD>',decode_responses=True,charset='U...
telegram_api/task/group/add_group.py
import telethon from telethon import TelegramClient from telethon.tl.functions.channels import JoinChannelRequest from redis import Redis import random, json, pymysql import asyncio from my_db import DbHelper #实例化一个redis redis_obj = Redis(host='localhost',port=6379,password='<PASSWORD>',decode_responses=True,charset='U...
0.087847
0.096791
from docopt import docopt import numpy as np import os import bob.io.image import bob.io.base import tensorflow as tf import sys from datetime import datetime def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _int64_feature(value): return tf.train.Feature(i...
cnn_training/vgg2_2_tfrecords.py
from docopt import docopt import numpy as np import os import bob.io.image import bob.io.base import tensorflow as tf import sys from datetime import datetime def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _int64_feature(value): return tf.train.Feature(i...
0.459076
0.243597
from __future__ import unicode_literals from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse_lazy CONTACT_FORM_USE_CAPTCHA = getattr(settings, 'CONTACT_FORM_USE_CAPTCHA', False) CONTACT_FORM_USE_SIGNALS = getattr(settings, 'CONTACT_FORM_U...
contact_form/conf/settings.py
from __future__ import unicode_literals from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse_lazy CONTACT_FORM_USE_CAPTCHA = getattr(settings, 'CONTACT_FORM_USE_CAPTCHA', False) CONTACT_FORM_USE_SIGNALS = getattr(settings, 'CONTACT_FORM_U...
0.292899
0.064418
import re import json import bs4 from michiru import modules, personalities ## Module information. __name__ = 'uribot.fourchan' __author__ = 'Shiz' __license__ = 'WTFPL' __desc__ = 'Gives URL information for 4chan links.' __deps__ = ['uribot'] URI_REGEXP = re.compile(r'^https?://boards\.4chan\.org/([a-z0-9]+)/thre...
michiru/modules/uribot/fourchan.py
import re import json import bs4 from michiru import modules, personalities ## Module information. __name__ = 'uribot.fourchan' __author__ = 'Shiz' __license__ = 'WTFPL' __desc__ = 'Gives URL information for 4chan links.' __deps__ = ['uribot'] URI_REGEXP = re.compile(r'^https?://boards\.4chan\.org/([a-z0-9]+)/thre...
0.288369
0.138637
from math import floor from astropy.time import Time from sqlalchemy import Column, String, Integer, BigInteger, Text from . import MCDeclarativeBase class SubsystemError(MCDeclarativeBase): """ Definition of subsystem_error table. Attributes ---------- id : BigInteger Column Autoincreme...
hera_mc/subsystem_error.py
from math import floor from astropy.time import Time from sqlalchemy import Column, String, Integer, BigInteger, Text from . import MCDeclarativeBase class SubsystemError(MCDeclarativeBase): """ Definition of subsystem_error table. Attributes ---------- id : BigInteger Column Autoincreme...
0.890425
0.34054
import datetime from PyQt5 import QtWidgets, QtCore, QtGui from src.utils.log_system import LogSystem from src.widgets.syntax_highlighter import SyntaxHighlighter from src.hack_compiler import HackAssemblyCompiler, InvalidSyntaxException, InternalException class ActionSy...
src/utils/action_system.py
import datetime from PyQt5 import QtWidgets, QtCore, QtGui from src.utils.log_system import LogSystem from src.widgets.syntax_highlighter import SyntaxHighlighter from src.hack_compiler import HackAssemblyCompiler, InvalidSyntaxException, InternalException class ActionSy...
0.280222
0.072571
import os, copy, logging import torch from torch import nn from allennlp.modules.conditional_random_field import ConditionalRandomField from util import func as H from . import transformer as T class EmbeddingClfHead(T.BaseClfHead): def __init__(self, config, lm_model, lm_config, embed_type='w2v', w2v_path=No...
modules/embedding.py
import os, copy, logging import torch from torch import nn from allennlp.modules.conditional_random_field import ConditionalRandomField from util import func as H from . import transformer as T class EmbeddingClfHead(T.BaseClfHead): def __init__(self, config, lm_model, lm_config, embed_type='w2v', w2v_path=No...
0.779406
0.209167
from multiprocessing import Event import grpc import pytest from uuid import uuid4 from google.protobuf import json_format from google.protobuf.empty_pb2 import Empty from common.cryptographer import Cryptographer, hash_160 from teos.watcher import Watcher from teos.responder import Responder from teos.gatekeeper im...
test/teos/unit/test_internal_api.py
from multiprocessing import Event import grpc import pytest from uuid import uuid4 from google.protobuf import json_format from google.protobuf.empty_pb2 import Empty from common.cryptographer import Cryptographer, hash_160 from teos.watcher import Watcher from teos.responder import Responder from teos.gatekeeper im...
0.396419
0.11427
import math import zipfile import os import xml.etree.ElementTree as ElementTree import copy import urllib.request import shutil import tempfile from or_datasets import Bunch from typing import List, Tuple, Optional def fetch_vrp_rep(name: str, instance: str = None, return_raw=True) -> Bunch: """ Fetches data...
or_datasets/vrp_rep.py
import math import zipfile import os import xml.etree.ElementTree as ElementTree import copy import urllib.request import shutil import tempfile from or_datasets import Bunch from typing import List, Tuple, Optional def fetch_vrp_rep(name: str, instance: str = None, return_raw=True) -> Bunch: """ Fetches data...
0.648689
0.69022
import datetime, threading, time from abc import abstractmethod from typing import Mapping from sqlalchemy import MetaData, Table, Column, Integer, String, ForeignKey from sqlalchemy.orm import mapper, relationship, reconstructor from cassiopeia.dto.common import DtoObject metadata = MetaData() class SQLBaseObject(...
cassiopeia-sqlstore/cassiopeia_sqlstore/common.py
import datetime, threading, time from abc import abstractmethod from typing import Mapping from sqlalchemy import MetaData, Table, Column, Integer, String, ForeignKey from sqlalchemy.orm import mapper, relationship, reconstructor from cassiopeia.dto.common import DtoObject metadata = MetaData() class SQLBaseObject(...
0.751739
0.224608
import logging import os import subprocess from pip.basecommand import Command from pip.commands.show import search_packages_info from pip.status_codes import SUCCESS, ERROR from pip._vendor import pkg_resources import sys class ViewCommand(Command): """ Views the package source directory with the editor de...
pipview/view.py
import logging import os import subprocess from pip.basecommand import Command from pip.commands.show import search_packages_info from pip.status_codes import SUCCESS, ERROR from pip._vendor import pkg_resources import sys class ViewCommand(Command): """ Views the package source directory with the editor de...
0.234933
0.067087
import torch from kaolin.metrics import tetmesh class TestTetMeshMetrics: def test_tetrahedron_volume(self): tetrahedrons = torch.tensor([[[[0.5000, 0.5000, 0.4500], [0.4500, 0.5000, 0.5000], [0.4750, 0.4500, 0.4500], ...
tests/python/kaolin/metrics/test_tetmesh.py
import torch from kaolin.metrics import tetmesh class TestTetMeshMetrics: def test_tetrahedron_volume(self): tetrahedrons = torch.tensor([[[[0.5000, 0.5000, 0.4500], [0.4500, 0.5000, 0.5000], [0.4750, 0.4500, 0.4500], ...
0.652906
0.680877
import os import requests from django import forms from utilities.exceptions import CloudBoltException from resourcehandlers.forms import ( BaseResourceHandlerCredentialsForm, BaseResourceHandlerSettingsForm, ) from .models import RhevResourceHandler from infrastructure.models import Environment from ovirtsdk4 i...
forms.py
import os import requests from django import forms from utilities.exceptions import CloudBoltException from resourcehandlers.forms import ( BaseResourceHandlerCredentialsForm, BaseResourceHandlerSettingsForm, ) from .models import RhevResourceHandler from infrastructure.models import Environment from ovirtsdk4 i...
0.560493
0.043937
__all__ = ['DirectScrolledWindowFrame'] from panda3d.core import * from direct.gui import DirectGuiGlobals as DGG from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectButton import DirectButton from direct.gui.DirectScrolledFrame import DirectScrolledFrame class DirectScrolledWindowFrame(DirectScrolle...
DirectGuiExtension/DirectScrolledWindowFrame.py
__all__ = ['DirectScrolledWindowFrame'] from panda3d.core import * from direct.gui import DirectGuiGlobals as DGG from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectButton import DirectButton from direct.gui.DirectScrolledFrame import DirectScrolledFrame class DirectScrolledWindowFrame(DirectScrolle...
0.565299
0.296158
from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from sara_flexbe_states.SetKey import SetKey from flexbe_states.log_key_state import LogKeyState from sara_flexbe_states.sara_set_head_angle import SaraSetHeadAngle from sara_flexbe_states.list_entities_...
sara_flexbe_behaviors/src/sara_flexbe_behaviors/action_count_sm.py
from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from sara_flexbe_states.SetKey import SetKey from flexbe_states.log_key_state import LogKeyState from sara_flexbe_states.sara_set_head_angle import SaraSetHeadAngle from sara_flexbe_states.list_entities_...
0.311532
0.241808
STATS = [ { "num_node_expansions": 0, "search_time": 0.0127327, "total_time": 0.0637178, "plan_length": 64, "plan_cost": 64, "objects_used": 264, "objects_total": 374, "neural_net_time": 0.09185624122619629, "num_replanning_steps": 14, ...
scenegraph/exp-official/taskographyv4tiny5_hierarchical/hierarchical_test_stats.py
STATS = [ { "num_node_expansions": 0, "search_time": 0.0127327, "total_time": 0.0637178, "plan_length": 64, "plan_cost": 64, "objects_used": 264, "objects_total": 374, "neural_net_time": 0.09185624122619629, "num_replanning_steps": 14, ...
0.276886
0.516535
import os import numpy as np import pandas as pd from keras.optimizers import Adam class WordEmbedder: """ WordEmbedder is a helper class for every embedding algorithms. It does extract all possible words, adjacency matrix, corpus from the given sequences. It is parent class of SkipGram, F...
seqlearner/WordEmbedder.py
import os import numpy as np import pandas as pd from keras.optimizers import Adam class WordEmbedder: """ WordEmbedder is a helper class for every embedding algorithms. It does extract all possible words, adjacency matrix, corpus from the given sequences. It is parent class of SkipGram, F...
0.769167
0.501343
import time import numpy as np from tensorflow.keras import Input, layers from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras.regularizers import l2 from tensorflow.keras.utils import plot_model from imple...
stft-cnn-fault-diagnosis/without_stft.py
import time import numpy as np from tensorflow.keras import Input, layers from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras.regularizers import l2 from tensorflow.keras.utils import plot_model from imple...
0.648244
0.342049
import math from jsonargparse import ArgumentParser, ActionParser import torch from .attack_factory import AttackFactory as AF class RandomAttackFactory(object): def __init__( self, attack_types, min_eps=1e-5, max_eps=0.1, min_snr=30, max_snr=60, min_alpha=...
hyperion/torch/adv_attacks/random_attack_factory.py
import math from jsonargparse import ArgumentParser, ActionParser import torch from .attack_factory import AttackFactory as AF class RandomAttackFactory(object): def __init__( self, attack_types, min_eps=1e-5, max_eps=0.1, min_snr=30, max_snr=60, min_alpha=...
0.7797
0.133839
from I3Tray import * from icecube import icetray, dataclasses, dataio, simclasses from os.path import expandvars import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import pylab from optparse import OptionParser parser = OptionParser() parser.add_option("-i","--infile", dest="INFILE", ...
sim-services/resources/gcd_validation/details/validate_stress_test_samples.py
from I3Tray import * from icecube import icetray, dataclasses, dataio, simclasses from os.path import expandvars import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import pylab from optparse import OptionParser parser = OptionParser() parser.add_option("-i","--infile", dest="INFILE", ...
0.281504
0.120957
import dash import dash_core_components as dcc import dash_html_components as html from matplotlib import pyplot as plt import pandas as pd import numpy as np import plotly.graph_objs as go from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import StandardScaler from sklearn.model_selection i...
heroku/app.py
import dash import dash_core_components as dcc import dash_html_components as html from matplotlib import pyplot as plt import pandas as pd import numpy as np import plotly.graph_objs as go from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import StandardScaler from sklearn.model_selection i...
0.406862
0.266174
import sys import array import struct from . import errors from . import wire_format class OutputStream(object): """Contains all logic for writing bits, and ToString() to get the result.""" def __init__(self): self._buffer = array.array('B') if sys.version_info < (3, 3): def append_raw_...
odps/tunnel/pb/output_stream.py
import sys import array import struct from . import errors from . import wire_format class OutputStream(object): """Contains all logic for writing bits, and ToString() to get the result.""" def __init__(self): self._buffer = array.array('B') if sys.version_info < (3, 3): def append_raw_...
0.486575
0.277228
import datetime import testtools from mock import patch import oslo_messaging as messaging from oslo_config import cfg from oslo_log import log as logging from designate import exceptions from designate.central import service as central_service from designate.tests.test_api.test_v1 import ApiV1Test LOG = logging.ge...
designate/tests/test_api/test_v1/test_domains.py
import datetime import testtools from mock import patch import oslo_messaging as messaging from oslo_config import cfg from oslo_log import log as logging from designate import exceptions from designate.central import service as central_service from designate.tests.test_api.test_v1 import ApiV1Test LOG = logging.ge...
0.496094
0.42937
import pytest from crummycm.validation.validation import validate from example_templates.component.config_dict.a import ( cd_outer, no_cd_single, no_cd_single_nested, ) ex_config = { "cd_outer": ( ( { "my_mixed": { "kd_num": 0, ...
tests/unit/validate/test_dict_cd.py
import pytest from crummycm.validation.validation import validate from example_templates.component.config_dict.a import ( cd_outer, no_cd_single, no_cd_single_nested, ) ex_config = { "cd_outer": ( ( { "my_mixed": { "kd_num": 0, ...
0.541894
0.413359
from pathlib import Path from statistics import median from typing import Optional POINTS = {")": 3, "]": 57, "}": 1197, ">": 25137} AUTOCOMPLETE_POINTS = {")": 1, "]": 2, "}": 3, ">": 4} def read_syntax_file(path: Path) -> list[str]: with open(path, "r") as file: return file.read().split("\n") def ch...
advent/day_10.py
from pathlib import Path from statistics import median from typing import Optional POINTS = {")": 3, "]": 57, "}": 1197, ">": 25137} AUTOCOMPLETE_POINTS = {")": 1, "]": 2, "}": 3, ">": 4} def read_syntax_file(path: Path) -> list[str]: with open(path, "r") as file: return file.read().split("\n") def ch...
0.763484
0.374991
from .GoogleTokenSpan import GoogleTokenSpan from .GoogleSentiment import GoogleSentiment class GoogleMention(GoogleTokenSpan): def __init__(self, dictionary, document, entity): text = dictionary.pop('text') content = text.pop('content') begin = text.pop('begin_offset') end = begin + len(content) super()._...
linguistics/google/GoogleEntity.py
from .GoogleTokenSpan import GoogleTokenSpan from .GoogleSentiment import GoogleSentiment class GoogleMention(GoogleTokenSpan): def __init__(self, dictionary, document, entity): text = dictionary.pop('text') content = text.pop('content') begin = text.pop('begin_offset') end = begin + len(content) super()._...
0.767777
0.205954
from unittest import TestCase, mock import unittest from buf import libraries import os import sys import tempfile class TestMakeDir(TestCase): """Tests buf.libraries.make_library.""" def test_already_exists(self): """Tests that the function raises an error if the directory it is trying to create alre...
tests/test_libraries.py
from unittest import TestCase, mock import unittest from buf import libraries import os import sys import tempfile class TestMakeDir(TestCase): """Tests buf.libraries.make_library.""" def test_already_exists(self): """Tests that the function raises an error if the directory it is trying to create alre...
0.563858
0.503662
import fnmatch import re import collections from zlib import adler32 from typing import ByteString, Iterable, Callable, Union from .. import arg, Unit from ...lib.tools import isbuffer def pathspec(expression): """ Normalizes a path which is separated by backward or forward slashes to be s...
refinery/units/formats/__init__.py
import fnmatch import re import collections from zlib import adler32 from typing import ByteString, Iterable, Callable, Union from .. import arg, Unit from ...lib.tools import isbuffer def pathspec(expression): """ Normalizes a path which is separated by backward or forward slashes to be s...
0.759091
0.099645
from os import environ from pathlib import Path import envdir import sentry_sdk from configurations import Configuration from sentry_sdk.integrations.django import DjangoIntegration # Common settings BASE_DIR = Path(__file__).absolute().parent.parent PROJECT_NAME = "{{cookiecutter.project_name}}" CONFIGURATION = env...
{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/settings.py
from os import environ from pathlib import Path import envdir import sentry_sdk from configurations import Configuration from sentry_sdk.integrations.django import DjangoIntegration # Common settings BASE_DIR = Path(__file__).absolute().parent.parent PROJECT_NAME = "{{cookiecutter.project_name}}" CONFIGURATION = env...
0.63307
0.133528
import pandas as pd import requests from bs4 import BeautifulSoup from tqdm import tqdm import argparse import sys #TESTING URLS # "https://www.imdb.com/title/tt5753856" DARK # "https://www.imdb.com/title/tt0098904" SEINFLED # "https://www.imdb.com/title/tt0306414" THEWIRE # "https://www.imdb.com/title/tt0096697" Simp...
IMDB Data Scraper/scrape.py
import pandas as pd import requests from bs4 import BeautifulSoup from tqdm import tqdm import argparse import sys #TESTING URLS # "https://www.imdb.com/title/tt5753856" DARK # "https://www.imdb.com/title/tt0098904" SEINFLED # "https://www.imdb.com/title/tt0306414" THEWIRE # "https://www.imdb.com/title/tt0096697" Simp...
0.174692
0.162148
from antlr4 import * # This class defines a complete listener for a parse tree produced by QrogueDungeonParser. class QrogueDungeonListener(ParseTreeListener): # Enter a parse tree produced by QrogueDungeonParser#start. def enterStart(self, ctx): pass # Exit a parse tree produced by QrogueDungeon...
qrogue/game/world/dungeon_generator/dungeon_parser/QrogueDungeonListener.py
from antlr4 import * # This class defines a complete listener for a parse tree produced by QrogueDungeonParser. class QrogueDungeonListener(ParseTreeListener): # Enter a parse tree produced by QrogueDungeonParser#start. def enterStart(self, ctx): pass # Exit a parse tree produced by QrogueDungeon...
0.307462
0.14978
import torch def l2norm(tensor, dim, keepdim): """ Computes the l2-norm of elements in input tensor. :param tensor: PyTorch tensor. :type tensor: `torch.nn.Module` :param dim: Reduction dimension. :type dim: `int` :param keepdim: Whether the output has `dim` retained. :type keepdim: `...
condensa/functional.py
import torch def l2norm(tensor, dim, keepdim): """ Computes the l2-norm of elements in input tensor. :param tensor: PyTorch tensor. :type tensor: `torch.nn.Module` :param dim: Reduction dimension. :type dim: `int` :param keepdim: Whether the output has `dim` retained. :type keepdim: `...
0.968329
0.878366
import sqlite3 import argparse import datetime import chtc_usage_tools as cut import matplotlib.pyplot as plt import matplotlib.dates as mpld import matplotlib as mpl from numpy import array mpl.rcParams['axes.color_cycle'] = ['r', 'k', 'c'] parser = argparse.ArgumentParser(description='A tool to extract usage data'...
extractUsage.py
import sqlite3 import argparse import datetime import chtc_usage_tools as cut import matplotlib.pyplot as plt import matplotlib.dates as mpld import matplotlib as mpl from numpy import array mpl.rcParams['axes.color_cycle'] = ['r', 'k', 'c'] parser = argparse.ArgumentParser(description='A tool to extract usage data'...
0.281307
0.249304
import uuid import pygame from dataclasses import dataclass from ..style import Color from ..structures import Vec2 from . import physics Model = physics.Model vec2 = physics.vec2 @dataclass class Component: entity_id = None def update(self, delta) -> None: pass @property def class_name(self):...
gg/ecs/components.py
import uuid import pygame from dataclasses import dataclass from ..style import Color from ..structures import Vec2 from . import physics Model = physics.Model vec2 = physics.vec2 @dataclass class Component: entity_id = None def update(self, delta) -> None: pass @property def class_name(self):...
0.892773
0.402627
import matplotlib.pyplot as plt import cv2 import numpy as np import pandas as pd from tensorflow.keras.models import Model, Sequential from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Reshape,LeakyReLU, Dropout import tensorflow as tf from tensorflow.keras.layers import AveragePooling2D,UpSampling2...
colorize_train.py
import matplotlib.pyplot as plt import cv2 import numpy as np import pandas as pd from tensorflow.keras.models import Model, Sequential from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Reshape,LeakyReLU, Dropout import tensorflow as tf from tensorflow.keras.layers import AveragePooling2D,UpSampling2...
0.664867
0.400632
from flask import abort, escape, Flask, render_template, request, session from functools import wraps import json import sys import uuid app = Flask(__name__, static_folder="static") # Decorators def requires_admin(f): @wraps(f) def decorated_function(*args, **kwargs): if "team_id" not in session or...
app.py
from flask import abort, escape, Flask, render_template, request, session from functools import wraps import json import sys import uuid app = Flask(__name__, static_folder="static") # Decorators def requires_admin(f): @wraps(f) def decorated_function(*args, **kwargs): if "team_id" not in session or...
0.340485
0.119691
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('customer_id', models.AutoField(prima...
APMS/apps/orders/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('customer_id', models.AutoField(prima...
0.5564
0.205157
# standards import re # canif from .parser import ParserError RE_SKIPPED = re.compile(r'(?:\s+|//.*)+') RE_END = re.compile(r'$') class Lexer: """ Splits the input text into tokens, i.e. the smallest, indivisible strings in the text. Instances of this class keep track of where they are in the text, a...
canif/lexer.py
# standards import re # canif from .parser import ParserError RE_SKIPPED = re.compile(r'(?:\s+|//.*)+') RE_END = re.compile(r'$') class Lexer: """ Splits the input text into tokens, i.e. the smallest, indivisible strings in the text. Instances of this class keep track of where they are in the text, a...
0.683947
0.531574
import warnings import numpy as np import pandas as pd import pytest from sklearn.metrics import auc, confusion_matrix, matthews_corrcoef, roc_curve from sklearn.preprocessing import binarize from src.models.metrics_utils import (confusion_matrix_to_dataframe, mcc_auc_score, mcc_...
tests/src/models/test_metrics_utils.py
import warnings import numpy as np import pandas as pd import pytest from sklearn.metrics import auc, confusion_matrix, matthews_corrcoef, roc_curve from sklearn.preprocessing import binarize from src.models.metrics_utils import (confusion_matrix_to_dataframe, mcc_auc_score, mcc_...
0.852537
0.616618
from genshibasic.genshi import Genshi from genshibasic.lexer import Lexer import unittest class LexerTestSuite(unittest.TestCase): def test_hello(self): tokens = self.__lex('hello') self.assertEqual(len(tokens), 1) self.assertEqual(tokens[0].pos, (1, 5)) self.assertEqual(tokens[0]...
test/test_lexer.py
from genshibasic.genshi import Genshi from genshibasic.lexer import Lexer import unittest class LexerTestSuite(unittest.TestCase): def test_hello(self): tokens = self.__lex('hello') self.assertEqual(len(tokens), 1) self.assertEqual(tokens[0].pos, (1, 5)) self.assertEqual(tokens[0]...
0.555918
0.547646
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from argparse import ArgumentParser import threading import json import logging as log import commands class ERROR_CODE: PARSE_ERROR = -32700 # Invalid JSON was received by the server. INVALID_REQ = -32600 # The JSON sent is not a ...
sdntestbed_source/sdntestbed/python/novaconsole-master/rpcserver.py
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from argparse import ArgumentParser import threading import json import logging as log import commands class ERROR_CODE: PARSE_ERROR = -32700 # Invalid JSON was received by the server. INVALID_REQ = -32600 # The JSON sent is not a ...
0.605799
0.072276
import urllib2 import time import random from datetime import timedelta from bs4 import BeautifulSoup from google.appengine.api import urlfetch from models.models import Match, Map, Server def scrape_matches(pages=2): """ gets match statistics from oc.tc/matches pages last_page - the highest match ...
src/controllers/scraper.py
import urllib2 import time import random from datetime import timedelta from bs4 import BeautifulSoup from google.appengine.api import urlfetch from models.models import Match, Map, Server def scrape_matches(pages=2): """ gets match statistics from oc.tc/matches pages last_page - the highest match ...
0.197677
0.162579
import sys import aws_lambda_wsgi import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output sys.path.append('.') from pangea import about, sampling_numbers, sampling_period # noqa: E402 from app import app # noqa: E402 ...
index.py
import sys import aws_lambda_wsgi import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output sys.path.append('.') from pangea import about, sampling_numbers, sampling_period # noqa: E402 from app import app # noqa: E402 ...
0.381104
0.214609
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule from ansible_collec...
venv/lib/python3.6/site-packages/ansible_collections/f5networks/f5_modules/tests/unit/modules/network/f5/test_bigip_ucs.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule from ansible_collec...
0.426919
0.279165
from enum import Enum ROWS = 6 COLS = 7 class Color(Enum): RED = 1 BLACK = 2 class Board: def __init__(self): self.grid = list() for _ in range(COLS): col = list() for _ in range(ROWS): col.append(None) self.grid.append(col) se...
solutions/problem_219.py
from enum import Enum ROWS = 6 COLS = 7 class Color(Enum): RED = 1 BLACK = 2 class Board: def __init__(self): self.grid = list() for _ in range(COLS): col = list() for _ in range(ROWS): col.append(None) self.grid.append(col) se...
0.568176
0.235394
from docopt import docopt import os import yaml import json def main(args): output_filename = args['--output'] input_path = args['--input'] input_paths = [] templates = [] templates_target_path = args['--target-templates-path'] templates = [] for root, directories, files in os.walk(input...
scripts/gen_data_templates.py
from docopt import docopt import os import yaml import json def main(args): output_filename = args['--output'] input_path = args['--input'] input_paths = [] templates = [] templates_target_path = args['--target-templates-path'] templates = [] for root, directories, files in os.walk(input...
0.189071
0.078148
from lewis.adapters.stream import StreamInterface from lewis.core.logging import has_log from lewis.utils.command_builder import CmdBuilder from lewis.utils.replies import conditional_reply from .dfkps_base import CommonStreamInterface import logging __all__ = ["Danfysik9X00StreamInterface"] @has_log class Danfysi...
lewis_emulators/danfysik/interfaces/dfkps_9X00.py
from lewis.adapters.stream import StreamInterface from lewis.core.logging import has_log from lewis.utils.command_builder import CmdBuilder from lewis.utils.replies import conditional_reply from .dfkps_base import CommonStreamInterface import logging __all__ = ["Danfysik9X00StreamInterface"] @has_log class Danfysi...
0.685002
0.144511
from ..translate import ( win_agg, win_over, win_cumul, sql_scalar, sql_agg, RankOver, wrap_annotate, annotate, extend_base, SqlTranslator, ) from .base import ( SqlColumn, SqlColumnAgg, base_scalar, base_win, base_agg ) import sqlalchemy.sql.sql...
siuba/sql/dialects/postgresql.py
from ..translate import ( win_agg, win_over, win_cumul, sql_scalar, sql_agg, RankOver, wrap_annotate, annotate, extend_base, SqlTranslator, ) from .base import ( SqlColumn, SqlColumnAgg, base_scalar, base_win, base_agg ) import sqlalchemy.sql.sql...
0.279238
0.202187
import asyncio from typing import Optional from main import os from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton from aiogram.utils import exceptions, executor from models import User import database from loguru import logger as log from celery import Celery celery_app = Celery('tasks', broker=os....
tasks.py
import asyncio from typing import Optional from main import os from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton from aiogram.utils import exceptions, executor from models import User import database from loguru import logger as log from celery import Celery celery_app = Celery('tasks', broker=os....
0.668015
0.112065
import copy import collections from werkzeug.exceptions import Forbidden from sqlalchemy import and_ from ggrc import db from ggrc import models from ggrc.utils import benchmark from ggrc.rbac import permissions from ggrc.query.default_handler import DefaultHandler def _set_data(object_query, data): """Helper fun...
src/ggrc/query/assessment_related_objects.py
import copy import collections from werkzeug.exceptions import Forbidden from sqlalchemy import and_ from ggrc import db from ggrc import models from ggrc.utils import benchmark from ggrc.rbac import permissions from ggrc.query.default_handler import DefaultHandler def _set_data(object_query, data): """Helper fun...
0.621656
0.335623
import networkx as nx import matplotlib.pyplot as plt from autoparse.automaton import preprocess, Automaton class Transition: def __init__( self, word: str, state_in, state_out, transition_ids=[], weight: int = 1, variables={}, ): self.word = wo...
autoparse/automaton_fitter.py
import networkx as nx import matplotlib.pyplot as plt from autoparse.automaton import preprocess, Automaton class Transition: def __init__( self, word: str, state_in, state_out, transition_ids=[], weight: int = 1, variables={}, ): self.word = wo...
0.792223
0.303719
import os import PIL.Image import numpy as np import tensorflow as tf import tensorflow_hub as hub from keras.applications import resnet50 from keras.applications.resnet50 import ResNet50 from keras.backend import set_session from scipy.stats import truncnorm # Initialize the module module_path = 'https://tfhub.dev/d...
utilities/gan-inversion/01_model_prep.py
import os import PIL.Image import numpy as np import tensorflow as tf import tensorflow_hub as hub from keras.applications import resnet50 from keras.applications.resnet50 import ResNet50 from keras.backend import set_session from scipy.stats import truncnorm # Initialize the module module_path = 'https://tfhub.dev/d...
0.758958
0.322286
from lib import script import random rand = random.randint def warp_uptown_east(pc): result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp") if result == 1: script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン elif result == 2: script.warp(pc, 10023400, rand(126, 129), ran...
script/site_packages/warp_event.py
from lib import script import random rand = random.randint def warp_uptown_east(pc): result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp") if result == 1: script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン elif result == 2: script.warp(pc, 10023400, rand(126, 129), ran...
0.157785
0.250913
from asyncio import DatagramTransport import json, yaml from paramiko import SSHException import requests from server.utils.response_util import RET from flask import jsonify, current_app, g from typing import List from flask import current_app, jsonify from sqlalchemy.exc import IntegrityError, SQLAlchemyError from ...
radiaTest-server/server/utils/permission_utils.py
from asyncio import DatagramTransport import json, yaml from paramiko import SSHException import requests from server.utils.response_util import RET from flask import jsonify, current_app, g from typing import List from flask import current_app, jsonify from sqlalchemy.exc import IntegrityError, SQLAlchemyError from ...
0.424531
0.098947
# Golden Search, mimics the secant method, but for finding the Global Max and min (optimization of a function) # Strategy in selecting the bounds of the interval: # l0 = distance between estimate, # l0 = l1+l2 ; l1/l0 = l2/l1 # R = (l2/l1)**-1 (reciprocal) # From substitution : 1 +R = 1/R -> R**2 +...
GoldSearch.py
# Golden Search, mimics the secant method, but for finding the Global Max and min (optimization of a function) # Strategy in selecting the bounds of the interval: # l0 = distance between estimate, # l0 = l1+l2 ; l1/l0 = l2/l1 # R = (l2/l1)**-1 (reciprocal) # From substitution : 1 +R = 1/R -> R**2 +...
0.384912
0.644505
import scrapy import sys from scrapy.selector import Selector import amazon_crawler.spider_logger as db_logger from amazon_crawler.items import AmazonItem as ReviewerItem import amazon_crawler.mysql_helper as db import amazon_crawler.html_extractor as html_extractor from amazon_crawler.spider_base import SpiderBase f...
amazon_crawler/amazon_crawler/spiders/reviewer.py
import scrapy import sys from scrapy.selector import Selector import amazon_crawler.spider_logger as db_logger from amazon_crawler.items import AmazonItem as ReviewerItem import amazon_crawler.mysql_helper as db import amazon_crawler.html_extractor as html_extractor from amazon_crawler.spider_base import SpiderBase f...
0.145267
0.050075
from string import * import re from zapps.rt import * class CommandParserScanner(Scanner): patterns = [ ('"/"', re.compile('/')), ('[ \t]+', re.compile('[ \t]+')), ('NUMBER', re.compile('[0-9]+')), ('STRING', re.compile('".*"')), ('FLOAT', re.compile('[0-9]+\\.[0-9]+')), ...
examples/command.py
from string import * import re from zapps.rt import * class CommandParserScanner(Scanner): patterns = [ ('"/"', re.compile('/')), ('[ \t]+', re.compile('[ \t]+')), ('NUMBER', re.compile('[0-9]+')), ('STRING', re.compile('".*"')), ('FLOAT', re.compile('[0-9]+\\.[0-9]+')), ...
0.257672
0.09556
import WelcomeNote import math import OLSDims import mdl import EnvSettings from osgeo import osr import Circ import os import ObsData class dataInput: ip = mdl.Data() f=ip.f AppOLS = OLSDims.AppDim.AppOLS ToOLS = OLSDims.TODim.ToOLS AppOLSNAME=OLSDims.AppDim.AppOLSNAME AppOLSDIMS=OLSDims.AppDim...
Point_Engine.py
import WelcomeNote import math import OLSDims import mdl import EnvSettings from osgeo import osr import Circ import os import ObsData class dataInput: ip = mdl.Data() f=ip.f AppOLS = OLSDims.AppDim.AppOLS ToOLS = OLSDims.TODim.ToOLS AppOLSNAME=OLSDims.AppDim.AppOLSNAME AppOLSDIMS=OLSDims.AppDim...
0.035763
0.166134
import os from dotenv import load_dotenv import praw import json load_dotenv(verbose=True) CLIENT_ID = os.environ.get("CLIENT_ID") CLIENT_SECRET = os.environ.get("CLIENT_SECRET") USER_AGENT = os.environ.get("USER_AGENT") USERNAME = os.environ.get("USERNAME") PASSWORD = os.environ.get("PASSWORD") def get_json(): ...
reddit_comments.py
import os from dotenv import load_dotenv import praw import json load_dotenv(verbose=True) CLIENT_ID = os.environ.get("CLIENT_ID") CLIENT_SECRET = os.environ.get("CLIENT_SECRET") USER_AGENT = os.environ.get("USER_AGENT") USERNAME = os.environ.get("USERNAME") PASSWORD = os.environ.get("PASSWORD") def get_json(): ...
0.405096
0.079424
import json import logging import time from datetime import datetime from tempfile import SpooledTemporaryFile from typing import List, Union, Dict, Any, Optional import pandas import requests from fastapi.encoders import jsonable_encoder from pytz import timezone from sentry_sdk import capture_exception from sqlalche...
backend/app/app/crud/crud_fact.py
import json import logging import time from datetime import datetime from tempfile import SpooledTemporaryFile from typing import List, Union, Dict, Any, Optional import pandas import requests from fastapi.encoders import jsonable_encoder from pytz import timezone from sentry_sdk import capture_exception from sqlalche...
0.720368
0.075244
# In[ ]: import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage.filters import gaussian import scipy import cv2 from scipy import ndimage import Image_preperation as prep import FitFunction as fit import FileManager as fm import Image_preperation as prep def calc_mean...
ActiveFitContour.py
# In[ ]: import numpy as np import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage.filters import gaussian import scipy import cv2 from scipy import ndimage import Image_preperation as prep import FitFunction as fit import FileManager as fm import Image_preperation as prep def calc_mean...
0.462716
0.567277
import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt import os import matplotlib.cm as cm from collections import defaultdict import matplotlib font = {'family' : 'sans-serif', 'variant' : 'normal', 'weight' : 'light', 'size' : 14} matplotlib.rc('font', **font) def read_in_edges_...
src_general/SR_pdf.py
import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt import os import matplotlib.cm as cm from collections import defaultdict import matplotlib font = {'family' : 'sans-serif', 'variant' : 'normal', 'weight' : 'light', 'size' : 14} matplotlib.rc('font', **font) def read_in_edges_...
0.477067
0.716057
import struct import sys import os disk_data = [ 0x4A, 0x57, 0x5E, 0x75, 0x38, 0x66, 0x3B, 0x79, 0x3A, 0x60, 0x75, 0x61, 0x26, 0x38, 0x68, 0x5E, 0x28, 0x68, 0x6C, 0x6C, 0x72, 0x76, 0x71, 0x7E, 0x55, 0x47, 0x38, 0x42, 0x7A, 0x4A, 0x6B, 0x4D, 0x4D, 0x65, 0x37, 0x79, 0x45, 0x62, 0x2E, 0x70, 0x4C, 0x63, 0x38...
Gathered CTF writeups/codegate_quals_2020/malicious/malicious_mbr_crack.py
import struct import sys import os disk_data = [ 0x4A, 0x57, 0x5E, 0x75, 0x38, 0x66, 0x3B, 0x79, 0x3A, 0x60, 0x75, 0x61, 0x26, 0x38, 0x68, 0x5E, 0x28, 0x68, 0x6C, 0x6C, 0x72, 0x76, 0x71, 0x7E, 0x55, 0x47, 0x38, 0x42, 0x7A, 0x4A, 0x6B, 0x4D, 0x4D, 0x65, 0x37, 0x79, 0x45, 0x62, 0x2E, 0x70, 0x4C, 0x63, 0x38...
0.034464
0.650009
# COMMAND ---------- # MAGIC %md # MAGIC # MAGIC # Density Estimation via Voronoi Diagrams in High Dimensions # COMMAND ---------- # MAGIC %md # MAGIC # MAGIC <NAME> and <NAME> # MAGIC # MAGIC [Video of project presentation](https://drive.google.com/file/d/14E_igECN6hDZieWNn9VVTepCo5mu-rzy/view?usp=sharing) # ...
dbcArchives/2021/000_0-sds-3-x-projects/student-project-17_group-TowardsScalableTDA/00_introduction.py
# COMMAND ---------- # MAGIC %md # MAGIC # MAGIC # Density Estimation via Voronoi Diagrams in High Dimensions # COMMAND ---------- # MAGIC %md # MAGIC # MAGIC <NAME> and <NAME> # MAGIC # MAGIC [Video of project presentation](https://drive.google.com/file/d/14E_igECN6hDZieWNn9VVTepCo5mu-rzy/view?usp=sharing) # ...
0.878562
0.842734
from django.shortcuts import render, HttpResponse, redirect, \ get_object_or_404, reverse from django.contrib.auth.decorators import login_required from django.contrib import messages from django.conf import settings from decimal import Decimal from paypal.standard.forms import PayPalPaymentsForm from django.views....
ecommerce_app/views.py
from django.shortcuts import render, HttpResponse, redirect, \ get_object_or_404, reverse from django.contrib.auth.decorators import login_required from django.contrib import messages from django.conf import settings from decimal import Decimal from paypal.standard.forms import PayPalPaymentsForm from django.views....
0.508788
0.081739
import click def parse_variable_filter(argument): variable, _, values = argument[1:].partition('=') if variable == 'py': variable = 'python' parsed_values = set(values.split(',')) if values else set() return variable, parsed_values def select_matrix_environments(environments, included_varia...
src/hatch/cli/run/__init__.py
import click def parse_variable_filter(argument): variable, _, values = argument[1:].partition('=') if variable == 'py': variable = 'python' parsed_values = set(values.split(',')) if values else set() return variable, parsed_values def select_matrix_environments(environments, included_varia...
0.649023
0.735167
import numpy as np from tqdm import trange from chapter04.car_rental_mine import cartesian_prod np.random.seed(5) class WindyWorld(object): def __init__(self, hight, width, start, end, wind_force): self.hight = hight self.width = width self.start = start self.end = end s...
chapter06/windy_grid_world_mine.py
import numpy as np from tqdm import trange from chapter04.car_rental_mine import cartesian_prod np.random.seed(5) class WindyWorld(object): def __init__(self, hight, width, start, end, wind_force): self.hight = hight self.width = width self.start = start self.end = end s...
0.609989
0.441914
import matplotlib.pyplot as plt from PIL import Image import numpy as np import nibabel as nib import os import cv2 import math def water(img_path): src = cv2.imread(img_path) img = src.copy() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold( gray, 0, 255, cv2.THRESH_BI...
util/mask2label.py
import matplotlib.pyplot as plt from PIL import Image import numpy as np import nibabel as nib import os import cv2 import math def water(img_path): src = cv2.imread(img_path) img = src.copy() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold( gray, 0, 255, cv2.THRESH_BI...
0.193566
0.329931
import math,random import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sn from sklearn.metrics import confusion_matrix import torch import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset import torchaudio from torchaudio import transforms class AudioData(D...
utils.py
import math,random import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sn from sklearn.metrics import confusion_matrix import torch import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset import torchaudio from torchaudio import transforms class AudioData(D...
0.719778
0.438184
import requests import argparse import pathlib import json class PublishingFailedException(Exception): pass class PactBrokerInterface: """ Interface to a pact-broker instance Allows publishing pact test JSON files to pact-broker instance Attributes ---------- url : str pact-broker ...
pact_test_utils/publish_pacts.py
import requests import argparse import pathlib import json class PublishingFailedException(Exception): pass class PactBrokerInterface: """ Interface to a pact-broker instance Allows publishing pact test JSON files to pact-broker instance Attributes ---------- url : str pact-broker ...
0.698946
0.147709
import re class Account(): """Client account""" ID_COUNT = 1 def __init__(self, name, **kwargs): self.id = self.ID_COUNT self.name = name self.__dict__.update(kwargs) Account.ID_COUNT += 1 def __getitem__(self, key): return getattr(self, key) def __str__(...
Module_01/ex05/the_bank.py
import re class Account(): """Client account""" ID_COUNT = 1 def __init__(self, name, **kwargs): self.id = self.ID_COUNT self.name = name self.__dict__.update(kwargs) Account.ID_COUNT += 1 def __getitem__(self, key): return getattr(self, key) def __str__(...
0.539105
0.172694
from numpy.core.defchararray import zfill import taichi as ti import numpy as np from .camera import * from .shading import * from .renderer_utils import ray_aabb_intersection, intersect_sphere, ray_plane_intersect, reflect, refract inf = 1e8 eps = 1e-4 @ti.data_oriented class ParticleRenderer: padding = 3 # ext...
engine/fast_renderer/renderer.py
from numpy.core.defchararray import zfill import taichi as ti import numpy as np from .camera import * from .shading import * from .renderer_utils import ray_aabb_intersection, intersect_sphere, ray_plane_intersect, reflect, refract inf = 1e8 eps = 1e-4 @ti.data_oriented class ParticleRenderer: padding = 3 # ext...
0.708213
0.514278
from __future__ import print_function import argparse import os import csv import sys from scipy.stats import pearsonr import numpy import pandas def mse(y_true, y_pred): from sklearn.metrics import mean_squared_error return mean_squared_error(y_true,y_pred) def f1(y_true, y_pred): from sklearn.metrics...
calculateEvaluationCCC.py
from __future__ import print_function import argparse import os import csv import sys from scipy.stats import pearsonr import numpy import pandas def mse(y_true, y_pred): from sklearn.metrics import mean_squared_error return mean_squared_error(y_true,y_pred) def f1(y_true, y_pred): from sklearn.metrics...
0.337859
0.230573
import sys import re import json import uuid import datetime import time import glob import codecs __author__ = "<NAME>, <NAME>" __copyright__ = "Copyright 2014" __license__ = "GPL" __version__ = "3.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" # ghost settings post_id = 1 author_id =...
octopress2ghost.py
import sys import re import json import uuid import datetime import time import glob import codecs __author__ = "<NAME>, <NAME>" __copyright__ = "Copyright 2014" __license__ = "GPL" __version__ = "3.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" # ghost settings post_id = 1 author_id =...
0.223377
0.161353
import mock import pytest from boto3.exceptions import Boto3Error from ruamel.yaml import YAML from paasta_tools.cli.cmds.spark_run import configure_and_run_docker_container from paasta_tools.cli.cmds.spark_run import create_spark_config_str from paasta_tools.cli.cmds.spark_run import DEFAULT_SERVICE from paasta_tools...
tests/cli/test_cmds_spark_run.py
import mock import pytest from boto3.exceptions import Boto3Error from ruamel.yaml import YAML from paasta_tools.cli.cmds.spark_run import configure_and_run_docker_container from paasta_tools.cli.cmds.spark_run import create_spark_config_str from paasta_tools.cli.cmds.spark_run import DEFAULT_SERVICE from paasta_tools...
0.453262
0.137243
import logging import os def env_bool(name: str) -> bool: raw_value = os.getenv(name, "") return raw_value.lower() == "true" def env_list(name: str) -> list[str]: raw_value = os.getenv(name, "") if not raw_value: return [] return raw_value.split(",") SILENCED_SYSTEM_CHECKS = [] # ...
chmvh_website/chmvh_website/settings.py
import logging import os def env_bool(name: str) -> bool: raw_value = os.getenv(name, "") return raw_value.lower() == "true" def env_list(name: str) -> list[str]: raw_value = os.getenv(name, "") if not raw_value: return [] return raw_value.split(",") SILENCED_SYSTEM_CHECKS = [] # ...
0.405684
0.131145
from tensorflow.keras.models import Sequential from tensorflow.keras import backend as K from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import RandomRotation from tensorflow.keras.layers import MaxPooling2D from tensorflow.keras.layers impo...
CNN.py
from tensorflow.keras.models import Sequential from tensorflow.keras import backend as K from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import RandomRotation from tensorflow.keras.layers import MaxPooling2D from tensorflow.keras.layers impo...
0.564098
0.511595
import MySQLdb as mysql import os import jieba from wordcloud import WordCloud, ImageColorGenerator from concurrent.futures import ThreadPoolExecutor as tpe from matplotlib import pyplot as plt from util import PROJECT_ABS_PATH from scipy.misc import imread import time custom_dictionary = ["韩国人", "中国人", "第三世界", "死宅",...
analyse/count.py
import MySQLdb as mysql import os import jieba from wordcloud import WordCloud, ImageColorGenerator from concurrent.futures import ThreadPoolExecutor as tpe from matplotlib import pyplot as plt from util import PROJECT_ABS_PATH from scipy.misc import imread import time custom_dictionary = ["韩国人", "中国人", "第三世界", "死宅",...
0.123405
0.15633
import argparse from itertools import combinations import os import sys import matplotlib matplotlib.use("PDF") import matplotlib.pyplot as plt import mdtraj as md import numpy as np from sklearn.decomposition import FastICA from sklearn.decomposition import PCA from sklearn.decomposition import TruncatedSVD from skle...
crewman_daniels/component_analysis.py
import argparse from itertools import combinations import os import sys import matplotlib matplotlib.use("PDF") import matplotlib.pyplot as plt import mdtraj as md import numpy as np from sklearn.decomposition import FastICA from sklearn.decomposition import PCA from sklearn.decomposition import TruncatedSVD from skle...
0.424173
0.293797
from collections import defaultdict from decimal import Decimal from django.db import models, transaction from django.db.models import Count from django.db.models.fields.reverse_related import ForeignObjectRel from article.models import ArticleType, OrProductType from blame.models import ImmutableBlame, Blame from cr...
backend/logistics/models.py
from collections import defaultdict from decimal import Decimal from django.db import models, transaction from django.db.models import Count from django.db.models.fields.reverse_related import ForeignObjectRel from article.models import ArticleType, OrProductType from blame.models import ImmutableBlame, Blame from cr...
0.821975
0.444444
import numpy as np class ObjectStatic: """ Static data for an object. This data won't change between frames. """ def __init__(self, name: str, object_id: int, mass: float, segmentation_color: np.array, size: np.array, category: str, kinematic: bool, dynamic_friction: float, static_fr...
Python/tdw/object_data/object_static.py
import numpy as np class ObjectStatic: """ Static data for an object. This data won't change between frames. """ def __init__(self, name: str, object_id: int, mass: float, segmentation_color: np.array, size: np.array, category: str, kinematic: bool, dynamic_friction: float, static_fr...
0.933035
0.736472
from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Almacen', fields=[ ('idalmace...
full_inventory/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Almacen', fields=[ ('idalmace...
0.526099
0.139484
import chainer from chainer import Variable import chainer.functions as F import numpy as np import copy from losses import loss_fun from transport_costs import cost_fun from attacks import wrm_attack def get_batch(iterator, xp): batch = iterator.next() batchsize = len(batch) x = [] y = [] for j i...
extentions.py
import chainer from chainer import Variable import chainer.functions as F import numpy as np import copy from losses import loss_fun from transport_costs import cost_fun from attacks import wrm_attack def get_batch(iterator, xp): batch = iterator.next() batchsize = len(batch) x = [] y = [] for j i...
0.4856
0.228415
import os import buildbot import buildbot.process.factory from buildbot.steps.source import SVN from buildbot.steps.shell import ShellCommand, SetProperty from buildbot.steps.slave import RemoveDirectory from buildbot.process.properties import WithProperties, Property from zorg.buildbot.builders.Util import getVisualS...
zorg/buildbot/builders/LLDBuilder.py
import os import buildbot import buildbot.process.factory from buildbot.steps.source import SVN from buildbot.steps.shell import ShellCommand, SetProperty from buildbot.steps.slave import RemoveDirectory from buildbot.process.properties import WithProperties, Property from zorg.buildbot.builders.Util import getVisualS...
0.356671
0.092565
# Make coding more python3-ish from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from ansible_collections.community.internal_test_tools.tests.unit.compat.mock import patch from ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils impo...
venv/lib/python3.8/site-packages/ansible_collections/community/dns/tests/unit/plugins/modules/test_wait_for_txt.py
# Make coding more python3-ish from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from ansible_collections.community.internal_test_tools.tests.unit.compat.mock import patch from ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils impo...
0.630002
0.22482
import codecs import re from codecs import StreamReaderWriter from typing import Optional from logging2.handlers.abc import Handler from logging2.levels import LogLevel # NOTE: This module does not provide handlers for rotating log files. The rationale behind that is that all *NIX systems # have software specificall...
logging2/handlers/files.py
import codecs import re from codecs import StreamReaderWriter from typing import Optional from logging2.handlers.abc import Handler from logging2.levels import LogLevel # NOTE: This module does not provide handlers for rotating log files. The rationale behind that is that all *NIX systems # have software specificall...
0.800224
0.234341
import logging from abc import ABC, abstractmethod import numpy as np import pandas as pd from hdrbp._util import ( basic_repr, basic_str, compute_correlation, compute_diversification_ratio, compute_drawdowns, compute_gini, compute_prices, compute_risk_contributions, compute_turnov...
hdrbp/metric.py
import logging from abc import ABC, abstractmethod import numpy as np import pandas as pd from hdrbp._util import ( basic_repr, basic_str, compute_correlation, compute_diversification_ratio, compute_drawdowns, compute_gini, compute_prices, compute_risk_contributions, compute_turnov...
0.895543
0.449876
from datetime import datetime from typing import Any, Dict from core.forms import GameForm from core.test.tests_helpers import create_game, create_platform from django.core.exceptions import ValidationError from django.test import TestCase class GameFormTests(TestCase): def setUp(self) -> None: self.plat...
finishedgames/core/test/test_game_form.py
from datetime import datetime from typing import Any, Dict from core.forms import GameForm from core.test.tests_helpers import create_game, create_platform from django.core.exceptions import ValidationError from django.test import TestCase class GameFormTests(TestCase): def setUp(self) -> None: self.plat...
0.651244
0.454048
import os import random import en_core_web_sm import stringx import tensorflow as tf import tensorflow.logging as log from tensorflow.python.lib.io import file_io nlp = en_core_web_sm.load() # acceptable ways to end a sentence END_TOKENS = ['.', '!', '?', '...', "'", "`", '"', ")"] STOPLIST = frozenset(['@highlight'...
trainer/etl.py
import os import random import en_core_web_sm import stringx import tensorflow as tf import tensorflow.logging as log from tensorflow.python.lib.io import file_io nlp = en_core_web_sm.load() # acceptable ways to end a sentence END_TOKENS = ['.', '!', '?', '...', "'", "`", '"', ")"] STOPLIST = frozenset(['@highlight'...
0.529263
0.280145
from ctypes import * from os import EX_CANTCREAT import threading import queue import time import copy COM_OK = 0 COM_ERROR = 1 COM_ABORT = 2 COM_TIMEOUT = 3 MASTER_BROADCAST=0x07FF MASTER_P2P_MASK =0x0400 RX_FILTER_MASK_ALL=0xFFFFFFFF RX_FILTER_MASK_ONE=0x00000000 RX_VERBOS...
Host/usbCAN/usbCAN.py
from ctypes import * from os import EX_CANTCREAT import threading import queue import time import copy COM_OK = 0 COM_ERROR = 1 COM_ABORT = 2 COM_TIMEOUT = 3 MASTER_BROADCAST=0x07FF MASTER_P2P_MASK =0x0400 RX_FILTER_MASK_ALL=0xFFFFFFFF RX_FILTER_MASK_ONE=0x00000000 RX_VERBOS...
0.13102
0.100923
from flask_restful import Resource import libs.http_status as status import libs.json_response as response from libs.validator import Validator, require_json from managers.todo_manager import TodoManager from pprint import pprint manager = TodoManager() class TodosResource(Resource): def get(self): data ...
routes/todos.py
from flask_restful import Resource import libs.http_status as status import libs.json_response as response from libs.validator import Validator, require_json from managers.todo_manager import TodoManager from pprint import pprint manager = TodoManager() class TodosResource(Resource): def get(self): data ...
0.253122
0.071494
from OpenPNM.Geometry import models as gm from OpenPNM.Geometry import GenericGeometry class Stick_and_Ball(GenericGeometry): r""" Stick and Ball subclass of GenericGeometry. This subclass is meant as a basic default geometry to get started quickly. Parameters ---------- name : string ...
OpenPNM/Geometry/__Stick_and_Ball__.py
from OpenPNM.Geometry import models as gm from OpenPNM.Geometry import GenericGeometry class Stick_and_Ball(GenericGeometry): r""" Stick and Ball subclass of GenericGeometry. This subclass is meant as a basic default geometry to get started quickly. Parameters ---------- name : string ...
0.870501
0.230194
from .schfile import SchFile ''' Given a top schematic file name, SchDict will read all the schematics and put them in a dictionary. If they are instantiated multiple times, they will only be read/parsed once, but each instantiation will have its own dictionary entry with its own timestamp and parent. ''' class Sheet...
kipy/fileobjs/sch/schdict.py
from .schfile import SchFile ''' Given a top schematic file name, SchDict will read all the schematics and put them in a dictionary. If they are instantiated multiple times, they will only be read/parsed once, but each instantiation will have its own dictionary entry with its own timestamp and parent. ''' class Sheet...
0.459076
0.258674