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
from SimPy.Simulation import * import random import numpy import math import matplotlib.pyplot as pl ## Useful extras ---------- def conf(L): """confidence interval""" lower = numpy.mean(L) - 1.96*numpy.std(L)/math.sqrt(len(L)) upper = numpy.mean(L) + 1.96*numpy.std(L)/math.sqrt(len(L)) return (lower...
Undergraduate/COMP312/Final Project Submission/.fr-SjIgVy/project/Scripts and Data/MMC.py
from SimPy.Simulation import * import random import numpy import math import matplotlib.pyplot as pl ## Useful extras ---------- def conf(L): """confidence interval""" lower = numpy.mean(L) - 1.96*numpy.std(L)/math.sqrt(len(L)) upper = numpy.mean(L) + 1.96*numpy.std(L)/math.sqrt(len(L)) return (lower...
0.529263
0.420183
from urllib.parse import urlencode import requests from typeform import exception from typeform.enumerator import ErrorEnum class Client(object): BASE_URL = 'https://api.typeform.com/' def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secre...
typeform/client.py
from urllib.parse import urlencode import requests from typeform import exception from typeform.enumerator import ErrorEnum class Client(object): BASE_URL = 'https://api.typeform.com/' def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secre...
0.779657
0.16238
import os import discord import random from discord.ext import commands from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') client = discord.Client() ####################### # Twitch notification # ####################### ############ # Commands # ############ client = ...
main.py
import os import discord import random from discord.ext import commands from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') client = discord.Client() ####################### # Twitch notification # ####################### ############ # Commands # ############ client = ...
0.249082
0.038358
from django.views import View from django.contrib import messages from django.shortcuts import render, redirect from devices.controllers import cisco_controller as controller from devices.models import * class InterfaceDetails(View): template = 'device_interface.html' success_redirect = 'devices:Interface-Det...
NetManager/devices/views/interface.py
from django.views import View from django.contrib import messages from django.shortcuts import render, redirect from devices.controllers import cisco_controller as controller from devices.models import * class InterfaceDetails(View): template = 'device_interface.html' success_redirect = 'devices:Interface-Det...
0.638948
0.05634
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import QApplication,QMainWindow from PyQt5.QtWidgets import * from Ui_login import Ui_Login from Ui_register import Ui_Register from DataBase import DataBase from Ui_tablelist import Ui_TableList from Ui_products import Ui_MainWindow ...
pyqt数据库系统/仓库管理/Ui_main.py
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import QApplication,QMainWindow from PyQt5.QtWidgets import * from Ui_login import Ui_Login from Ui_register import Ui_Register from DataBase import DataBase from Ui_tablelist import Ui_TableList from Ui_products import Ui_MainWindow ...
0.077252
0.048092
import copy from datetime import datetime, timezone from logging import getLogger from typing import Dict, Iterable, Optional, Type, Union, Set, List from ogr.abstract import GitProject from packit.config import JobConfigTriggerType, PackageConfig from packit_service.config import PackageConfigGetter, ServiceConfig f...
packit_service/worker/events/event.py
import copy from datetime import datetime, timezone from logging import getLogger from typing import Dict, Iterable, Optional, Type, Union, Set, List from ogr.abstract import GitProject from packit.config import JobConfigTriggerType, PackageConfig from packit_service.config import PackageConfigGetter, ServiceConfig f...
0.76238
0.226612
import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class AlertsOperations(object): """AlertsOperations operations. You should not instantiate directly this class, but create a Client instance that will create it for you and at...
sdk/security/azure-mgmt-security/azure/mgmt/security/operations/_alerts_operations.py
import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class AlertsOperations(object): """AlertsOperations operations. You should not instantiate directly this class, but create a Client instance that will create it for you and at...
0.808483
0.109182
import os import numpy as np from PIL import Image # pylint: disable=E0401 import tensorflow.compat.v1 as tf # pylint: disable=C0411, E0401 # Import AMCT toolkit and set log level. There are four log levels, # 'info', 'debug', 'warning' and 'error'. The default level is 'info'. import amct_tensorflow as amct # pylint:...
python/level1_single_api/9_amct/amct_tensorflow/resnet-50_v1/src/resnet-50_v1_nuq.py
import os import numpy as np from PIL import Image # pylint: disable=E0401 import tensorflow.compat.v1 as tf # pylint: disable=C0411, E0401 # Import AMCT toolkit and set log level. There are four log levels, # 'info', 'debug', 'warning' and 'error'. The default level is 'info'. import amct_tensorflow as amct # pylint:...
0.402627
0.213551
import math import random import sys class gen: """条件式のジェネレータ""" # ランダムでループを回しても operators と sentences の位置を同期する op_index = [0, 1, 2, 3, 4, 5] # python の比較演算子リスト(問題集として利用するには、' == ' と ' != ' をそれぞれ '=', '<>' に変換する) operators = { 0: ' == ', 1: ' != ', 2: ' < ', 3: ' > ', 4: ' <= ',...
create_drills.py
import math import random import sys class gen: """条件式のジェネレータ""" # ランダムでループを回しても operators と sentences の位置を同期する op_index = [0, 1, 2, 3, 4, 5] # python の比較演算子リスト(問題集として利用するには、' == ' と ' != ' をそれぞれ '=', '<>' に変換する) operators = { 0: ' == ', 1: ' != ', 2: ' < ', 3: ' > ', 4: ' <= ',...
0.154919
0.422683
import logging import os import shutil import sys import GPy import numpy as np import pandas as pd import seaborn as sb from config import Config from controllers import sin_controller_02D from dynamics import dynamics_traj, duffing_dynamics, pendulum_dynamics, \ VanderPol_dynamics, duffing_dynamics_discrete, \ ...
quasilinear_observer_GP.py
import logging import os import shutil import sys import GPy import numpy as np import pandas as pd import seaborn as sb from config import Config from controllers import sin_controller_02D from dynamics import dynamics_traj, duffing_dynamics, pendulum_dynamics, \ VanderPol_dynamics, duffing_dynamics_discrete, \ ...
0.583915
0.251223
from contextlib import contextmanager from capybara.selector.expression_filter import ExpressionFilter from capybara.selector.node_filter import NodeFilter filter_sets = {} # Dict[str, FilterSet]: A dictionary of global filter sets keyed by name. class FilterSet(object): """ A group of filters for use by :...
capybara/selector/filter_set.py
from contextlib import contextmanager from capybara.selector.expression_filter import ExpressionFilter from capybara.selector.node_filter import NodeFilter filter_sets = {} # Dict[str, FilterSet]: A dictionary of global filter sets keyed by name. class FilterSet(object): """ A group of filters for use by :...
0.89751
0.288657
class ModelItemBase(object): def __init__(self, **kwargs): for k in kwargs.keys(): setattr(self, k, kwargs[k]) class IngredientTypeDef(ModelItemBase): def get_default_unit(self): return self.get_all_units()[0] def get_all_units(self): if self.extends is not None: ...
recipec/mm_classes.py
class ModelItemBase(object): def __init__(self, **kwargs): for k in kwargs.keys(): setattr(self, k, kwargs[k]) class IngredientTypeDef(ModelItemBase): def get_default_unit(self): return self.get_all_units()[0] def get_all_units(self): if self.extends is not None: ...
0.635675
0.218795
from django.test import TestCase from djangojs.utils import StorageGlobber from os.path import normpath class StorageGlobberTest(TestCase): def test_no_js_file(self): '''Should handle empty js file list''' self.assertEqual(StorageGlobber.glob(), []) def test_single_js_file(self): ''...
myenv/lib/python3.5/site-packages/djangojs/tests/test_globber.py
from django.test import TestCase from djangojs.utils import StorageGlobber from os.path import normpath class StorageGlobberTest(TestCase): def test_no_js_file(self): '''Should handle empty js file list''' self.assertEqual(StorageGlobber.glob(), []) def test_single_js_file(self): ''...
0.669529
0.40251
import unittest class CaseLetters(unittest.TestCase): def testA(self): self.assertEquals("A" + "A", "AA") def testB(self): self.assertEquals("B" + "B", "BB") def testC(self): self.assertEquals("C" + "C", "CC") def testD(self): self.assertEquals("D" + "D", "DD") def testE(self): self.assertEquals("E...
tests/suites.py
import unittest class CaseLetters(unittest.TestCase): def testA(self): self.assertEquals("A" + "A", "AA") def testB(self): self.assertEquals("B" + "B", "BB") def testC(self): self.assertEquals("C" + "C", "CC") def testD(self): self.assertEquals("D" + "D", "DD") def testE(self): self.assertEquals("E...
0.545528
0.511717
import random import apiai import json import cv2 import os import speech_recognition as sr def recognize_face(): while True: ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, ...
main.py
import random import apiai import json import cv2 import os import speech_recognition as sr def recognize_face(): while True: ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, ...
0.295027
0.21893
import json import logging import pytest from lifemonitor.api import models from tests import utils from tests.conftest_types import ClientAuthenticationMethod logger = logging.getLogger() @pytest.mark.parametrize("client_auth_method", [ # ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.API...
tests/integration/api/controllers/test_registries.py
import json import logging import pytest from lifemonitor.api import models from tests import utils from tests.conftest_types import ClientAuthenticationMethod logger = logging.getLogger() @pytest.mark.parametrize("client_auth_method", [ # ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.API...
0.549641
0.226848
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under th...
core/data_generator.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under th...
0.956543
0.662401
import pymysql.cursors; class DB_Users: def __init__(self, connection): self._connection = connection; self._createTable(); def _setData(self, serverID, accountID, data, dataType): try: with self._connection.cursor() as cursor: sql = "update `Users` set `{0}...
cogs/utils/DB_Users.py
import pymysql.cursors; class DB_Users: def __init__(self, connection): self._connection = connection; self._createTable(); def _setData(self, serverID, accountID, data, dataType): try: with self._connection.cursor() as cursor: sql = "update `Users` set `{0}...
0.299208
0.191007
import time from pathlib import Path import json import superannotate as sa from .test_assign_images import safe_create_project def test_add_bbox(tmpdir): tmpdir = Path(tmpdir) PROJECT_NAME = "Example Project test annotation add" PROJECT_DESCRIPTION = "test vector" PATH_TO_SAMPLE_PROJECT = Path("./t...
tests/test_annotation_adding.py
import time from pathlib import Path import json import superannotate as sa from .test_assign_images import safe_create_project def test_add_bbox(tmpdir): tmpdir = Path(tmpdir) PROJECT_NAME = "Example Project test annotation add" PROJECT_DESCRIPTION = "test vector" PATH_TO_SAMPLE_PROJECT = Path("./t...
0.312685
0.326057
from records_mover.db.redshift.redshift_db_driver import RedshiftDBDriver from records_mover.records.records_format import DelimitedRecordsFormat import unittest from mock import patch, MagicMock, Mock def fake_text(s): return (s,) class TestRedshiftDBDriverFormatNegotiation(unittest.TestCase): @patch('reco...
tests/unit/db/redshift/test_redshift_db_driver_format_negotiation.py
from records_mover.db.redshift.redshift_db_driver import RedshiftDBDriver from records_mover.records.records_format import DelimitedRecordsFormat import unittest from mock import patch, MagicMock, Mock def fake_text(s): return (s,) class TestRedshiftDBDriverFormatNegotiation(unittest.TestCase): @patch('reco...
0.619701
0.134747
This sample code demonstrates how to: - load text data into python using pandas module - preprocess textual categorical features - build decision tree using training data - predict scores over novel test data """ # Loading requisite libraries import sys import os import re import pandas as pd import numpy as np import...
MachineLearning/DTREE_NAIVE_BAYES/Q1/dtree_data_code/decision_tree.py
This sample code demonstrates how to: - load text data into python using pandas module - preprocess textual categorical features - build decision tree using training data - predict scores over novel test data """ # Loading requisite libraries import sys import os import re import pandas as pd import numpy as np import...
0.583915
0.653597
from aocpuzzle import AoCPuzzle class SignalEntry: def __init__(self, signal_pattern: str, four_digits: str) -> None: self.signal_pattern = signal_pattern.split() self.four_digits = four_digits.split() self.digits: list[set[str]] = [set()] * 10 self.build_digits() def build_d...
src/years/2021/08/solution.py
from aocpuzzle import AoCPuzzle class SignalEntry: def __init__(self, signal_pattern: str, four_digits: str) -> None: self.signal_pattern = signal_pattern.split() self.four_digits = four_digits.split() self.digits: list[set[str]] = [set()] * 10 self.build_digits() def build_d...
0.586523
0.529628
from models import base_model from flask_pymongo import ObjectId from werkzeug.exceptions import NotFound from jsonmerge import merge import datetime class TravelModel: def __init__(self): self.travel = base_model.mongo.db.travel self.user = base_model.mongo.db.user def transform(self, travel)...
app/models/travel_model.py
from models import base_model from flask_pymongo import ObjectId from werkzeug.exceptions import NotFound from jsonmerge import merge import datetime class TravelModel: def __init__(self): self.travel = base_model.mongo.db.travel self.user = base_model.mongo.db.user def transform(self, travel)...
0.449393
0.123128
from abc import ABCMeta, abstractmethod from typing import Optional class Money(float, metaclass=ABCMeta): """ Handles amounts of money by subclassing float. In general it's a very bad idea to store amounts of money as floats as all kind of funny things can happen. But as openpyxl parses currency cell...
pydantic_xlsx/types.py
from abc import ABCMeta, abstractmethod from typing import Optional class Money(float, metaclass=ABCMeta): """ Handles amounts of money by subclassing float. In general it's a very bad idea to store amounts of money as floats as all kind of funny things can happen. But as openpyxl parses currency cell...
0.935898
0.899431
# 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 of t...
badge_generator/generate_latex.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 of t...
0.462473
0.093927
import copy import falcon import json import os import shutil import subprocess import sys import traceback from datetime import datetime, timedelta from sqlalchemy import func, desc from sqlalchemy.exc import SQLAlchemyError import model import endpoint import util from db import engine, session from util import User...
app.py
import copy import falcon import json import os import shutil import subprocess import sys import traceback from datetime import datetime, timedelta from sqlalchemy import func, desc from sqlalchemy.exc import SQLAlchemyError import model import endpoint import util from db import engine, session from util import User...
0.164081
0.052716
class Node: def __init__(self,value): self.info = value self.link = None class SingleLinked: def __init__(self): self.start = None list = SingleLinked() def insertAtBeg(value): if list.start == None: list.start = Node(value) #list.start.link = None else: ...
LinkedList/SingleLinkedListInsert.py
class Node: def __init__(self,value): self.info = value self.link = None class SingleLinked: def __init__(self): self.start = None list = SingleLinked() def insertAtBeg(value): if list.start == None: list.start = Node(value) #list.start.link = None else: ...
0.391406
0.237963
import os import tempfile import time from math import exp import graphviz import networkx as nx from sppl.spe import AtomicLeaf from sppl.spe import NominalLeaf from sppl.spe import ProductSPE from sppl.spe import RealLeaf from sppl.spe import SumSPE gensym = lambda: 'r%s' % (str(time.time()).replace('.', ''),) ...
magics/render.py
import os import tempfile import time from math import exp import graphviz import networkx as nx from sppl.spe import AtomicLeaf from sppl.spe import NominalLeaf from sppl.spe import ProductSPE from sppl.spe import RealLeaf from sppl.spe import SumSPE gensym = lambda: 'r%s' % (str(time.time()).replace('.', ''),) ...
0.450843
0.286113
from gen.int_compute_class_gen import IntegerComputationClassGenerator from tests.util import read_file, assert_runs_to_completion def test_int_comp(tmp_path): int_gen = IntegerComputationClassGenerator("IntComp", 3, 3) int_gen.serialize(tmp_path) actual_output = read_file(tmp_path, "IntComp.som").strip(...
tests/test_int_compute.py
from gen.int_compute_class_gen import IntegerComputationClassGenerator from tests.util import read_file, assert_runs_to_completion def test_int_comp(tmp_path): int_gen = IntegerComputationClassGenerator("IntComp", 3, 3) int_gen.serialize(tmp_path) actual_output = read_file(tmp_path, "IntComp.som").strip(...
0.571169
0.463687
import numpy as np import os import pandas as pd import psycopg2 import time from dotenv import ( find_dotenv, load_dotenv ) from pathlib import Path from sqlalchemy import create_engine class Backend(object): def __init__(self, use_docker_host=True): load_dotenv(find_dotenv()) self.pg_use...
plmdata/backend.py
import numpy as np import os import pandas as pd import psycopg2 import time from dotenv import ( find_dotenv, load_dotenv ) from pathlib import Path from sqlalchemy import create_engine class Backend(object): def __init__(self, use_docker_host=True): load_dotenv(find_dotenv()) self.pg_use...
0.402744
0.102529
from django.db import migrations, models from hexbytes import HexBytes from gnosis.safe.safe_signature import ( SafeSignature, SafeSignatureApprovedHash, SafeSignatureType, ) def add_signature_type(apps, schema_editor): MultisigConfirmation = apps.get_model("history", "MultisigConfirmation") Mu...
safe_transaction_service/history/migrations/0016_multisigconfirmation_signature_type.py
from django.db import migrations, models from hexbytes import HexBytes from gnosis.safe.safe_signature import ( SafeSignature, SafeSignatureApprovedHash, SafeSignatureType, ) def add_signature_type(apps, schema_editor): MultisigConfirmation = apps.get_model("history", "MultisigConfirmation") Mu...
0.48121
0.19163
import collections import inspect from abc import ABC, abstractmethod from typing import Callable, Optional, Dict, List, Any import attrs from databutler.datana.generic.corpus.code import DatanaFunction from databutler.datana.generic.corpus.processing.base_processor import DatanaFunctionProcessor from databutler.pat ...
databutler/datana/generic/corpus/processing/keyword_normalization.py
import collections import inspect from abc import ABC, abstractmethod from typing import Callable, Optional, Dict, List, Any import attrs from databutler.datana.generic.corpus.code import DatanaFunction from databutler.datana.generic.corpus.processing.base_processor import DatanaFunctionProcessor from databutler.pat ...
0.826782
0.280974
from typing import Any, Generic, List, Optional, Tuple, TypeVar, cast import numpy as np import torch from torch import nn from mlprogram.actions import ActionSequence from mlprogram.builtins import Environment from mlprogram.encoders import ActionSequenceEncoder from mlprogram.languages import Parser, Token Code = ...
mlprogram/transforms/action_sequence.py
from typing import Any, Generic, List, Optional, Tuple, TypeVar, cast import numpy as np import torch from torch import nn from mlprogram.actions import ActionSequence from mlprogram.builtins import Environment from mlprogram.encoders import ActionSequenceEncoder from mlprogram.languages import Parser, Token Code = ...
0.922678
0.386648
import sqlite3 class Database(object): def __init__(self): conn = sqlite3.connect('self.db') c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS self(cluster text, cloud " "text, instance text, launch integer, benchmark text)") conn.close() def add(self, ...
resources/cluster/database.py
import sqlite3 class Database(object): def __init__(self): conn = sqlite3.connect('self.db') c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS self(cluster text, cloud " "text, instance text, launch integer, benchmark text)") conn.close() def add(self, ...
0.310067
0.106412
from flask import session from wtforms import Form, StringField, SelectField, BooleanField, SelectMultipleField from wtforms.csrf.session import SessionCSRF from wtforms.validators import input_required, length from wtforms.widgets import CheckboxInput, ListWidget def init_app(app): BaseForm.Meta.csrf_secret = by...
odp/app/forms.py
from flask import session from wtforms import Form, StringField, SelectField, BooleanField, SelectMultipleField from wtforms.csrf.session import SessionCSRF from wtforms.validators import input_required, length from wtforms.widgets import CheckboxInput, ListWidget def init_app(app): BaseForm.Meta.csrf_secret = by...
0.759136
0.152032
from datetime import datetime import pandas as pd import fxsignal import fxcmpy import yaml import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', handlers=[logging.FileHandler("./logs/test_algo.log"), logging.StreamHandler()]) d...
scripts/test_algo.py
from datetime import datetime import pandas as pd import fxsignal import fxcmpy import yaml import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', handlers=[logging.FileHandler("./logs/test_algo.log"), logging.StreamHandler()]) d...
0.436382
0.256448
from dataiku.runnables import Runnable import dataiku import urllib2, sys import requests import json import os import dl_image_toolbox_utils as utils import pandas as pd import constants import time # We deactivate GPU for this script, because all the methods only need to # fetch information about model and do not m...
deeplearning-image-gpu/python-runnables/download-models/runnable.py
from dataiku.runnables import Runnable import dataiku import urllib2, sys import requests import json import os import dl_image_toolbox_utils as utils import pandas as pd import constants import time # We deactivate GPU for this script, because all the methods only need to # fetch information about model and do not m...
0.454472
0.186817
from nectarallocationclient import exceptions from nectarallocationclient.v1 import allocations from nectarallocationclient.tests.unit import utils from nectarallocationclient.tests.unit.v1 import fakes class AllocationsTest(utils.TestCase): def setUp(self): super(AllocationsTest, self).setUp() ...
nectarallocationclient/tests/unit/v1/test_allocations.py
from nectarallocationclient import exceptions from nectarallocationclient.v1 import allocations from nectarallocationclient.tests.unit import utils from nectarallocationclient.tests.unit.v1 import fakes class AllocationsTest(utils.TestCase): def setUp(self): super(AllocationsTest, self).setUp() ...
0.594316
0.254784
from pystac.extensions.item_assets import ItemAssetsExtension from pystac.extensions.view import ViewExtension import unittest import pystac from pystac.cache import CollectionCache from pystac.serialization import ( identify_stac_object, identify_stac_object_type, merge_common_properties, migrate_to_l...
tests/serialization/test_migrate.py
from pystac.extensions.item_assets import ItemAssetsExtension from pystac.extensions.view import ViewExtension import unittest import pystac from pystac.cache import CollectionCache from pystac.serialization import ( identify_stac_object, identify_stac_object_type, merge_common_properties, migrate_to_l...
0.655557
0.256611
from os.path import abspath, dirname, join import configparser # All the configs are in secret.cfg that must be created in prod server when deploying CURRENT_DIR = abspath(dirname(__file__)) configfile = configparser.ConfigParser() configpath = abspath(join(CURRENT_DIR, "secret.cfg")) with open(configpath, "r")...
settings/config.py
from os.path import abspath, dirname, join import configparser # All the configs are in secret.cfg that must be created in prod server when deploying CURRENT_DIR = abspath(dirname(__file__)) configfile = configparser.ConfigParser() configpath = abspath(join(CURRENT_DIR, "secret.cfg")) with open(configpath, "r")...
0.241489
0.068631
import numpy as np import os from scipy.special import softmax import time import shutil import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim from torch.nn.utils import clip_grad_norm_ from ops.dataset import TSNDataSet from ops.models import TSN from ops.transforms import * from opts_cust...
demo_custom.py
import numpy as np import os from scipy.special import softmax import time import shutil import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim from torch.nn.utils import clip_grad_norm_ from ops.dataset import TSNDataSet from ops.models import TSN from ops.transforms import * from opts_cust...
0.543833
0.182863
# Import many helpful packages that we will use import math, random, time, copy, multiprocessing, itertools, sys, PIL import networkx as nx import matplotlib.pyplot as plt import IPython, io, os import numpy as np from urllib.request import urlopen from io import BytesIO # STEP 1.2 # Colab does not have a "video dri...
AI python Neural network/ExampleGameNN.py
# Import many helpful packages that we will use import math, random, time, copy, multiprocessing, itertools, sys, PIL import networkx as nx import matplotlib.pyplot as plt import IPython, io, os import numpy as np from urllib.request import urlopen from io import BytesIO # STEP 1.2 # Colab does not have a "video dri...
0.492188
0.466116
# # 113th Congress as News Commentators on Twitter # # In this project I am answering the following questions: # # * Who are the most active news commentators among senators and congressmen ? # * Which news got the most attention by the politicians ? # * How many news (of 7376) are commentated by democrats and/or re...
analysis/tweeps-US.py
# # 113th Congress as News Commentators on Twitter # # In this project I am answering the following questions: # # * Who are the most active news commentators among senators and congressmen ? # * Which news got the most attention by the politicians ? # * How many news (of 7376) are commentated by democrats and/or re...
0.39222
0.513912
from . import AWSObject, AWSProperty from .validators import * from .constants import * # ------------------------------------------- class WAFPredicate(AWSProperty): """# Predicate - CloudFormationResourceSpecification version: 1.4.0 { "Documentation": "http://docs.aws.amazon.com/AWSCloudFormation/lates...
stubs/waf.py
from . import AWSObject, AWSProperty from .validators import * from .constants import * # ------------------------------------------- class WAFPredicate(AWSProperty): """# Predicate - CloudFormationResourceSpecification version: 1.4.0 { "Documentation": "http://docs.aws.amazon.com/AWSCloudFormation/lates...
0.537041
0.132852
from __future__ import annotations import dataclasses import logging import inspect import pytest import xml.etree.ElementTree as ET from relaton_bib import FormattedString, ContributorRole, \ ContributionInfo, Organization @pytest.fixture def role(): return ContributorRole(type="type", description=[ ...
tests/test_contribution_info.py
from __future__ import annotations import dataclasses import logging import inspect import pytest import xml.etree.ElementTree as ET from relaton_bib import FormattedString, ContributorRole, \ ContributionInfo, Organization @pytest.fixture def role(): return ContributorRole(type="type", description=[ ...
0.773943
0.298319
from dataclasses import dataclass, fields import typing as t from hmalib.models import Label, MatchMessage import hmalib.common.config as config from requests import get, post, put, delete, Response class LabelWithConstraints(Label): _KEY_CONSTRAINT = "KeyConstraint" def __init__(self, value: str): ...
hasher-matcher-actioner/hmalib/common/actioner_models.py
from dataclasses import dataclass, fields import typing as t from hmalib.models import Label, MatchMessage import hmalib.common.config as config from requests import get, post, put, delete, Response class LabelWithConstraints(Label): _KEY_CONSTRAINT = "KeyConstraint" def __init__(self, value: str): ...
0.825027
0.21684
import networkx as nx import numpy as np import torch import graph as gl import random OFFSET_4 = torch.from_numpy(np.array([[-5, 5], [5, 5], [-5, -5], [5, -5]]).astype(np.float32)) OFFSET_9 = torch.from_numpy(np.array([[-10, -10], [0, -10], [10, -10], [-10, 0], [0, 0], [10, 0], ...
ae_datasets/d_creator.py
import networkx as nx import numpy as np import torch import graph as gl import random OFFSET_4 = torch.from_numpy(np.array([[-5, 5], [5, 5], [-5, -5], [5, -5]]).astype(np.float32)) OFFSET_9 = torch.from_numpy(np.array([[-10, -10], [0, -10], [10, -10], [-10, 0], [0, 0], [10, 0], ...
0.633297
0.464537
from module import Module, GIT_HOME from module import ANSI_BOLD, ANSI_ERROR, ANSI_CLEAR, ANSI_SUCCESS from tabulate import tabulate import subprocess CONFIGS = [ '.tmux.conf', ] PROGRAMS = { 'tmux': 'sudo pacman -S --needed tmux', 'xsel': 'sudo pacman -S --needed xsel', 'xclip': 'sudo pacman -S --nee...
setup-arch/tmux.py
from module import Module, GIT_HOME from module import ANSI_BOLD, ANSI_ERROR, ANSI_CLEAR, ANSI_SUCCESS from tabulate import tabulate import subprocess CONFIGS = [ '.tmux.conf', ] PROGRAMS = { 'tmux': 'sudo pacman -S --needed tmux', 'xsel': 'sudo pacman -S --needed xsel', 'xclip': 'sudo pacman -S --nee...
0.278846
0.139016
import paho.mqtt.client as mqtt from config import BROKER import json from utils import euclidean_distance class Communication: """Handles MQTT communication.""" def __init__(self, teamname): self.teamname = teamname self.teammates = [] self.publisher = mqtt.Client(f'{teamname}_publish...
additional_code/communication_new.py
import paho.mqtt.client as mqtt from config import BROKER import json from utils import euclidean_distance class Communication: """Handles MQTT communication.""" def __init__(self, teamname): self.teamname = teamname self.teammates = [] self.publisher = mqtt.Client(f'{teamname}_publish...
0.585338
0.187114
from __future__ import absolute_import, division, print_function, unicode_literals from pants.backend.native.config.environment import (Assembler, CCompiler, CppCompiler, CppToolchain, CToolchain, Linker, Platform) from pants.backend.native.subsystems.binaries.binu...
src/python/pants/backend/native/subsystems/native_toolchain.py
from __future__ import absolute_import, division, print_function, unicode_literals from pants.backend.native.config.environment import (Assembler, CCompiler, CppCompiler, CppToolchain, CToolchain, Linker, Platform) from pants.backend.native.subsystems.binaries.binu...
0.592902
0.077378
from ..conf_file import get_vmpooler_hostname, get_auth_token from ..service import get_vm, list_vm, info_vm, destroy_vm, get_token_info from ..util import pretty_print #=================================================================================================== # Functions: Private #===========================...
vmpooler_client/commands/vm.py
from ..conf_file import get_vmpooler_hostname, get_auth_token from ..service import get_vm, list_vm, info_vm, destroy_vm, get_token_info from ..util import pretty_print #=================================================================================================== # Functions: Private #===========================...
0.729231
0.367724
import sys from os import mkdir from os.path import dirname, abspath, exists import shutil import time BASE_PATH = dirname(dirname(dirname(dirname(abspath(__file__))))) sys.path.append(BASE_PATH) # print(BASE_PATH) from lib import settings from lib.command import SubprocessExecute from lib.logger import l...
bin/logic/make/make_server.py
import sys from os import mkdir from os.path import dirname, abspath, exists import shutil import time BASE_PATH = dirname(dirname(dirname(dirname(abspath(__file__))))) sys.path.append(BASE_PATH) # print(BASE_PATH) from lib import settings from lib.command import SubprocessExecute from lib.logger import l...
0.083783
0.03359
from __future__ import with_statement import os import os.path import re PKG = "django_settings_yaml" VERSION_PY = os.path.join(PKG, "version.py") VERSION_TEMPLATE = """# This file is generated from information obtained via git describe # Distribution tarballs contain a pre-generated copy of this file. __version__ =...
setup.py
from __future__ import with_statement import os import os.path import re PKG = "django_settings_yaml" VERSION_PY = os.path.join(PKG, "version.py") VERSION_TEMPLATE = """# This file is generated from information obtained via git describe # Distribution tarballs contain a pre-generated copy of this file. __version__ =...
0.30013
0.078997
import pytest from gwcloud_python.utils import file_filters from gwcloud_python import FileReference, FileReferenceList @pytest.fixture def png_data(): return FileReferenceList([ FileReference(path='data/dir/test1.png', file_size='1', download_token='test_download_token_1'), FileReference(path='da...
gwcloud_python/utils/tests/test_file_filters.py
import pytest from gwcloud_python.utils import file_filters from gwcloud_python import FileReference, FileReferenceList @pytest.fixture def png_data(): return FileReferenceList([ FileReference(path='data/dir/test1.png', file_size='1', download_token='test_download_token_1'), FileReference(path='da...
0.403214
0.390418
__author__ = 'mnowotka' import os import sys import re import hashlib from optparse import OptionParser import requests import BeautifulSoup #------------------------------------------------------------------------------- PAGE_REGEX = re.compile(r"&lt;&lt;\s?&lt;\s?(?P<current_page>\d+) of (?P<total_pages>\d+)\s?&gt...
sea_cli/sea.py
__author__ = 'mnowotka' import os import sys import re import hashlib from optparse import OptionParser import requests import BeautifulSoup #------------------------------------------------------------------------------- PAGE_REGEX = re.compile(r"&lt;&lt;\s?&lt;\s?(?P<current_page>\d+) of (?P<total_pages>\d+)\s?&gt...
0.165931
0.088387
import pony.orm as pny from Database import db from Database.users import User import datetime import uuid #these are all db tables related to the workflow system class MessageLog(db.Entity): uuid = pny.PrimaryKey(str) status = pny.Required(str) date_submitted = pny.Required(datetime.datetime, precision=6...
Database/workflow.py
import pony.orm as pny from Database import db from Database.users import User import datetime import uuid #these are all db tables related to the workflow system class MessageLog(db.Entity): uuid = pny.PrimaryKey(str) status = pny.Required(str) date_submitted = pny.Required(datetime.datetime, precision=6...
0.395601
0.40028
import csv import pandas as pd from collections import Counter from nltk.tokenize import RegexpTokenizer import time def getFoodIdDf(description, foodIdFilePath="foodData/input_food.csv"): colList = ["sr_description", "fdc_id"] df = pd.read_csv(foodIdFilePath, usecols=colList) tokenizer = RegexpTokenize...
getFoodData.py
import csv import pandas as pd from collections import Counter from nltk.tokenize import RegexpTokenizer import time def getFoodIdDf(description, foodIdFilePath="foodData/input_food.csv"): colList = ["sr_description", "fdc_id"] df = pd.read_csv(foodIdFilePath, usecols=colList) tokenizer = RegexpTokenize...
0.289372
0.192672
from classes.strategy import Strategy def shifted_binary_search(array, target, strategy=Strategy.Iteration): ''' Given an array of numbers that is sorted but shifted by an unknown number of indices in an unknown direction, find and return the first found index of the array where array[index] == target. If...
problems/sorting/shifted_binary_search.py
from classes.strategy import Strategy def shifted_binary_search(array, target, strategy=Strategy.Iteration): ''' Given an array of numbers that is sorted but shifted by an unknown number of indices in an unknown direction, find and return the first found index of the array where array[index] == target. If...
0.768646
0.761738
import matplotlib matplotlib.use('TkAgg') import numpy as np import matplotlib.pyplot as plt import sys,os sys.path.append('/home/msdos/focalplane/plate_control/trunk/petal') import petalcomm import petal import pandas as pd import datetime import time, datetime import pickle import csv from scipy import interpolate im...
start_petal_temp_telemetry.py
import matplotlib matplotlib.use('TkAgg') import numpy as np import matplotlib.pyplot as plt import sys,os sys.path.append('/home/msdos/focalplane/plate_control/trunk/petal') import petalcomm import petal import pandas as pd import datetime import time, datetime import pickle import csv from scipy import interpolate im...
0.08363
0.170715
from argparse import ArgumentTypeError def str_to_str_list(values): if isinstance(values, str): values = (str(v) for v in values.split()) else: values = (str(v) for v in values) return list(values) def str_to_float_list(values): if isinstance(values, str): values = (float(v) ...
aevnmt/hparams/args.py
from argparse import ArgumentTypeError def str_to_str_list(values): if isinstance(values, str): values = (str(v) for v in values.split()) else: values = (str(v) for v in values) return list(values) def str_to_float_list(values): if isinstance(values, str): values = (float(v) ...
0.803598
0.575588
import sys import patchy_san.parameters as params import data_processing.graphs as graphs VERSION_TYPES = ['GLOB_OBJ_PREV', 'META_PREV', 'PROC_OBJ_PREV'] def get_graph(results): """ Builds a graph object from a BoltStatementResult object which is the raw result of a neo4j query. :param results: A Bo...
data_processing/preprocessing.py
import sys import patchy_san.parameters as params import data_processing.graphs as graphs VERSION_TYPES = ['GLOB_OBJ_PREV', 'META_PREV', 'PROC_OBJ_PREV'] def get_graph(results): """ Builds a graph object from a BoltStatementResult object which is the raw result of a neo4j query. :param results: A Bo...
0.534127
0.569853
import time import torch from torch import sqrt as sqrt # [s, px, py, pz, dxy, dyz, dxz, dx2-y2, dz2, S] def get_hop_int(input_params=torch.zeros(13)): # input_params[0]=V_sss, # input_params[1]=V_sps, !!!!!! --> -1 # input_params[2]=V_pps, # input_params[3]=V_ppp, # input_params[4]=V_sds, ...
params_pytorch_spd.py
import time import torch from torch import sqrt as sqrt # [s, px, py, pz, dxy, dyz, dxz, dx2-y2, dz2, S] def get_hop_int(input_params=torch.zeros(13)): # input_params[0]=V_sss, # input_params[1]=V_sps, !!!!!! --> -1 # input_params[2]=V_pps, # input_params[3]=V_ppp, # input_params[4]=V_sds, ...
0.124692
0.373476
import pandas as pd from sklearn.model_selection import train_test_split # Code starts here data = pd.read_csv(path) X = data.drop(['customer.id','paid.back.loan'], axis=1) y = data['paid.back.loan'] X_train,X_test,y_train,y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # Code ends here # -----...
Using-decision-tree-model-to-find-loan-defaulters/code.py
import pandas as pd from sklearn.model_selection import train_test_split # Code starts here data = pd.read_csv(path) X = data.drop(['customer.id','paid.back.loan'], axis=1) y = data['paid.back.loan'] X_train,X_test,y_train,y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # Code ends here # -----...
0.448668
0.445107
import logging import os from oslo_config import cfg from oslo_policy import policy from searchlight.common import policies LOG = logging.getLogger(__name__) policy_file_opts = [ cfg.StrOpt("service_policy_path", default='', help="Base path for policy files. If not specified, " ...
searchlight-6.0.0/searchlight/service_policies.py
import logging import os from oslo_config import cfg from oslo_policy import policy from searchlight.common import policies LOG = logging.getLogger(__name__) policy_file_opts = [ cfg.StrOpt("service_policy_path", default='', help="Base path for policy files. If not specified, " ...
0.299003
0.061087
import matplotlib.pyplot as plt import numpy as np import os import imageio from timeit import timeit from mpl_toolkits import mplot3d import scipy from fractions import Fraction import svd as svd from matplotlib.image import imread from skimage import color from skimage import io from watermarkingliutan import * from ...
katie/SVD_Code_OLD/watermarking/watermarkexperiments.py
import matplotlib.pyplot as plt import numpy as np import os import imageio from timeit import timeit from mpl_toolkits import mplot3d import scipy from fractions import Fraction import svd as svd from matplotlib.image import imread from skimage import color from skimage import io from watermarkingliutan import * from ...
0.461988
0.390999
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
benchmarks/SimResults/_bigLittle_hrrs_splash_tugberk_ml/SystemIPC/EightThreads_barnes/power.py
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
0.72526
0.302893
import tensorflow as tf import numpy as np class TextCNN(object): """ A CNN for text classification. Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. """ def __init__( self, sequence_length, num_classes, vocab_size, embedding_size, filter_sizes, num_...
model.py
import tensorflow as tf import numpy as np class TextCNN(object): """ A CNN for text classification. Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. """ def __init__( self, sequence_length, num_classes, vocab_size, embedding_size, filter_sizes, num_...
0.941251
0.360883
import random from collections import deque import time import torch import numpy as np from torchvision import transforms def process_frame(frame): """ Turn game frame into small, square, grayscale image. """ pipeline = transforms.Compose([ transforms.ToPILImage(), # turn numpy ndarray into...
src/utils.py
import random from collections import deque import time import torch import numpy as np from torchvision import transforms def process_frame(frame): """ Turn game frame into small, square, grayscale image. """ pipeline = transforms.Compose([ transforms.ToPILImage(), # turn numpy ndarray into...
0.677261
0.554048
import logging import secrets from convex_api import KeyPair from .command_base import CommandBase logger = logging.getLogger(__name__) class AccountCreateCommand(CommandBase): def __init__(self, sub_parser=None): super().__init__('create', sub_parser) def create_parser(self, sub_parser): ...
convex_api/tool/command/account_create_command.py
import logging import secrets from convex_api import KeyPair from .command_base import CommandBase logger = logging.getLogger(__name__) class AccountCreateCommand(CommandBase): def __init__(self, sub_parser=None): super().__init__('create', sub_parser) def create_parser(self, sub_parser): ...
0.577495
0.091911
import logging import os import json from logging.handlers import RotatingFileHandler from requests_oauthlib import OAuth2Session import datetime import secret import msal import ssl import kafka_producer logger = logging.getLogger() logger.setLevel('INFO') log_path = 'log_' + os.path.basename(__file__).split('.')[0] ...
doc/api_collection_programs/azure/identity_protection_risk_detections/identity_protection_risk_detections.py
import logging import os import json from logging.handlers import RotatingFileHandler from requests_oauthlib import OAuth2Session import datetime import secret import msal import ssl import kafka_producer logger = logging.getLogger() logger.setLevel('INFO') log_path = 'log_' + os.path.basename(__file__).split('.')[0] ...
0.509276
0.047184
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from swagger_client.api_client import ApiClient class RegistryApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. ...
pythonclient/swagger_client/api/registry_api.py
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from swagger_client.api_client import ApiClient class RegistryApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. ...
0.712532
0.056809
import matplotlib.pyplot as plt from matplotlib import colors import numpy as np import cv2 def plot3d_hsv(img, rgb_img): h, s, v = cv2.split(img) fig = plt.figure() axis = fig.add_subplot(1, 1, 1, projection="3d") pixel_colors = rgb_img.reshape((np.shape(rgb_img)[0] * np.shape(rgb_img)[1], 3)) ...
utils.py
import matplotlib.pyplot as plt from matplotlib import colors import numpy as np import cv2 def plot3d_hsv(img, rgb_img): h, s, v = cv2.split(img) fig = plt.figure() axis = fig.add_subplot(1, 1, 1, projection="3d") pixel_colors = rgb_img.reshape((np.shape(rgb_img)[0] * np.shape(rgb_img)[1], 3)) ...
0.703855
0.487673
import numpy as np # linear algebra import pandas as pd import pickle from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split file = pd.read_excel("../datasets/SportsArticles/features.xlsx") file.dropna() #print(str(file.head())) # Get columns names #print(str(list(file)))...
training/objectivity.py
import numpy as np # linear algebra import pandas as pd import pickle from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split file = pd.read_excel("../datasets/SportsArticles/features.xlsx") file.dropna() #print(str(file.head())) # Get columns names #print(str(list(file)))...
0.319652
0.362151
from smbus2 import SMBus import time # ADS1x15 default i2c address I2C_address = 0x48 # General ADS1x15 family ADC class class ADS1x15: # ADS1x15 register address CONVERSION_REG = 0x00 CONFIG_REG = 0x01 LO_THRESH_REG = 0x02 HI_THRESH_REG = 0x03 # Input multiplexer configuration ...
ADS1x15/ADS1x15.py
from smbus2 import SMBus import time # ADS1x15 default i2c address I2C_address = 0x48 # General ADS1x15 family ADC class class ADS1x15: # ADS1x15 register address CONVERSION_REG = 0x00 CONFIG_REG = 0x01 LO_THRESH_REG = 0x02 HI_THRESH_REG = 0x03 # Input multiplexer configuration ...
0.594904
0.215681
import sys from pathlib import Path from typing import List, Sequence, Union from boltons import setutils from micropy.project.modules import ProjectModule from micropy.stubs import StubManager from micropy.stubs.stubs import DeviceStub class StubsModule(ProjectModule): """Project module for handling Stubs. ...
micropy/project/modules/stubs.py
import sys from pathlib import Path from typing import List, Sequence, Union from boltons import setutils from micropy.project.modules import ProjectModule from micropy.stubs import StubManager from micropy.stubs.stubs import DeviceStub class StubsModule(ProjectModule): """Project module for handling Stubs. ...
0.75037
0.174551
from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle from PhysicsTools.Heppy.physicsobjects.PhysicsObjects import Jet from PhysicsTools.HeppyCore.utils.deltar import * from PhysicsTools.HeppyCore.statistics.counter import Counter, Counters ...
PhysicsTools/Heppy/python/analyzers/objects/METAnalyzer.py
from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle from PhysicsTools.Heppy.physicsobjects.PhysicsObjects import Jet from PhysicsTools.HeppyCore.utils.deltar import * from PhysicsTools.HeppyCore.statistics.counter import Counter, Counters ...
0.331012
0.17037
import numpy as np import os import gzip import urllib.request def extract_data(filename, num_images): with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read(num_images*28*28) data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32) data = (dat...
aix360/datasets/mnist_dataset.py
import numpy as np import os import gzip import urllib.request def extract_data(filename, num_images): with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read(num_images*28*28) data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32) data = (dat...
0.211906
0.321567
import datetime import click from aspen.config.config import Config from aspen.database.connection import ( get_db_uri, init_db, session_scope, SqlAlchemyInterface, ) from aspen.database.models import ( GisaidDumpWorkflow, ProcessedGisaidDump, RawGisaidDump, WorkflowStatusType, ) from ...
src/backend/aspen/workflows/transform_gisaid/save.py
import datetime import click from aspen.config.config import Config from aspen.database.connection import ( get_db_uri, init_db, session_scope, SqlAlchemyInterface, ) from aspen.database.models import ( GisaidDumpWorkflow, ProcessedGisaidDump, RawGisaidDump, WorkflowStatusType, ) from ...
0.363308
0.102036
from collections import namedtuple def setup_puzzle(filename:str) -> tuple: puzzle_input = read_input_file(filename) return get_numbers(puzzle_input[0]), create_boards(puzzle_input[1:]) def read_input_file(filename: str = "input_file.txt") -> list: with open(filename) as input_file: raw_input = ...
2021/day4/puzzles.py
from collections import namedtuple def setup_puzzle(filename:str) -> tuple: puzzle_input = read_input_file(filename) return get_numbers(puzzle_input[0]), create_boards(puzzle_input[1:]) def read_input_file(filename: str = "input_file.txt") -> list: with open(filename) as input_file: raw_input = ...
0.645679
0.471527
import argparse import json import uuid import requests import sys from string import Formatter from errors import UserError, RequestError from request_utils import Requests from environment_utils import Environments class Cli(object): def __init__( self, requests_filename='requests.json', ...
gimme.py
import argparse import json import uuid import requests import sys from string import Formatter from errors import UserError, RequestError from request_utils import Requests from environment_utils import Environments class Cli(object): def __init__( self, requests_filename='requests.json', ...
0.245899
0.086787
import random import time from itertools import product import numpy as np import gym from gym import logger env = gym.make('MountainCarContinuous-v0') POPULATION_SIZE = 10 MAX_POPULATION_SIZE = 100 MUTATION_CHANCE = 0.5 BREEDING_CHANCE = 0.5 CURRENT_AGENTS_COUNT = 0 # Constants got from continuous_mountain_car....
obrigatorias/inteligencia-artificial/Olivetti/Projetos/Rafael_Telles/agent.py
import random import time from itertools import product import numpy as np import gym from gym import logger env = gym.make('MountainCarContinuous-v0') POPULATION_SIZE = 10 MAX_POPULATION_SIZE = 100 MUTATION_CHANCE = 0.5 BREEDING_CHANCE = 0.5 CURRENT_AGENTS_COUNT = 0 # Constants got from continuous_mountain_car....
0.489748
0.311008
import click from starwhale.consts import DEFAULT_DATASET_YAML_NAME, LOCAL_FUSE_JSON_NAME from starwhale.swds.dataset import DataSet from starwhale.swds.store import DataSetLocalStore @click.group("dataset", help="StarWhale DataSet(swds) build/push/convert...") def dataset_cmd() -> None: pass @dataset_cmd.comm...
client/starwhale/cli/dataset.py
import click from starwhale.consts import DEFAULT_DATASET_YAML_NAME, LOCAL_FUSE_JSON_NAME from starwhale.swds.dataset import DataSet from starwhale.swds.store import DataSetLocalStore @click.group("dataset", help="StarWhale DataSet(swds) build/push/convert...") def dataset_cmd() -> None: pass @dataset_cmd.comm...
0.180612
0.176636
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u00a5") buf.write("\u05d7\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\...
src/SqlAnalyzer/parser/SqlLexer.py
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u00a5") buf.write("\u05d7\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\...
0.3027
0.503235
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'EventHubEventSubscriptionDestinationArgs', 'EventSubscriptionFilterArgs', 'WebHookEventSubscriptionDestinationArgs', ] @pulumi.input_type class E...
sdk/python/pulumi_azure_nextgen/eventgrid/v20180101/_inputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'EventHubEventSubscriptionDestinationArgs', 'EventSubscriptionFilterArgs', 'WebHookEventSubscriptionDestinationArgs', ] @pulumi.input_type class E...
0.865934
0.079246
import os import pandas as pd import geopandas as gpd from shapely.geometry import mapping, Point, Polygon import numpy as np import matplotlib.pyplot as plt import sys sys.path.append('../') from load_paths import load_box_paths datapath, projectpath, wdir,exe_dir, git_dir = load_box_paths() datapath = os.path.join(d...
data_processing/ems_populations.py
import os import pandas as pd import geopandas as gpd from shapely.geometry import mapping, Point, Polygon import numpy as np import matplotlib.pyplot as plt import sys sys.path.append('../') from load_paths import load_box_paths datapath, projectpath, wdir,exe_dir, git_dir = load_box_paths() datapath = os.path.join(d...
0.253953
0.348229
import os gettext = lambda s: s DATA_DIR = os.path.dirname(os.path.dirname(__file__)) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.django...
{{cookiecutter.project_slug}}/web/{{cookiecutter.project_slug}}/settings.py
import os gettext = lambda s: s DATA_DIR = os.path.dirname(os.path.dirname(__file__)) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.django...
0.303113
0.061706
from cog import BasePredictor, Input, Path from typing import Iterator import torch import yaml import pathlib import os import yaml from util import get_single_rgb # https://stackoverflow.com/a/6587648/1010653 import tempfile, shutil def create_temporary_copy(src_path): _, tf_suffix = os.path.splitext(src_path) ...
cogrun.py
from cog import BasePredictor, Input, Path from typing import Iterator import torch import yaml import pathlib import os import yaml from util import get_single_rgb # https://stackoverflow.com/a/6587648/1010653 import tempfile, shutil def create_temporary_copy(src_path): _, tf_suffix = os.path.splitext(src_path) ...
0.695855
0.211682
from spikeextractors import RecordingExtractor from spikeextractors import SortingExtractor import json import numpy as np from pathlib import Path from .mdaio import DiskReadMda, readmda, writemda32, writemda64 import os class MdaRecordingExtractor(RecordingExtractor): extractor_name = 'MdaRecordingExtractor' ...
spikeextractors/extractors/mdaextractors/mdaextractors.py
from spikeextractors import RecordingExtractor from spikeextractors import SortingExtractor import json import numpy as np from pathlib import Path from .mdaio import DiskReadMda, readmda, writemda32, writemda64 import os class MdaRecordingExtractor(RecordingExtractor): extractor_name = 'MdaRecordingExtractor' ...
0.526586
0.163079
import datetime from django.test import TestCase from django.test import Client import responses from .models import Post, User class PostTestCase(TestCase): def setUp(self) -> None: self.client = Client(HTTP_AUTHORIZATION="Bearer test") return super().setUp() @responses.activate def t...
freefeeds/tests.py
import datetime from django.test import TestCase from django.test import Client import responses from .models import Post, User class PostTestCase(TestCase): def setUp(self) -> None: self.client = Client(HTTP_AUTHORIZATION="Bearer test") return super().setUp() @responses.activate def t...
0.296756
0.308451
from micolog_plugin import * import logging from model import * from google.appengine.api import users class sys_plugin(Plugin): def __init__(self): Plugin.__init__(self,__file__) self.author="xuming" self.authoruri="http://xuming.net" self.uri="http://xuming.net" self.description="SysPlugin." s...
plugins/sys_plugin/sys_plugin.py
from micolog_plugin import * import logging from model import * from google.appengine.api import users class sys_plugin(Plugin): def __init__(self): Plugin.__init__(self,__file__) self.author="xuming" self.authoruri="http://xuming.net" self.uri="http://xuming.net" self.description="SysPlugin." s...
0.12768
0.038829
import requests class CaiClient: """ The CAI public API """ def __init__(self, user_slug, bot_slug, version_slug, developer_token, bot_client_id, bot_client_secret): """ Args : - user_slug (str) : the user slug of the bot owner on the CAI platform - bot_slug (str) : the bot slug of the ...
dataset_translation/cai_client.py
import requests class CaiClient: """ The CAI public API """ def __init__(self, user_slug, bot_slug, version_slug, developer_token, bot_client_id, bot_client_secret): """ Args : - user_slug (str) : the user slug of the bot owner on the CAI platform - bot_slug (str) : the bot slug of the ...
0.709724
0.228974
import matplotlib.pyplot as plt # plotting from vivarium.plots.simulation_output import plot_variables from vivarium.plots.agents_multigen import plot_agents_multigen from vivarium_multibody.plots.snapshots import format_snapshot_data, plot_snapshots, plot_tags import copy def plot_single( output, var...
bioscrape_cobra/plot.py
import matplotlib.pyplot as plt # plotting from vivarium.plots.simulation_output import plot_variables from vivarium.plots.agents_multigen import plot_agents_multigen from vivarium_multibody.plots.snapshots import format_snapshot_data, plot_snapshots, plot_tags import copy def plot_single( output, var...
0.65368
0.325226
import unittest from app.utils import KMP class KMPTests(unittest.TestCase): def test_string_pattern_matching(self): kmp = KMP() pattern_1 = "abc" dataset_1 = "abbabbabbcbabcaabbababcababa" expected_1 = [11, 20] self.assertListEqual(kmp.search(dataset_1, pattern_1), expec...
tests/utils/kmp_tests.py
import unittest from app.utils import KMP class KMPTests(unittest.TestCase): def test_string_pattern_matching(self): kmp = KMP() pattern_1 = "abc" dataset_1 = "abbabbabbcbabcaabbababcababa" expected_1 = [11, 20] self.assertListEqual(kmp.search(dataset_1, pattern_1), expec...
0.613584
0.669583
class NeuroConfig(object): """Stores datasets, backends and npy arrays in memory when the server is launched. Created once per server execution""" _counter = 0 def __init__(self): NeuroConfig._counter += 1 self._id = NeuroConfig._counter self.entries = { "j0251...
python/neuroglancer/config.py
class NeuroConfig(object): """Stores datasets, backends and npy arrays in memory when the server is launched. Created once per server execution""" _counter = 0 def __init__(self): NeuroConfig._counter += 1 self._id = NeuroConfig._counter self.entries = { "j0251...
0.817137
0.206114
from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import os import copy plt.ion() ...
TransferLearing.py
from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import os import copy plt.ion() ...
0.863852
0.59884
import warnings from typing import Union from torch import nn as nn from torchvision import transforms as TF from vp_suite.utils.models import ScaleToModel, ScaleToTest from vp_suite.base import VPModel, VPDataset from vp_suite.utils.dataset_wrapper import VPDatasetWrapper def check_model_and_data_compat(model: VPMo...
vp_suite/utils/compatibility.py
import warnings from typing import Union from torch import nn as nn from torchvision import transforms as TF from vp_suite.utils.models import ScaleToModel, ScaleToTest from vp_suite.base import VPModel, VPDataset from vp_suite.utils.dataset_wrapper import VPDatasetWrapper def check_model_and_data_compat(model: VPMo...
0.895984
0.516535
import os from os.path import join import pandas as pd import re import argparse class HucDirectory(object): def __init__(self, path, limit_branches=[]): self.dir = path self.name = os.path.basename(path) self.limit_branches = limit_branches self.usgs_dtypes = {'location_id':str...
src/usgs_gage_aggregate.py
import os from os.path import join import pandas as pd import re import argparse class HucDirectory(object): def __init__(self, path, limit_branches=[]): self.dir = path self.name = os.path.basename(path) self.limit_branches = limit_branches self.usgs_dtypes = {'location_id':str...
0.294621
0.159708
from __future__ import print_function import os, sys, time startTime = time.time() sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common'))) import driver, scenario_common, utils, vcoptparse, workload_runner class ReplicaSequence(object): def __init__(self, string): ...
test/scenarios/more_or_less_secondaries.py
from __future__ import print_function import os, sys, time startTime = time.time() sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common'))) import driver, scenario_common, utils, vcoptparse, workload_runner class ReplicaSequence(object): def __init__(self, string): ...
0.419648
0.23001
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def generate_data_ajive_fig2(seed=None, all_components=False): """ Samples the data from AJIVE figure 2. Note here we use rows as observations i.e. data matrices are n x d where n = # observations. Parameter...
jive/ajive_fig2.py
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def generate_data_ajive_fig2(seed=None, all_components=False): """ Samples the data from AJIVE figure 2. Note here we use rows as observations i.e. data matrices are n x d where n = # observations. Parameter...
0.601125
0.64912
from collections import defaultdict import pymysql import os from statsmodels.stats.inter_rater import fleiss_kappa connection = pymysql.connect(host=os.getenv("DB_HOST", "localhost"), user=os.getenv("DB_USER", "root"), password=os.getenv("DB_PASS", ""), ...
src/scripts/dataset/kappa.py
from collections import defaultdict import pymysql import os from statsmodels.stats.inter_rater import fleiss_kappa connection = pymysql.connect(host=os.getenv("DB_HOST", "localhost"), user=os.getenv("DB_USER", "root"), password=os.getenv("DB_PASS", ""), ...
0.341363
0.099908