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 numpy as np from hypothesis import given from hypothesis import strategies as st from hypothesis.extra.numpy import arrays, array_shapes from hypothesis.extra.pandas import data_frames, column, series, range_indexes from timeseers.utils import MinMaxScaler @given( arrays( np.float, shape=a...
tests/test_utils.py
import numpy as np from hypothesis import given from hypothesis import strategies as st from hypothesis.extra.numpy import arrays, array_shapes from hypothesis.extra.pandas import data_frames, column, series, range_indexes from timeseers.utils import MinMaxScaler @given( arrays( np.float, shape=a...
0.722429
0.689951
import torch from mmcv.runner import force_fp32 from torch import nn as nn from typing import List from .furthest_point_sample import (furthest_point_sample, furthest_point_sample_with_dist) from .utils import calc_square_dist def get_sampler_type(sampler_type): """Get the typ...
mmdet3d/ops/furthest_point_sample/points_sampler.py
import torch from mmcv.runner import force_fp32 from torch import nn as nn from typing import List from .furthest_point_sample import (furthest_point_sample, furthest_point_sample_with_dist) from .utils import calc_square_dist def get_sampler_type(sampler_type): """Get the typ...
0.940044
0.588594
from django.urls import path from . import views urlpatterns = [ # Global Dimension path("dimension/", views.DimensionView.as_view(), name="dimension"), # path("metrics/", views.MetricsView.as_view(), name="metrics"), path( "global-dimension/", views.GlobalDimensionView.as_view(), name="globalD...
api/cueSearch/urls.py
from django.urls import path from . import views urlpatterns = [ # Global Dimension path("dimension/", views.DimensionView.as_view(), name="dimension"), # path("metrics/", views.MetricsView.as_view(), name="metrics"), path( "global-dimension/", views.GlobalDimensionView.as_view(), name="globalD...
0.467089
0.088741
from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing import os import random import subprocess import sys import time def random_name(): return str(random.randint(0, 99999999)) def start_local_scheduler(plasma_store_name, ...
python/ray/local_scheduler/local_scheduler_services.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing import os import random import subprocess import sys import time def random_name(): return str(random.randint(0, 99999999)) def start_local_scheduler(plasma_store_name, ...
0.502441
0.129046
import pickle import openpyxl from local_settings_eclipse import db def fetch_file(path): with open(path, 'rb') as fp: file = pickle.load(fp) return file RELATIVE_PATH = "/home/imlegend19/PycharmProjects/Research - Data Mining/eclipse/" wb = openpyxl.Workbook() sheet = wb.active titles = ["Assign...
eclipse/correlation/script.py
import pickle import openpyxl from local_settings_eclipse import db def fetch_file(path): with open(path, 'rb') as fp: file = pickle.load(fp) return file RELATIVE_PATH = "/home/imlegend19/PycharmProjects/Research - Data Mining/eclipse/" wb = openpyxl.Workbook() sheet = wb.active titles = ["Assign...
0.178454
0.172625
"""Unit test for proxy.py""" import abc import asyncio import time from typing import List import unittest import proxy class MockRng(abc.ABC): def __init__(self, results: List[float]): self._results = results def uniform(self, from_val: float, to_val: float) -> float: val_range = to_val - ...
pw_transfer/integration_test/proxy_test.py
"""Unit test for proxy.py""" import abc import asyncio import time from typing import List import unittest import proxy class MockRng(abc.ABC): def __init__(self, results: List[float]): self._results = results def uniform(self, from_val: float, to_val: float) -> float: val_range = to_val - ...
0.844601
0.589894
import copy from google.cloud import datacatalog from google.datacatalog_connectors.commons import prepare from google.datacatalog_connectors.apache_atlas.prepare import constant from google.datacatalog_connectors.apache_atlas.prepare import \ datacatalog_attribute_normalizer as attr_normalizer class DataCatal...
google-datacatalog-apache-atlas-connector/src/google/datacatalog_connectors/apache_atlas/prepare/datacatalog_tag_factory.py
import copy from google.cloud import datacatalog from google.datacatalog_connectors.commons import prepare from google.datacatalog_connectors.apache_atlas.prepare import constant from google.datacatalog_connectors.apache_atlas.prepare import \ datacatalog_attribute_normalizer as attr_normalizer class DataCatal...
0.557604
0.11004
import discord # Make sure we're using the correct version of Discord.py if discord.__author__ != "Rapptz": print("Error: Please use the rewrite version of Discord.py.") print("Check the README for instructions.") exit() import requests, asyncio, platform from discord.ext.commands import Bot # End imports...
main.py
import discord # Make sure we're using the correct version of Discord.py if discord.__author__ != "Rapptz": print("Error: Please use the rewrite version of Discord.py.") print("Check the README for instructions.") exit() import requests, asyncio, platform from discord.ext.commands import Bot # End imports...
0.282295
0.18508
import torch import torch.nn as nn import segmentation_models_pytorch as smp class Generator_with_Refin(nn.Module): def __init__(self, encoder): """Generator initialization Args: encoder: an encoder for Unet generator """ super(Generator_with_Refin, self).__init__() ...
shadow_class/networks.py
import torch import torch.nn as nn import segmentation_models_pytorch as smp class Generator_with_Refin(nn.Module): def __init__(self, encoder): """Generator initialization Args: encoder: an encoder for Unet generator """ super(Generator_with_Refin, self).__init__() ...
0.958644
0.413773
import json from pathlib import Path from typing import Any, Mapping, Optional, Union, cast, get_args import pulumi_nomad as nomad from infra.config import STACK_NAME from infra.nomad_service_postgres import NomadServicePostgresDbArgs import pulumi _ValidNomadVarTypePrimitives = Union[str, bool, int] _ValidNomadVarT...
pulumi/infra/nomad_job.py
import json from pathlib import Path from typing import Any, Mapping, Optional, Union, cast, get_args import pulumi_nomad as nomad from infra.config import STACK_NAME from infra.nomad_service_postgres import NomadServicePostgresDbArgs import pulumi _ValidNomadVarTypePrimitives = Union[str, bool, int] _ValidNomadVarT...
0.763572
0.064742
from __future__ import absolute_import, unicode_literals try: import json except ImportError: import simplejson as json import textwrap from django.core import serializers from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from markupmirror.fields import Markup from mar...
tests/tests/fields.py
from __future__ import absolute_import, unicode_literals try: import json except ImportError: import simplejson as json import textwrap from django.core import serializers from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from markupmirror.fields import Markup from mar...
0.763572
0.210462
import time import unittest import hiro from holmium.core import Page, Element, Locators, ElementMap from holmium.core.conditions import ( ALL, MATCHES_TEXT, VISIBLE, INVISIBLE, ANY ) from tests.utils import make_temp_page, get_driver class WaitConditionTests(unittest.TestCase): def setUp(self): sel...
tests/wait_condition_tests.py
import time import unittest import hiro from holmium.core import Page, Element, Locators, ElementMap from holmium.core.conditions import ( ALL, MATCHES_TEXT, VISIBLE, INVISIBLE, ANY ) from tests.utils import make_temp_page, get_driver class WaitConditionTests(unittest.TestCase): def setUp(self): sel...
0.360151
0.16228
from django.conf import settings from django.urls import reverse # Projectroles dependency from projectroles.models import SODAR_CONSTANTS from projectroles.plugins import ProjectAppPluginPoint from .models import File, Folder, HyperLink from .urls import urlpatterns # SODAR Constants APP_SETTING_SCOPE_PROJECT = SO...
filesfolders/plugins.py
from django.conf import settings from django.urls import reverse # Projectroles dependency from projectroles.models import SODAR_CONSTANTS from projectroles.plugins import ProjectAppPluginPoint from .models import File, Folder, HyperLink from .urls import urlpatterns # SODAR Constants APP_SETTING_SCOPE_PROJECT = SO...
0.657868
0.126569
try: from collections import Sequence except ImportError: from collections.abc import Sequence from io import BytesIO import zipfile class DocumentCollection(Sequence): def __init__( self, sumo_client, query, mapper_function=None ): self.sumo = sumo_client ...
src/fmu/sumo/explorer/_document_collection.py
try: from collections import Sequence except ImportError: from collections.abc import Sequence from io import BytesIO import zipfile class DocumentCollection(Sequence): def __init__( self, sumo_client, query, mapper_function=None ): self.sumo = sumo_client ...
0.554229
0.149687
map_template = ( ( (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0...
games/world_gen_output.py
map_template = ( ( (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0...
0.069977
0.140248
import logging _global_dict = {} def init_glb(): """ initialize global variables """ global _global_dict _global_dict = { "configManage": None, "projectScript": None, "userData": {}, "deviceInstance": None, "pocoInstance": None, "rerunFailInfo": Non...
flybirds/core/global_resource.py
import logging _global_dict = {} def init_glb(): """ initialize global variables """ global _global_dict _global_dict = { "configManage": None, "projectScript": None, "userData": {}, "deviceInstance": None, "pocoInstance": None, "rerunFailInfo": Non...
0.419291
0.06951
from __future__ import absolute_import, unicode_literals from django.core import mail from django.core.urlresolvers import reverse from django.contrib.auth.tests.utils import skipIfCustomUser from django.test import TestCase, Client from django.utils.translation import ugettext as _ from feincms.content.application.mod...
tests/postfinance/test_api.py
from __future__ import absolute_import, unicode_literals from django.core import mail from django.core.urlresolvers import reverse from django.contrib.auth.tests.utils import skipIfCustomUser from django.test import TestCase, Client from django.utils.translation import ugettext as _ from feincms.content.application.mod...
0.292494
0.158923
import pygame import random import math from pygame import mixer #Initializing pygame pygame.init() #initializing the screen screen = pygame.display.set_mode((800,600)) #Titile & Icon pygame.display.set_caption("Space Invaders") icon = pygame.image.load("alien.png") pygame.display.set_icon(icon) #score score_va...
games/SpaceInvaders/Pygame_original.py
import pygame import random import math from pygame import mixer #Initializing pygame pygame.init() #initializing the screen screen = pygame.display.set_mode((800,600)) #Titile & Icon pygame.display.set_caption("Space Invaders") icon = pygame.image.load("alien.png") pygame.display.set_icon(icon) #score score_va...
0.090624
0.242643
import os import platform import sys import traceback import discord from kithscord import common, util class ArgError(Exception): pass class UserCommand: """ Base class to handle user commands. """ def __init__(self): """ Initialise UserCommand class """ # Cre...
kithscord/user_commands.py
import os import platform import sys import traceback import discord from kithscord import common, util class ArgError(Exception): pass class UserCommand: """ Base class to handle user commands. """ def __init__(self): """ Initialise UserCommand class """ # Cre...
0.309232
0.101456
import re import numpy as np from .. import util def load_off(file_obj, **kwargs): """ Load an OFF file into the kwargs for a Trimesh constructor Parameters ---------- file_obj : file object Contains an OFF file Returns ---------- loaded : dict kwargs for Trimesh constr...
trimesh/exchange/off.py
import re import numpy as np from .. import util def load_off(file_obj, **kwargs): """ Load an OFF file into the kwargs for a Trimesh constructor Parameters ---------- file_obj : file object Contains an OFF file Returns ---------- loaded : dict kwargs for Trimesh constr...
0.67694
0.380011
import oculus import vizcam import vizfx import viz import vizconnect import vizact import vizproximity import vizinfo viz.phys.enable() viz.go() boxInfo = vizinfo.InfoPanel('Box Material Characteristics', align=viz.ALIGN_LEFT_TOP) boxInfo.addSeparator() boxScale = boxInfo.addLabelItem('Scale',viz.addS...
Vizardcit.py
import oculus import vizcam import vizfx import viz import vizconnect import vizact import vizproximity import vizinfo viz.phys.enable() viz.go() boxInfo = vizinfo.InfoPanel('Box Material Characteristics', align=viz.ALIGN_LEFT_TOP) boxInfo.addSeparator() boxScale = boxInfo.addLabelItem('Scale',viz.addS...
0.340924
0.068475
import pytest from sqlalchemy.orm import Session from ...scrapers.course import Course from ...scrapers.course_class import CourseClass from .. import crud, models from ..sql import SessionLocal, engine class University: def __init__(self, name): self.name = name university = University("test1") term_...
coursecake/database/tests/test_crud.py
import pytest from sqlalchemy.orm import Session from ...scrapers.course import Course from ...scrapers.course_class import CourseClass from .. import crud, models from ..sql import SessionLocal, engine class University: def __init__(self, name): self.name = name university = University("test1") term_...
0.240061
0.49646
from __future__ import absolute_import, division, print_function, unicode_literals import pytest from tests import debug from tests.patterns import some from tests.timeline import Event @pytest.mark.parametrize("module", ["module", ""]) @pytest.mark.parametrize("line", ["line", ""]) def test_stack_format(pyfile, t...
tests/ptvsd/server/test_vs_specific.py
from __future__ import absolute_import, division, print_function, unicode_literals import pytest from tests import debug from tests.patterns import some from tests.timeline import Event @pytest.mark.parametrize("module", ["module", ""]) @pytest.mark.parametrize("line", ["line", ""]) def test_stack_format(pyfile, t...
0.457379
0.299272
from PyQt5 import QtWidgets, QtCore __all__ = ['TabWidget', 'CustomQDialog', 'CustomQMainWidget'] class TabWidget(QtWidgets.QTabWidget): """ Table widget to populate all the samples. """ def __init__(self, n_array, parent=None): super(TabWidget, self).__init__(parent) tab_list = [] ...
smlgui/widgets.py
from PyQt5 import QtWidgets, QtCore __all__ = ['TabWidget', 'CustomQDialog', 'CustomQMainWidget'] class TabWidget(QtWidgets.QTabWidget): """ Table widget to populate all the samples. """ def __init__(self, n_array, parent=None): super(TabWidget, self).__init__(parent) tab_list = [] ...
0.636127
0.110279
import sys from pyspark import SparkConf, SparkContext import re import numpy as np import scipy.sparse as sps from pyspark.mllib.linalg import Vectors from pyspark.mllib.linalg import SparseVector from pyspark.mllib.regression import LabeledPoint # Load and parse the data def parsePoint(line): data = line.split("...
part4-SimRank PageRank/wez311_task4.py
import sys from pyspark import SparkConf, SparkContext import re import numpy as np import scipy.sparse as sps from pyspark.mllib.linalg import Vectors from pyspark.mllib.linalg import SparseVector from pyspark.mllib.regression import LabeledPoint # Load and parse the data def parsePoint(line): data = line.split("...
0.339718
0.572424
from ... import main from json import loads as json from json import JSONDecodeError from datetime import datetime from ...settings import Settings as s import unittest class Test(unittest.TestCase): def setUp(self): self.eazy = main.EazySDK().get def test_searching_more_than_one_parameter_narrows_se...
tests/customer/get_customer.py
from ... import main from json import loads as json from json import JSONDecodeError from datetime import datetime from ...settings import Settings as s import unittest class Test(unittest.TestCase): def setUp(self): self.eazy = main.EazySDK().get def test_searching_more_than_one_parameter_narrows_se...
0.435902
0.335814
import struct # @todo: use these PACKET_LENGTH = 12 DATA_OFFSET = 8 class CommandPacket(object): def __init__(self, rnw=True, address=0, vals=None): """ """ assert isinstance(vals, (type(None), list)) self.rawbytes = bytearray([0 for _ in range(PACKET_LENGTH)]) self.rawbytes[0] =...
rhea/utils/command_packet.py
import struct # @todo: use these PACKET_LENGTH = 12 DATA_OFFSET = 8 class CommandPacket(object): def __init__(self, rnw=True, address=0, vals=None): """ """ assert isinstance(vals, (type(None), list)) self.rawbytes = bytearray([0 for _ in range(PACKET_LENGTH)]) self.rawbytes[0] =...
0.40028
0.394755
from django.shortcuts import redirect, render, get_object_or_404 from signup.models import MyUser from .models import Profile from .forms import ProfileForm from django.contrib.auth import get_user_model from post.models import Post # Create your views here. def writeprofile(request): id =request.user.id user...
user/views.py
from django.shortcuts import redirect, render, get_object_or_404 from signup.models import MyUser from .models import Profile from .forms import ProfileForm from django.contrib.auth import get_user_model from post.models import Post # Create your views here. def writeprofile(request): id =request.user.id user...
0.310276
0.063135
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits # Class that will be saved locally ============== class Dust(): def __init__(self, path = ''): self.path = path + 'data_dust/' self.angles = [inp for inp in np.arange(0,181)] def read_lambda(self): """ ...
library/mcfost_dust.py
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits # Class that will be saved locally ============== class Dust(): def __init__(self, path = ''): self.path = path + 'data_dust/' self.angles = [inp for inp in np.arange(0,181)] def read_lambda(self): """ ...
0.556641
0.431824
import logging import traceback from modules.helpers import get_initial_alarm_result, get_query info = { 'version': 0.1, 'name': 'User-agent module', 'alarmmsg': 'VISIT FROM BLACKLISTED USERAGENT TO C2_*', 'description': 'This check queries for UA\'s that are listed in any blacklist_useragents.conf an...
elkserver/docker/redelk-base/redelkinstalldata/scripts/modules/alarm_useragent/module.py
import logging import traceback from modules.helpers import get_initial_alarm_result, get_query info = { 'version': 0.1, 'name': 'User-agent module', 'alarmmsg': 'VISIT FROM BLACKLISTED USERAGENT TO C2_*', 'description': 'This check queries for UA\'s that are listed in any blacklist_useragents.conf an...
0.42919
0.093802
import csv import pandas as pd import geopandas as gpd import dash_html_components as html def seismic_reporting_data(occurence): ''' Seismic Reporting Function Collects the additional features of the disaster like 'Tsunami Alerts', 'Danger Alerts' Depends on the occurence type that is being chosen Parameter : `...
report_alerts.py
import csv import pandas as pd import geopandas as gpd import dash_html_components as html def seismic_reporting_data(occurence): ''' Seismic Reporting Function Collects the additional features of the disaster like 'Tsunami Alerts', 'Danger Alerts' Depends on the occurence type that is being chosen Parameter : `...
0.632616
0.387864
import tkinter as tk from tkinter import ttk from scrolledlist_frame import ScrolledList class CatFrm(tk.Frame): """A frame where a word for translation might be selected from a category or a subcategory of words. Contains widgets: 'self.catcb' combobox for choosing a category, 'self.subcatcb' co...
dictionary/categories_frame.py
import tkinter as tk from tkinter import ttk from scrolledlist_frame import ScrolledList class CatFrm(tk.Frame): """A frame where a word for translation might be selected from a category or a subcategory of words. Contains widgets: 'self.catcb' combobox for choosing a category, 'self.subcatcb' co...
0.64969
0.386503
from flask import Flask , request, render_template from threading import Thread import youtube_dl from flask_socketio import SocketIO, emit import os app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv("secret") socketio = SocketIO(app) user_sess = {} @socketio.on('bg-job') def handle_json(messag...
app.py
from flask import Flask , request, render_template from threading import Thread import youtube_dl from flask_socketio import SocketIO, emit import os app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv("secret") socketio = SocketIO(app) user_sess = {} @socketio.on('bg-job') def handle_json(messag...
0.226441
0.062445
# use tdklib library,which provides a wrapper for tdk testcase script import tdklib; from time import sleep; #Test component to be tested obj = tdklib.TDKScriptingLibrary("sysutil","1"); #IP and Port of box, No need to change, #This will be replaced with corresponding DUT Ip and port while executing script ip = <ipadd...
testscripts/RDKB/component/sysutil/TS_SANITY_CheckForSignificantErrorLogMsg.py
# use tdklib library,which provides a wrapper for tdk testcase script import tdklib; from time import sleep; #Test component to be tested obj = tdklib.TDKScriptingLibrary("sysutil","1"); #IP and Port of box, No need to change, #This will be replaced with corresponding DUT Ip and port while executing script ip = <ipadd...
0.228071
0.173201
import numpy as np import scipy.special import masp.array_response_simulator as asr import masp.utils from masp.validate_data_types import _validate_int, _validate_ndarray_2D, _validate_string, _validate_float, \ _validate_ndarray_1D, _validate_ndarray def simulate_sph_array(N_filt, mic_dirs_rad, src_dirs_rad, a...
masp/array_response_simulator/simulate_array.py
import numpy as np import scipy.special import masp.array_response_simulator as asr import masp.utils from masp.validate_data_types import _validate_int, _validate_ndarray_2D, _validate_string, _validate_float, \ _validate_ndarray_1D, _validate_ndarray def simulate_sph_array(N_filt, mic_dirs_rad, src_dirs_rad, a...
0.873943
0.740491
from django.core.exceptions import ObjectDoesNotExist from django.utils.encoding import smart_text from rest_framework import exceptions, relations from resolwe.permissions.shortcuts import get_objects_for_user from resolwe.permissions.utils import get_full_perm class DictRelatedField(relations.RelatedField): "...
resolwe/flow/serializers/fields.py
from django.core.exceptions import ObjectDoesNotExist from django.utils.encoding import smart_text from rest_framework import exceptions, relations from resolwe.permissions.shortcuts import get_objects_for_user from resolwe.permissions.utils import get_full_perm class DictRelatedField(relations.RelatedField): "...
0.817502
0.216239
from nemo.collections import nlp as nemo_nlp from nemo.utils.exp_manager import exp_manager from nemo.collections.nlp.parts.utils_funcs import tensor2list from nemo.collections.nlp.parts.nlp_overrides import NLPDDPPlugin import os import wget import torch import pytorch_lightning as pl from omegaconf import OmegaConf...
finetuning/re/re_ddp.py
from nemo.collections import nlp as nemo_nlp from nemo.utils.exp_manager import exp_manager from nemo.collections.nlp.parts.utils_funcs import tensor2list from nemo.collections.nlp.parts.nlp_overrides import NLPDDPPlugin import os import wget import torch import pytorch_lightning as pl from omegaconf import OmegaConf...
0.44553
0.250649
import logging from os.path import join import numpy as np from src.utils.rand_utils import RandUtils from src.data.data_loader import DataLoader from src.utils.config_loader import ConfigLoader from src.data.data_preprocessor import DataPreprocessor from src.features.text_vectorizer import TextVectorizer from src.mo...
WP3/Task3.3/src/tasks/experiments.py
import logging from os.path import join import numpy as np from src.utils.rand_utils import RandUtils from src.data.data_loader import DataLoader from src.utils.config_loader import ConfigLoader from src.data.data_preprocessor import DataPreprocessor from src.features.text_vectorizer import TextVectorizer from src.mo...
0.446495
0.25215
import os.path as osp from itertools import product import matplotlib import matplotlib.colors as colors import matplotlib.pyplot as plt import scipy from scipy.stats import sem import numpy as np import rlutils as rl from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle, Polygon ...
rewardpredictive/plot.py
import os.path as osp from itertools import product import matplotlib import matplotlib.colors as colors import matplotlib.pyplot as plt import scipy from scipy.stats import sem import numpy as np import rlutils as rl from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle, Polygon ...
0.38318
0.50415
import asyncio from libp2p.protocol_muxer.multiselect_client import MultiselectClient from libp2p.protocol_muxer.multiselect import Multiselect from libp2p.peer.id import id_b58_decode from .network_interface import INetwork from .notifee_interface import INotifee from .stream.net_stream import NetStream from .connec...
libp2p/network/swarm.py
import asyncio from libp2p.protocol_muxer.multiselect_client import MultiselectClient from libp2p.protocol_muxer.multiselect import Multiselect from libp2p.peer.id import id_b58_decode from .network_interface import INetwork from .notifee_interface import INotifee from .stream.net_stream import NetStream from .connec...
0.413004
0.126407
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the “Software”), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ...
bittensor/_neuron/text/template_server/run.py
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the “Software”), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ...
0.694406
0.239161
import numpy as np class GridWorld: NUM_STATES = 90 NUM_FEATURES = 3 NUM_ACTIONS = 4 def __init__(self): # initialize empty transition and reward tables self.p = np.zeros((30, 3, 30, 3, 4), dtype=np.float32) self.r = np.zeros((30, 3, 4), dtype=np.float32) # fill in ...
model_transfer/gridworld.py
import numpy as np class GridWorld: NUM_STATES = 90 NUM_FEATURES = 3 NUM_ACTIONS = 4 def __init__(self): # initialize empty transition and reward tables self.p = np.zeros((30, 3, 30, 3, 4), dtype=np.float32) self.r = np.zeros((30, 3, 4), dtype=np.float32) # fill in ...
0.642545
0.676793
#-------------------- # System wide imports # ------------------- import hashlib import logging # --------------- # Airflow imports # --------------- from airflow.providers.sqlite.hooks.sqlite import SqliteHook #-------------- # local imports # ------------- # ----------------------- # Module global variables # -...
src/airflow_actionproject/callables/streetspectra.py
#-------------------- # System wide imports # ------------------- import hashlib import logging # --------------- # Airflow imports # --------------- from airflow.providers.sqlite.hooks.sqlite import SqliteHook #-------------- # local imports # ------------- # ----------------------- # Module global variables # -...
0.435661
0.073696
import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') #================================================ #Plots for the Value Function Iteration Lab #================================================ import numpy as np import math from scipy import stats as st import discretenorm f...
Vol2B/DynamicOpt1-Value/plots.py
import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') #================================================ #Plots for the Value Function Iteration Lab #================================================ import numpy as np import math from scipy import stats as st import discretenorm f...
0.487063
0.615839
import numpy as np from typing import Callable class GeneticAlgorithm: def __init__(self, population: list, calculate_fitness: Callable[..., float], mutate: Callable[], crossover: Callable[]): self.calculate_fitness = calculate_fitness ...
genetic.py
import numpy as np from typing import Callable class GeneticAlgorithm: def __init__(self, population: list, calculate_fitness: Callable[..., float], mutate: Callable[], crossover: Callable[]): self.calculate_fitness = calculate_fitness ...
0.730674
0.578746
"""Project class.""" from datetime import datetime from pathlib import Path from typing import List from urllib.parse import quote, urlparse from marshmallow import EXCLUDE from renku.core.management.migrate import SUPPORTED_PROJECT_VERSION from renku.core.metadata.database import persistent from renku.core.models i...
renku/core/models/project.py
"""Project class.""" from datetime import datetime from pathlib import Path from typing import List from urllib.parse import quote, urlparse from marshmallow import EXCLUDE from renku.core.management.migrate import SUPPORTED_PROJECT_VERSION from renku.core.metadata.database import persistent from renku.core.models i...
0.877359
0.179153
import collections, random from numpy import array from nltk.metrics import masi_distance, f_measure, precision, recall from nltk.probability import FreqDist, ConditionalFreqDist def sum_category_word_scores(categorized_words, score_fn): word_fd = FreqDist() category_word_fd = ConditionalFreqDist() for category, ...
nltk_trainer/classification/scoring.py
import collections, random from numpy import array from nltk.metrics import masi_distance, f_measure, precision, recall from nltk.probability import FreqDist, ConditionalFreqDist def sum_category_word_scores(categorized_words, score_fn): word_fd = FreqDist() category_word_fd = ConditionalFreqDist() for category, ...
0.323808
0.306871
import numpy as np import torch from .cluster_cpu import cluster as cluster_cpu try: from .cluster_cuda import cluster as cluster_gpu except ImportError: pass def cluster( hashes, lengths, groups=None, counts=None, centroids=None, distances=None, bitcounts=None, clusters=30, ...
language-modeling/fast_transformers/clustering/hamming/__init__.py
import numpy as np import torch from .cluster_cpu import cluster as cluster_cpu try: from .cluster_cuda import cluster as cluster_gpu except ImportError: pass def cluster( hashes, lengths, groups=None, counts=None, centroids=None, distances=None, bitcounts=None, clusters=30, ...
0.896467
0.645707
import sys import logging import argparse import yaml import subprocess import os RESTIC = "restic" LVS = "lvs" config = [] class BackupException(Exception): pass class Config: def __init__(self, configFile, prune): with open(configFile, 'r') as stream: configYaml = yaml.safe_load(strea...
lvm-backup.py
import sys import logging import argparse import yaml import subprocess import os RESTIC = "restic" LVS = "lvs" config = [] class BackupException(Exception): pass class Config: def __init__(self, configFile, prune): with open(configFile, 'r') as stream: configYaml = yaml.safe_load(strea...
0.129458
0.053059
# Python modules import datetime # NOC modules from noc.sa.models.interactionlog import InteractionLog from noc.config import config def get_seconds(section, option): v = config.get(section, option) m = 1 if v.endswith("h"): v = v[:-1] m = 3600 elif v.endswith("d"): v = v[:-1...
fm/handlers/event/audit.py
# Python modules import datetime # NOC modules from noc.sa.models.interactionlog import InteractionLog from noc.config import config def get_seconds(section, option): v = config.get(section, option) m = 1 if v.endswith("h"): v = v[:-1] m = 3600 elif v.endswith("d"): v = v[:-1...
0.364325
0.12416
import random import streamlit as st from typing import Tuple, List from streamlit.config import _global_development_mode MAX_GAMES = 10_000 def simulate_handle(start: float, payback_rate: float, bet: float) -> Tuple[float, int, List[float]]: """Run a simulation game and stop when player is broken Parame...
app/app.py
import random import streamlit as st from typing import Tuple, List from streamlit.config import _global_development_mode MAX_GAMES = 10_000 def simulate_handle(start: float, payback_rate: float, bet: float) -> Tuple[float, int, List[float]]: """Run a simulation game and stop when player is broken Parame...
0.855881
0.411347
import csv import json def main(): _user_input() raw_data = _get_data() filter_data = _filter_json() filtered_csv = _filter_csv(raw_data, filter_data) _write_to_file(filtered_csv) def _user_input(): print("Welcome to PGH Capital Projects. Now with search features!") print("Which topic...
Week 04/Project/BG_DAT129_HW04_Project.py
import csv import json def main(): _user_input() raw_data = _get_data() filter_data = _filter_json() filtered_csv = _filter_csv(raw_data, filter_data) _write_to_file(filtered_csv) def _user_input(): print("Welcome to PGH Capital Projects. Now with search features!") print("Which topic...
0.073505
0.21308
r"""ICNet Semantic Segmentation architecture. As described in http://arxiv.org/abs/1704.08545. ICNet for Real-Time Semantic Segmentation on High-Resolution Images <NAME>, <NAME>, <NAME>, <NAME>, <NAME> """ from abc import abstractmethod from functools import partial import tensorflow as tf from . import base...
segmentation/architectures/icnet_architecture.py
r"""ICNet Semantic Segmentation architecture. As described in http://arxiv.org/abs/1704.08545. ICNet for Real-Time Semantic Segmentation on High-Resolution Images <NAME>, <NAME>, <NAME>, <NAME>, <NAME> """ from abc import abstractmethod from functools import partial import tensorflow as tf from . import base...
0.94831
0.341857
import typing as t from toollib.validator import Attr class Arg: def __init__(self, *name_or_flags: str, action: str = None, nargs: t.Union[int, str] = None, const: t.Any = None, default: t.Any = None, type: typ...
toollib/tcli/option.py
import typing as t from toollib.validator import Attr class Arg: def __init__(self, *name_or_flags: str, action: str = None, nargs: t.Union[int, str] = None, const: t.Any = None, default: t.Any = None, type: typ...
0.693161
0.118385
import unittest import torch from torch import nn import torch_testing as tt from all.core import State from all.approximation.feature_network import FeatureNetwork STATE_DIM = 2 class TestFeatureNetwork(unittest.TestCase): def setUp(self): torch.manual_seed(2) self.model = nn.Sequential(nn.Linea...
all/approximation/feature_network_test.py
import unittest import torch from torch import nn import torch_testing as tt from all.core import State from all.approximation.feature_network import FeatureNetwork STATE_DIM = 2 class TestFeatureNetwork(unittest.TestCase): def setUp(self): torch.manual_seed(2) self.model = nn.Sequential(nn.Linea...
0.837188
0.684254
from nl_open_data.config import config from prefect import task, Flow, unmapped, Parameter from prefect.run_configs import LocalRun from prefect.storage import GCS from prefect.executors import DaskExecutor import nl_open_data.tasks as nlt with Flow("statline-catalogs") as st_catalogs_flow: catalog_urls = Parame...
nl_open_data/flows/register/register_statline_catalog_flow.py
from nl_open_data.config import config from prefect import task, Flow, unmapped, Parameter from prefect.run_configs import LocalRun from prefect.storage import GCS from prefect.executors import DaskExecutor import nl_open_data.tasks as nlt with Flow("statline-catalogs") as st_catalogs_flow: catalog_urls = Parame...
0.107689
0.212395
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: alicloud_security_group_facts version_added: "2.4" short_description: Gather facts on security group of Alibaba Cloud ECS. description: - This...
lib/ansible/modules/cloud/alicloud/alicloud_security_group_facts.py
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: alicloud_security_group_facts version_added: "2.4" short_description: Gather facts on security group of Alibaba Cloud ECS. description: - This...
0.562056
0.22289
import numpy as np import pytest from dirty_cat import target_encoder def test_target_encoder(): lambda_ = target_encoder.lambda_ X1 = np.array(['Red', 'red', 'green', 'blue', 'green', 'green', '...
dirty_cat/test/test_target_encoder.py
import numpy as np import pytest from dirty_cat import target_encoder def test_target_encoder(): lambda_ = target_encoder.lambda_ X1 = np.array(['Red', 'red', 'green', 'blue', 'green', 'green', '...
0.596668
0.51251
import logging import os import subprocess import warnings from builtins import object from collections import defaultdict from typing import DefaultDict, List, Optional, Tuple from bs4 import BeautifulSoup from IPython.display import DisplayHandle, display from wand.color import Color from wand.drawing import Drawing...
src/fonduer/utils/visualizer.py
import logging import os import subprocess import warnings from builtins import object from collections import defaultdict from typing import DefaultDict, List, Optional, Tuple from bs4 import BeautifulSoup from IPython.display import DisplayHandle, display from wand.color import Color from wand.drawing import Drawing...
0.90165
0.229967
from multiprocessing.pool import Pool import tables from phd.satellite.geant4_server import DetectorMode, Geant4Server import numpy as np from phd.satellite.run import request_generator from phd.satellite.satellite_pb2 import Run from phd.satellite.single_processing import load_likelihood_factory from phd.satellite.pr...
python/simulation_scripts/satellite/test_recontruction.py
from multiprocessing.pool import Pool import tables from phd.satellite.geant4_server import DetectorMode, Geant4Server import numpy as np from phd.satellite.run import request_generator from phd.satellite.satellite_pb2 import Run from phd.satellite.single_processing import load_likelihood_factory from phd.satellite.pr...
0.471953
0.348617
from keras.models import Model from keras.layers import Activation, Concatenate, Dense, Flatten, Input from keras.layers import LeakyReLU, Reshape from keras.layers import Conv2D, UpSampling2D from keras.layers import BatchNormalization def cs_generator(scene_size, modis_var_dim, noise_dim): f = 256 start_dim...
csmodiscgan/src/models.py
from keras.models import Model from keras.layers import Activation, Concatenate, Dense, Flatten, Input from keras.layers import LeakyReLU, Reshape from keras.layers import Conv2D, UpSampling2D from keras.layers import BatchNormalization def cs_generator(scene_size, modis_var_dim, noise_dim): f = 256 start_dim...
0.952627
0.694743
from datetime import datetime import yaml class DataValidator: def __init__(self): self.master_config = 'etc/weatherman.yml' with open(self.master_config) as ycf: self.config = yaml.load(ycf, Loader=yaml.FullLoader) def is_datetime(self, datetime_str): """ Is the ...
weatherman/data_validator.py
from datetime import datetime import yaml class DataValidator: def __init__(self): self.master_config = 'etc/weatherman.yml' with open(self.master_config) as ycf: self.config = yaml.load(ycf, Loader=yaml.FullLoader) def is_datetime(self, datetime_str): """ Is the ...
0.517083
0.262505
import os, time """ Modify following configurations to adapt to your environment. """ test_cases_dir = '../testcases/semantic/' # test_cases_dir = '../testcases/codegen/' # test_cases_dir = '../testcases/optim/' compile_cmd = "bash ../build.bash" execute_cmd = "bash ../semantic.bash" excluded_test_cases = ["foo....
tools/local_judge.py
import os, time """ Modify following configurations to adapt to your environment. """ test_cases_dir = '../testcases/semantic/' # test_cases_dir = '../testcases/codegen/' # test_cases_dir = '../testcases/optim/' compile_cmd = "bash ../build.bash" execute_cmd = "bash ../semantic.bash" excluded_test_cases = ["foo....
0.27406
0.229093
import numpy as np if True: # Include project path import sys import os ROOT = os.path.dirname(os.path.abspath(__file__))+"/../" CURR_PATH = os.path.dirname(os.path.abspath(__file__))+"/" sys.path.append(ROOT) import utils.lib_commons as lib_commons from utils.lib_skeletons_io import load...
src/s3_preprocess_features.py
import numpy as np if True: # Include project path import sys import os ROOT = os.path.dirname(os.path.abspath(__file__))+"/../" CURR_PATH = os.path.dirname(os.path.abspath(__file__))+"/" sys.path.append(ROOT) import utils.lib_commons as lib_commons from utils.lib_skeletons_io import load...
0.311008
0.209955
import numpy as np import pandas as pd import plotly.figure_factory as ff import cufflinks as cf from . import tools cf.go_offline() def distplot1d(ss: pd.Series, bins=10, hist=True, kde=True, rug=True, color=None, as_figure=False, legend=True, title=True, grid=True, figsize=None, **kwargs): ss = ...
mplotly/mplotly.py
import numpy as np import pandas as pd import plotly.figure_factory as ff import cufflinks as cf from . import tools cf.go_offline() def distplot1d(ss: pd.Series, bins=10, hist=True, kde=True, rug=True, color=None, as_figure=False, legend=True, title=True, grid=True, figsize=None, **kwargs): ss = ...
0.68941
0.400544
from caribou.settings.setting_types import * from gi.repository import GObject from gi.repository import Gdk from gi.repository import Gtk class AbstractPreferencesUI: def populate_settings(self, settings_manager): if getattr(self, "notebook", None) is None: self.notebook = Gtk.Notebook() ...
stdlib2-src/dist-packages/caribou/settings/preferences_window.py
from caribou.settings.setting_types import * from gi.repository import GObject from gi.repository import Gdk from gi.repository import Gtk class AbstractPreferencesUI: def populate_settings(self, settings_manager): if getattr(self, "notebook", None) is None: self.notebook = Gtk.Notebook() ...
0.570571
0.130895
import torch import torch.nn as nn from torch import autograd import torch.nn.functional as F import numpy as np class NaturalGradientDescentVelNet(nn.Module): """ taskmap_fcn: map to a latent space grad_taskmap_fcn: jacobian of the map grad_potential_fcn: gradient of a potential fcn defined on the mapped space ...
euclideanizing_flows/flows.py
import torch import torch.nn as nn from torch import autograd import torch.nn.functional as F import numpy as np class NaturalGradientDescentVelNet(nn.Module): """ taskmap_fcn: map to a latent space grad_taskmap_fcn: jacobian of the map grad_potential_fcn: gradient of a potential fcn defined on the mapped space ...
0.903341
0.638892
import time import numpy as np from scipy.sparse import coo_matrix from implicit.approximate_als import FaissAlternatingLeastSquares from implicit.nearest_neighbours import bm25_weight from implicit.datasets.movielens import get_movielens def experiment(B, K1, conf, variant='20m', min_rating=3.0): # read in the i...
ch04-recommending-products-and-services/movielens.py
import time import numpy as np from scipy.sparse import coo_matrix from implicit.approximate_als import FaissAlternatingLeastSquares from implicit.nearest_neighbours import bm25_weight from implicit.datasets.movielens import get_movielens def experiment(B, K1, conf, variant='20m', min_rating=3.0): # read in the i...
0.49707
0.476275
import subprocess def collect(): filter_keys = ['Manufacturer', 'Serial Number', 'Product Name', 'UUID', 'Wake-up Type'] raw_data = {} for key in filter_keys: try: res = subprocess.Popen("sudo dmidecode -t system|grep '%s'" % key, stdout=subprocess....
Client/plugins/collect_linux_info.py
import subprocess def collect(): filter_keys = ['Manufacturer', 'Serial Number', 'Product Name', 'UUID', 'Wake-up Type'] raw_data = {} for key in filter_keys: try: res = subprocess.Popen("sudo dmidecode -t system|grep '%s'" % key, stdout=subprocess....
0.229708
0.172381
import tensorflow as tf from tensorflow_probability.python.internal import special_math from tensorflow_probability import distributions as tfd import tensorflow_probability as tfp from tensorflow_probability import bijectors as tfb from tensorflow_probability.python.internal import tensor_util import numpy as np cla...
careless/utils/distributions.py
import tensorflow as tf from tensorflow_probability.python.internal import special_math from tensorflow_probability import distributions as tfd import tensorflow_probability as tfp from tensorflow_probability import bijectors as tfb from tensorflow_probability.python.internal import tensor_util import numpy as np cla...
0.951953
0.839734
import logging import numpy as np import pandas as pd import scipy.signal as signal from import_data import import_data from extract_data import extract_time_data from extract_data import extract_template_data logging.basicConfig(filename='hrmonitorlog.txt', format='%(levelname)s \ %(asctime)s %(message)s', datefmt='%m...
mean_hr_bpm.py
import logging import numpy as np import pandas as pd import scipy.signal as signal from import_data import import_data from extract_data import extract_time_data from extract_data import extract_template_data logging.basicConfig(filename='hrmonitorlog.txt', format='%(levelname)s \ %(asctime)s %(message)s', datefmt='%m...
0.523908
0.445409
import config import customer_details import no_found def show_customers(bit): conn,cursor=config.connect_to_database() sql="select * from customers where hasAcc='%s'"%bit try: cursor.execute(sql) results=cursor.fetchall() row_num=cursor.rowcount bit=int(bit) if bit==0: flag="New customers" cust_id="...
admin_show_customers.py
import config import customer_details import no_found def show_customers(bit): conn,cursor=config.connect_to_database() sql="select * from customers where hasAcc='%s'"%bit try: cursor.execute(sql) results=cursor.fetchall() row_num=cursor.rowcount bit=int(bit) if bit==0: flag="New customers" cust_id="...
0.043003
0.106133
import math import cairo import poppler import lmcore import datetime import sys import getopt today = datetime.date.today() year = today.strftime('%Y') A4_size_mm = [210.0, 297.0] def mm_to_inch(iterable): return [i * 0.0393700787 for i in iterable] def inch_to_point(iterable): return [i * 72.0 for i in it...
bibgen.py
import math import cairo import poppler import lmcore import datetime import sys import getopt today = datetime.date.today() year = today.strftime('%Y') A4_size_mm = [210.0, 297.0] def mm_to_inch(iterable): return [i * 0.0393700787 for i in iterable] def inch_to_point(iterable): return [i * 72.0 for i in it...
0.220007
0.245865
import json from typing import Dict, List, NewType from google.appengine.ext import ndb from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.award import Award from backend.common.models.event import Event from backend.common.models.team import Team from backend.common.queries.dict...
src/backend/common/queries/dict_converters/award_converter.py
import json from typing import Dict, List, NewType from google.appengine.ext import ndb from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.award import Award from backend.common.models.event import Event from backend.common.models.team import Team from backend.common.queries.dict...
0.612078
0.179872
import string import unittest from enigma import Reflector, Rotor, RotorMechanism class TestRotorMechanism(unittest.TestCase): """Test class for enigma's rotor mechanism.""" def get_rotors(self, settings): """Return rotor set.""" return [Rotor(**setting) for setting in settings] def ge...
tests/test_rotor/test_rotor_mechanism.py
import string import unittest from enigma import Reflector, Rotor, RotorMechanism class TestRotorMechanism(unittest.TestCase): """Test class for enigma's rotor mechanism.""" def get_rotors(self, settings): """Return rotor set.""" return [Rotor(**setting) for setting in settings] def ge...
0.864038
0.459319
import math import itertools import collections import numpy from ..dataset.dataset import DataSet from ..statistics.random import RandomState # Disable variable name nagging since these are mostly math functions # pylint: disable=invalid-name def new_labels(samples: int = 1024, random_seed: int = None, key: str ...
bananas/sampledata/synthetic.py
import math import itertools import collections import numpy from ..dataset.dataset import DataSet from ..statistics.random import RandomState # Disable variable name nagging since these are mostly math functions # pylint: disable=invalid-name def new_labels(samples: int = 1024, random_seed: int = None, key: str ...
0.528533
0.561696
import typing as t import numpy as np def bootstrap( samples: np.ndarray, num_resamples: int = 256, random_state: t.Optional[int] = None, ) -> np.ndarray: """Generator of bootstraps ``samples``. Arguments --------- samples : :obj:`np.ndarray` Population to draw samples from. ...
confidence_intervals/bootstrap.py
import typing as t import numpy as np def bootstrap( samples: np.ndarray, num_resamples: int = 256, random_state: t.Optional[int] = None, ) -> np.ndarray: """Generator of bootstraps ``samples``. Arguments --------- samples : :obj:`np.ndarray` Population to draw samples from. ...
0.842183
0.775286
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
python/discodisco/generated/proto/grpc/remote_pb2.py
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
0.331012
0.074265
from dataclasses import dataclass ''' @property is getter method getter use: Class.attribute @attribute.setter is setter method setter use: Class.attribute = attribute dataclass(frozen=True) is immutable ''' @dataclass class SettingsModel: ''' Data class for settings objects ''' _dialect: str ...
big_teacher/src/model/DataModel.py
from dataclasses import dataclass ''' @property is getter method getter use: Class.attribute @attribute.setter is setter method setter use: Class.attribute = attribute dataclass(frozen=True) is immutable ''' @dataclass class SettingsModel: ''' Data class for settings objects ''' _dialect: str ...
0.725843
0.098686
import os import time import analogio import board import busio import displayio import neopixel import sdcardio import storage import adafruit_ili9341 import adafruit_ov5640 # Release any resources currently in use for the displays displayio.release_displays() spi = busio.SPI(MOSI=board.LCD_MOSI, cl...
py/adafruit-circuitpython-bundle-7.x-mpy-20211104/examples/ov5640_sdcard_kaluga_1_3.py
import os import time import analogio import board import busio import displayio import neopixel import sdcardio import storage import adafruit_ili9341 import adafruit_ov5640 # Release any resources currently in use for the displays displayio.release_displays() spi = busio.SPI(MOSI=board.LCD_MOSI, cl...
0.275909
0.086362
# automate the tasks of managing a file-based postfix virtual alias / mailbox server # written by masenf # one day hack, the Version import argparse import base64 import difflib import logging import pwd import os import random import shutil import sys import tempfile import time from subprocess import check_output, ...
mailtool.py
# automate the tasks of managing a file-based postfix virtual alias / mailbox server # written by masenf # one day hack, the Version import argparse import base64 import difflib import logging import pwd import os import random import shutil import sys import tempfile import time from subprocess import check_output, ...
0.336658
0.082809
from django.db import models from django.shortcuts import reverse from users.models import Achievement class Page(models.Model): class Permissions(models.IntegerChoices): PUBLIC = 0, 'Public' USER = 1, 'Logged In' MEMBER = 2, 'Member' EX_EXEC = 3, 'Ex-Exec' EXEC = 4, 'Exec...
pages/models.py
from django.db import models from django.shortcuts import reverse from users.models import Achievement class Page(models.Model): class Permissions(models.IntegerChoices): PUBLIC = 0, 'Public' USER = 1, 'Logged In' MEMBER = 2, 'Member' EX_EXEC = 3, 'Ex-Exec' EXEC = 4, 'Exec...
0.547222
0.082143
print("Part 1") print("") print_me = 10 for i in range(9): string = "" for j in range(i+1): string += str(print_me) + " " print_me += 1 print(string) print("") print("Part 2") print("") n = int(input("How large of a box? ")) border = 'o'*2*n inner = 'o' + ' '*(2*n-2) + 'o' p...
Exercises/5/main.py
print("Part 1") print("") print_me = 10 for i in range(9): string = "" for j in range(i+1): string += str(print_me) + " " print_me += 1 print(string) print("") print("Part 2") print("") n = int(input("How large of a box? ")) border = 'o'*2*n inner = 'o' + ' '*(2*n-2) + 'o' p...
0.23793
0.10004
from typing import Tuple, Any, Callable, Optional, Dict, Type from ax.core.runner import Runner from ax.runners.synthetic import SyntheticRunner from ax.storage.json_store.encoders import runner_to_dict from ax.storage.json_store.registry import CORE_ENCODER_REGISTRY, CORE_DECODER_REGISTRY from ax.utils.common.logger...
ax/storage/runner_registry.py
from typing import Tuple, Any, Callable, Optional, Dict, Type from ax.core.runner import Runner from ax.runners.synthetic import SyntheticRunner from ax.storage.json_store.encoders import runner_to_dict from ax.storage.json_store.registry import CORE_ENCODER_REGISTRY, CORE_DECODER_REGISTRY from ax.utils.common.logger...
0.714628
0.389169
import logging import tempfile from pathlib import Path from typing import List, Dict, Optional, Union from torch.profiler import profile from ray import train from ray.train.callbacks import TrainingCallback from ray.train.callbacks.logging import TrainCallbackLogdirManager from ray.train.callbacks.results_preproces...
python/ray/train/callbacks/profile.py
import logging import tempfile from pathlib import Path from typing import List, Dict, Optional, Union from torch.profiler import profile from ray import train from ray.train.callbacks import TrainingCallback from ray.train.callbacks.logging import TrainCallbackLogdirManager from ray.train.callbacks.results_preproces...
0.882441
0.175044
import os import yaml import zipfile import shutil import lmctl.files as files import lmctl.project.handlers.interface as handlers_api import lmctl.project.validation as project_validation import lmctl.utils.descriptors as descriptor_utils from .brent_content import BrentResourcePackageContentTree, BrentPkgContentTree ...
lmctl/project/handlers/brent/brent_src.py
import os import yaml import zipfile import shutil import lmctl.files as files import lmctl.project.handlers.interface as handlers_api import lmctl.project.validation as project_validation import lmctl.utils.descriptors as descriptor_utils from .brent_content import BrentResourcePackageContentTree, BrentPkgContentTree ...
0.5144
0.122471
from collections import namedtuple from collections.abc import Mapping, Set from pypyr.dsl import SpecialTagDirective from pypyr.errors import KeyInContextHasNoValueError, KeyNotInContextError from pypyr.formatting import RecursiveFormatter from pypyr.moduleloader import _ChainMapPretendDict from pypyr.utils import as...
pypyr/context.py
from collections import namedtuple from collections.abc import Mapping, Set from pypyr.dsl import SpecialTagDirective from pypyr.errors import KeyInContextHasNoValueError, KeyNotInContextError from pypyr.formatting import RecursiveFormatter from pypyr.moduleloader import _ChainMapPretendDict from pypyr.utils import as...
0.906266
0.360095
import sys import operator class UnionFind(): def __init__(self, n_nodes): """ Union-Find data structure initialization sets each node to be its own parent (so that each node is in its own set/connected component), and to also have rank 0. Input - n_nodes: no of nodes ...
hackerrank/2017/w28/frndshp/frndshp.py
import sys import operator class UnionFind(): def __init__(self, n_nodes): """ Union-Find data structure initialization sets each node to be its own parent (so that each node is in its own set/connected component), and to also have rank 0. Input - n_nodes: no of nodes ...
0.344333
0.472866
import DistributedLawnDecor from direct.directnotify import DirectNotifyGlobal from direct.showbase.ShowBase import * from direct.interval.IntervalGlobal import * import GardenGlobals from toontown.toonbase import TTLocalizer from toontown.estate import PlantingGUI from toontown.estate import PlantTreeGUI from toontown...
v1.0.0.test/toontown/estate/DistributedGardenPlot.py
import DistributedLawnDecor from direct.directnotify import DirectNotifyGlobal from direct.showbase.ShowBase import * from direct.interval.IntervalGlobal import * import GardenGlobals from toontown.toonbase import TTLocalizer from toontown.estate import PlantingGUI from toontown.estate import PlantTreeGUI from toontown...
0.375363
0.143218
import sys from zlib import crc32 from depthcharge import log from depthcharge.hunter import ReverseCRC32Hunter THE_RAVEN = b""" Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore-- While I nodded, nearly napping, suddenly there came a tapping, ...
python/examples/reverse_crc32_algo_poc.py
import sys from zlib import crc32 from depthcharge import log from depthcharge.hunter import ReverseCRC32Hunter THE_RAVEN = b""" Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore-- While I nodded, nearly napping, suddenly there came a tapping, ...
0.232746
0.35516
import matplotlib matplotlib.use('agg') import os import sys import yt import matplotlib.pyplot as plt import numpy as np from functools import reduce from mpl_toolkits.axes_grid1 import ImageGrid # assume that our data is in CGS from yt.units import cm, amu from yt.frontends.boxlib.api import LogiDataset from yt.v...
Exec/science/massive_star/analysis/massive_star_composition.py
import matplotlib matplotlib.use('agg') import os import sys import yt import matplotlib.pyplot as plt import numpy as np from functools import reduce from mpl_toolkits.axes_grid1 import ImageGrid # assume that our data is in CGS from yt.units import cm, amu from yt.frontends.boxlib.api import LogiDataset from yt.v...
0.318909
0.55652
from __future__ import print_function, division, absolute_import from ..rna import ( load_cufflinks_fpkm_dict, load_transcript_fpkm_dict_from_gtf ) def add_rna_args(arg_parser): rna_group = arg_parser.add_argument_group( title="RNA-Seq", description="Transcript and gene abundance quantific...
topiary/cli/rna.py
from __future__ import print_function, division, absolute_import from ..rna import ( load_cufflinks_fpkm_dict, load_transcript_fpkm_dict_from_gtf ) def add_rna_args(arg_parser): rna_group = arg_parser.add_argument_group( title="RNA-Seq", description="Transcript and gene abundance quantific...
0.71113
0.248039
import argparse def str2bool(v): if isinstance(v, bool): return v # pylint: disable=no-else-return if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("Bool...
cloudiscovery/shared/parameters.py
import argparse def str2bool(v): if isinstance(v, bool): return v # pylint: disable=no-else-return if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("Bool...
0.508788
0.124505
import argparse import http.server import logging import os import re import shutil import sys from http import HTTPStatus sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) ) import mdlight.index.tree from mdlight.index.pages import MarkdownPage...
mdlight/server.py
import argparse import http.server import logging import os import re import shutil import sys from http import HTTPStatus sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) ) import mdlight.index.tree from mdlight.index.pages import MarkdownPage...
0.320396
0.061734
import logging from abc import ABC from typing import Mapping, List from tqdm import tqdm from codeprep.preprocess.codestructure import CodeBaseStructure from codeprep.preprocess.tokens import TokenSequence from langmodels.evaluation.characteristics import characterize_token from langmodels.evaluation.dataloader impo...
langmodels/evaluation/metrics.py
import logging from abc import ABC from typing import Mapping, List from tqdm import tqdm from codeprep.preprocess.codestructure import CodeBaseStructure from codeprep.preprocess.tokens import TokenSequence from langmodels.evaluation.characteristics import characterize_token from langmodels.evaluation.dataloader impo...
0.842248
0.173393
from __future__ import print_function import numpy as np import pytest import kernel_tuner from .context import skip_if_no_cuda @pytest.fixture def env(): kernel_string = """ __global__ void vector_add(float *c, float *a, float *b, int n) { int i = blockIdx.x * block_size_x + threadIdx.x; i...
test/test_runners.py
from __future__ import print_function import numpy as np import pytest import kernel_tuner from .context import skip_if_no_cuda @pytest.fixture def env(): kernel_string = """ __global__ void vector_add(float *c, float *a, float *b, int n) { int i = blockIdx.x * block_size_x + threadIdx.x; i...
0.680454
0.539165
import os from ..run import run from ..utils import BuildConfig from ..utils import add_coverage_argument from ..utils import add_jobs_argument from ..utils import add_no_ccache_argument from ..utils import add_optimize_argument from ..utils import add_unsafe_argument from ..utils import add_url_argument from ..utils ...
mys/cli/subparsers/test.py
import os from ..run import run from ..utils import BuildConfig from ..utils import add_coverage_argument from ..utils import add_jobs_argument from ..utils import add_no_ccache_argument from ..utils import add_optimize_argument from ..utils import add_unsafe_argument from ..utils import add_url_argument from ..utils ...
0.23467
0.070528
import random import ray from typing import List, Type import gym import hydra import matplotlib.pyplot as plt import numpy as np from cmaes import CMA from matplotlib import animation from omegaconf.dictconfig import DictConfig from scipy.sparse.csr import csr_matrix from torch import optim from tqdm import tqdm cl...
esn_rl/dqn_esn.py
import random import ray from typing import List, Type import gym import hydra import matplotlib.pyplot as plt import numpy as np from cmaes import CMA from matplotlib import animation from omegaconf.dictconfig import DictConfig from scipy.sparse.csr import csr_matrix from torch import optim from tqdm import tqdm cl...
0.864711
0.568595
import requests from asyncio.tasks import sleep from cogs.dbc import DaedalusBaseCog from core.utils import yaml, dprint, print_exc from discord.colour import Colour from discord.embeds import Embed from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from random import randi...
src/cogs/games.py
import requests from asyncio.tasks import sleep from cogs.dbc import DaedalusBaseCog from core.utils import yaml, dprint, print_exc from discord.colour import Colour from discord.embeds import Embed from discord.ext import commands from discord.ext.commands.cooldowns import BucketType from random import randi...
0.29381
0.111919
from unittest import TestCase import os, sys # 3rd party lib support if sys.version_info[0] == 3: from pathlib import Path else: from pathlib2 import Path ModuleNotFoundError = ImportError # local lib imports try: from pylightxl import pylightxl as xl except ModuleNotFoundError: sys.path.append('...
test/test_readxl.py
from unittest import TestCase import os, sys # 3rd party lib support if sys.version_info[0] == 3: from pathlib import Path else: from pathlib2 import Path ModuleNotFoundError = ImportError # local lib imports try: from pylightxl import pylightxl as xl except ModuleNotFoundError: sys.path.append('...
0.372619
0.413596