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 re
from datetime import datetime
from flask import Blueprint
from jwt import PyJWTError
import configs
from app import derive_import_root, add_url_rules_for_blueprint
from application import exception
from application.model.invitation_code import InvitationCode
from application.model.role import Role
from appl... | application/views/user/user.py | import re
from datetime import datetime
from flask import Blueprint
from jwt import PyJWTError
import configs
from app import derive_import_root, add_url_rules_for_blueprint
from application import exception
from application.model.invitation_code import InvitationCode
from application.model.role import Role
from appl... | 0.284874 | 0.065815 |
import os
from datetime import datetime
import logging
import pandas as pd
import pandas.errors as pandas_errors
import pytz
import settings
logger = logging.getLogger(__name__)
def find_csv(csv_filename_prefix: str, target_dir: str = None) -> str:
"""As we specify only the airodump output file prefix, this h... | airo_tasks/watch_airodump_csv.py | import os
from datetime import datetime
import logging
import pandas as pd
import pandas.errors as pandas_errors
import pytz
import settings
logger = logging.getLogger(__name__)
def find_csv(csv_filename_prefix: str, target_dir: str = None) -> str:
"""As we specify only the airodump output file prefix, this h... | 0.497803 | 0.252303 |
import argparse
import numpy as np
import numpy.linalg as sla
def op_selectTopR(vct_input, R):
"""
Returns the Rth greatest elements indices
in input vector and store them in idxs_n.
Here, we're using this function instead of
a complete sorting one, where it's more efficient
than comp... | core_numpy.py | import argparse
import numpy as np
import numpy.linalg as sla
def op_selectTopR(vct_input, R):
"""
Returns the Rth greatest elements indices
in input vector and store them in idxs_n.
Here, we're using this function instead of
a complete sorting one, where it's more efficient
than comp... | 0.722527 | 0.649579 |
import re, pywikibot, os
from bs4 import BeautifulSoup, Tag
#os.chdir(r'projects/cee')
site = pywikibot.Site("lv", "wikipedia")
apiq = '''{
"action": "parse",
"format": "json",
"page": "Diāna Hadžijeva",
"prop": "text|langlinks|categories|links|templates|images|externallinks|sections|revid|displayti... | prose2.py | import re, pywikibot, os
from bs4 import BeautifulSoup, Tag
#os.chdir(r'projects/cee')
site = pywikibot.Site("lv", "wikipedia")
apiq = '''{
"action": "parse",
"format": "json",
"page": "Diāna Hadžijeva",
"prop": "text|langlinks|categories|links|templates|images|externallinks|sections|revid|displayti... | 0.053151 | 0.077938 |
from datetime import datetime
import rdkit
from tckdb.backend.app.models.np_species import NonPhysicalSpecies
timestamp = datetime.timestamp(datetime.utcnow())
formaldehyde_xyz = {'symbols': ('C', 'O', 'H', 'H'),
'isotopes': (12, 16, 1, 1),
'coords': ((-0.0122240982, 0.000180... | tckdb/backend/app/tests/models/test_np_species.py | from datetime import datetime
import rdkit
from tckdb.backend.app.models.np_species import NonPhysicalSpecies
timestamp = datetime.timestamp(datetime.utcnow())
formaldehyde_xyz = {'symbols': ('C', 'O', 'H', 'H'),
'isotopes': (12, 16, 1, 1),
'coords': ((-0.0122240982, 0.000180... | 0.688049 | 0.406509 |
stanCode Breakout Project
Adapted from <NAME>'s Breakout by
<NAME>, <NAME>, <NAME>,
and <NAME>
"""
from campy.graphics.gobjects import GRect
from campy.gui.events.timer import pause
from log_in_page import Log_in_page
from breakoutgraphics import BreakoutGraphics
from campy.gui.events.mouse import onmouseclicked
"""
... | breakout.py | stanCode Breakout Project
Adapted from <NAME>'s Breakout by
<NAME>, <NAME>, <NAME>,
and <NAME>
"""
from campy.graphics.gobjects import GRect
from campy.gui.events.timer import pause
from log_in_page import Log_in_page
from breakoutgraphics import BreakoutGraphics
from campy.gui.events.mouse import onmouseclicked
"""
... | 0.541409 | 0.206654 |
from abc import ABCMeta, abstractmethod
import glob
import os
import tarfile
from tempfile import TemporaryDirectory
import tensorflow as tf
def affine(input_tensor, output_size, bias=True, bias_start=0.0,
input_size=None, scope="affine", sparse_input=False):
"""Add an affine transformation of `input_... | muffnn/core.py | from abc import ABCMeta, abstractmethod
import glob
import os
import tarfile
from tempfile import TemporaryDirectory
import tensorflow as tf
def affine(input_tensor, output_size, bias=True, bias_start=0.0,
input_size=None, scope="affine", sparse_input=False):
"""Add an affine transformation of `input_... | 0.935546 | 0.881564 |
import pytest
from pytest import approx
import numpy
from brachiograph import BrachioGraph
import linedraw
class TestBrachioGraph:
bg = BrachioGraph(virtual=True)
def test_defaults_of_default_bg(self):
assert (self.bg.angle_1, self.bg.angle_2) == (-90, 90)
class TestBiDiBrachioGraph:
bg = Br... | tests/test_brachiograph.py | import pytest
from pytest import approx
import numpy
from brachiograph import BrachioGraph
import linedraw
class TestBrachioGraph:
bg = BrachioGraph(virtual=True)
def test_defaults_of_default_bg(self):
assert (self.bg.angle_1, self.bg.angle_2) == (-90, 90)
class TestBiDiBrachioGraph:
bg = Br... | 0.503418 | 0.428413 |
import os
import sys
import glob
import time
import gc
import logging
import argparse
import multiprocessing as mproc
from functools import partial
import cv2 as cv
import numpy as np
sys.path += [os.path.abspath('.'), os.path.abspath('..')] # Add path to root
from benchmark.utilities.dataset import find_largest_obj... | bm_dataset/crop_dataset_images.py | import os
import sys
import glob
import time
import gc
import logging
import argparse
import multiprocessing as mproc
from functools import partial
import cv2 as cv
import numpy as np
sys.path += [os.path.abspath('.'), os.path.abspath('..')] # Add path to root
from benchmark.utilities.dataset import find_largest_obj... | 0.41561 | 0.198045 |
from ImageUtilities import imageReadRGB, showImageRGB, createImageF
from ImageRegionsUtilities import densityHistogram, colourFeature, meanShift, backProjection,backProjectionImage,regionSize
# Math and iteration
from math import exp
from timeit import itertools
'''
Parameters:
pathToDir ... | ExamplesPython_3.6/Chapter9/CamShift.py | from ImageUtilities import imageReadRGB, showImageRGB, createImageF
from ImageRegionsUtilities import densityHistogram, colourFeature, meanShift, backProjection,backProjectionImage,regionSize
# Math and iteration
from math import exp
from timeit import itertools
'''
Parameters:
pathToDir ... | 0.409221 | 0.523299 |
from shexer.utils.target_elements import determine_original_target_nodes_if_needed
from shexer.model.property import Property
from shexer.utils.uri import remove_corners
from shexer.utils.target_elements import tune_target_classes_if_needed
from shexer.consts import SHAPES_DEFAULT_NAMESPACE
from shexer.utils.log import... | shexer/core/profiling/class_profiler.py | from shexer.utils.target_elements import determine_original_target_nodes_if_needed
from shexer.model.property import Property
from shexer.utils.uri import remove_corners
from shexer.utils.target_elements import tune_target_classes_if_needed
from shexer.consts import SHAPES_DEFAULT_NAMESPACE
from shexer.utils.log import... | 0.301362 | 0.119024 |
import math
from keras import activations, layers, initializers
from keras.utils.generic_utils import register_keras_serializable
from keras.utils.tf_utils import shape_type_conversion
@register_keras_serializable(package='TFVan')
class MLP(layers.Layer):
def __init__(self, ratio, dropout, **kwargs):
supe... | tfvan/mlp.py | import math
from keras import activations, layers, initializers
from keras.utils.generic_utils import register_keras_serializable
from keras.utils.tf_utils import shape_type_conversion
@register_keras_serializable(package='TFVan')
class MLP(layers.Layer):
def __init__(self, ratio, dropout, **kwargs):
supe... | 0.910523 | 0.285901 |
import os
import time
import unittest
from meross_iot.api import MerossHttpClient
EMAIL = os.environ.get('MEROSS_EMAIL')
PASSWORD = os.environ.get('MEROSS_PASSWORD')
class TestHttpMethods(unittest.TestCase):
def setUp(self):
self.client = MerossHttpClient(email=EMAIL, password=PASSWORD)
def test_de... | tests/test_power_plugs.py | import os
import time
import unittest
from meross_iot.api import MerossHttpClient
EMAIL = os.environ.get('MEROSS_EMAIL')
PASSWORD = os.environ.get('MEROSS_PASSWORD')
class TestHttpMethods(unittest.TestCase):
def setUp(self):
self.client = MerossHttpClient(email=EMAIL, password=PASSWORD)
def test_de... | 0.512693 | 0.37711 |
import os.path
import re
def validfilename(filename, fullpath=False, posixchars=False, iso9660=False,
posixlenght=False, msdoslenght=False, lenghterror=False):
r"""
Remove all invalid characters from a file or folder name and check its
validity on Linux, Microsoft Windows, Microsoft MS-... | skio/system.py |
import os.path
import re
def validfilename(filename, fullpath=False, posixchars=False, iso9660=False,
posixlenght=False, msdoslenght=False, lenghterror=False):
r"""
Remove all invalid characters from a file or folder name and check its
validity on Linux, Microsoft Windows, Microsoft MS-... | 0.526586 | 0.2641 |
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from skimage import color
from skimage import img_as_ubyte, img_as_float
from skimage.transform import rescale
from skimage.segmentation import slic
from skimage.future.graph import cut_normalized
from skimage.future.graph import rag_mean_color
f... | image_clustering_2d.py | import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from skimage import color
from skimage import img_as_ubyte, img_as_float
from skimage.transform import rescale
from skimage.segmentation import slic
from skimage.future.graph import cut_normalized
from skimage.future.graph import rag_mean_color
f... | 0.731251 | 0.491456 |
import os
# temporarily redirect config directory to prevent matplotlib importing
# testing that for writeable directory which results in sandbox error in
# certain easy_install versions
os.environ["MPLCONFIGDIR"] = "."
DESCRIPTION = "Somecode Twitter Science and Research Platform"
LONG_DESCRIPTION = """\
SOMECODE is... | setup.py | import os
# temporarily redirect config directory to prevent matplotlib importing
# testing that for writeable directory which results in sandbox error in
# certain easy_install versions
os.environ["MPLCONFIGDIR"] = "."
DESCRIPTION = "Somecode Twitter Science and Research Platform"
LONG_DESCRIPTION = """\
SOMECODE is... | 0.199152 | 0.16455 |
import xlwt
import re
from structure import TABLE, COLUMN, DRIVER
class ReTableDriver(DRIVER):
def parse(self, s):
comment, table_name, columns, engine, charset = "", "None", [], "Default", "Default"
primary_keys, foreign_keys, index_keys, unique_keys = [], [], [], []
# 提取表信息
res ... | src/dbvd.py | import xlwt
import re
from structure import TABLE, COLUMN, DRIVER
class ReTableDriver(DRIVER):
def parse(self, s):
comment, table_name, columns, engine, charset = "", "None", [], "Default", "Default"
primary_keys, foreign_keys, index_keys, unique_keys = [], [], [], []
# 提取表信息
res ... | 0.165189 | 0.095139 |
import os
import sys
sys.path.insert(0, './')
import pickle
import argparse
import numpy as np
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dim', type = int, default = 2,
help = 'the number of dimensions, default = 2')
parser.add_argument('--pts', type = i... | gen_syn.py | import os
import sys
sys.path.insert(0, './')
import pickle
import argparse
import numpy as np
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dim', type = int, default = 2,
help = 'the number of dimensions, default = 2')
parser.add_argument('--pts', type = i... | 0.221519 | 0.13569 |
# Author: <NAME>
# Description: Show Network and According Measurements
import sys, os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
## Parameters
##
config = {
"acolor": "#0336FF",
"bcolor": "#FF0266",
"awcolor": "#6ebeff",
"ca... | NetworkViewer/network.py |
# Author: <NAME>
# Description: Show Network and According Measurements
import sys, os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
## Parameters
##
config = {
"acolor": "#0336FF",
"bcolor": "#FF0266",
"awcolor": "#6ebeff",
"ca... | 0.354545 | 0.221277 |
from datetime import datetime, timedelta, timezone
import pytest
from assertpy import assert_that
from common.utils import time_is_up
from slurm_plugin.common import TIMESTAMP_FORMAT, get_clustermgtd_heartbeat
@pytest.mark.parametrize(
"initial_time, current_time, grace_time, expected_result",
[
(d... | tests/slurm_plugin/test_common.py |
from datetime import datetime, timedelta, timezone
import pytest
from assertpy import assert_that
from common.utils import time_is_up
from slurm_plugin.common import TIMESTAMP_FORMAT, get_clustermgtd_heartbeat
@pytest.mark.parametrize(
"initial_time, current_time, grace_time, expected_result",
[
(d... | 0.763307 | 0.482795 |
from os import stat
from tkinter import *
import tkinter as tk
import serial
import time
from serial.tools.list_ports import comports
import sys
from PIL import Image, ImageTk
import struct
import os
# GUI Parameters
WINDOW_SIZE = "1600x900"
TEXT_COLOR = "white"
BACKGROUND_COLOR = "gray10"
connected = False
validate... | GUI/gui.py | from os import stat
from tkinter import *
import tkinter as tk
import serial
import time
from serial.tools.list_ports import comports
import sys
from PIL import Image, ImageTk
import struct
import os
# GUI Parameters
WINDOW_SIZE = "1600x900"
TEXT_COLOR = "white"
BACKGROUND_COLOR = "gray10"
connected = False
validate... | 0.246896 | 0.143908 |
import xml.etree.ElementTree as ET
import time
import select
from io import StringIO
from threading import Thread, Event, Lock
from os import read
from .coqapi import Ok, Err
from .xmltype import *
class CoqHandler:
def __init__(self, state_manager, printer):
self.printer = printer
self.state_mana... | rplugin/python3/pycoqtop/coqxml.py | import xml.etree.ElementTree as ET
import time
import select
from io import StringIO
from threading import Thread, Event, Lock
from os import read
from .coqapi import Ok, Err
from .xmltype import *
class CoqHandler:
def __init__(self, state_manager, printer):
self.printer = printer
self.state_mana... | 0.189559 | 0.101367 |
import os
import unittest
import mock
from landscaper import paths
from landscaper.utilities import coordinates
class TestCoordinatesJson(unittest.TestCase):
"""
Unit tests for the coordinates json file.
"""
def test_get_coordinates_json_path(self):
"""
Check that the path is availab... | tests/test_coordinates.py | import os
import unittest
import mock
from landscaper import paths
from landscaper.utilities import coordinates
class TestCoordinatesJson(unittest.TestCase):
"""
Unit tests for the coordinates json file.
"""
def test_get_coordinates_json_path(self):
"""
Check that the path is availab... | 0.684475 | 0.541106 |
# pylint: disable=invalid-name,line-too-long
import pytest
import srv_control
import srv_msg
import references
import misc
@pytest.mark.v6
@pytest.mark.options
@pytest.mark.user
def test_v6_options_user_defined_option():
# Testing server ability to configure it with user custom option
# in this case: opt... | tests/dhcpv6/options_validation/test_v6_user_options.py |
# pylint: disable=invalid-name,line-too-long
import pytest
import srv_control
import srv_msg
import references
import misc
@pytest.mark.v6
@pytest.mark.options
@pytest.mark.user
def test_v6_options_user_defined_option():
# Testing server ability to configure it with user custom option
# in this case: opt... | 0.334481 | 0.060696 |
import torch
import pandas as pd
from laylm.trainer import metrics
from laylm.config import label as label_cfg
from laylm.config import token as token_cfg
def annoset_inputs(data_dict, device):
input_ids = torch.tensor(data_dict['token_ids'], dtype=torch.long)
mask = torch.tensor(data_dict['mask'], dtype... | laylm/prod/utils.py | import torch
import pandas as pd
from laylm.trainer import metrics
from laylm.config import label as label_cfg
from laylm.config import token as token_cfg
def annoset_inputs(data_dict, device):
input_ids = torch.tensor(data_dict['token_ids'], dtype=torch.long)
mask = torch.tensor(data_dict['mask'], dtype... | 0.19349 | 0.24844 |
import argparse
import os
import sys
from c64img import __version__ as ver
from c64img.hires import HiresConverter
from c64img.multi import MultiConverter
from c64img.path import get_modified_fname
def convert(arguments, converter_class):
"""
Convert pictures
"""
last = conv = None
exit_code = 0
... | c64img/cmd_convert.py | import argparse
import os
import sys
from c64img import __version__ as ver
from c64img.hires import HiresConverter
from c64img.multi import MultiConverter
from c64img.path import get_modified_fname
def convert(arguments, converter_class):
"""
Convert pictures
"""
last = conv = None
exit_code = 0
... | 0.400163 | 0.239928 |
# imports
import argparse
from utils import Data
from ann import ANN, k_fold_train
def parse_args():
'''parse the arguments for artificial neural network'''
parser = argparse.ArgumentParser(
description='Artificial Neural Network for classification'
)
parser.add_argument(
'-a', '--at... | source/main.py |
# imports
import argparse
from utils import Data
from ann import ANN, k_fold_train
def parse_args():
'''parse the arguments for artificial neural network'''
parser = argparse.ArgumentParser(
description='Artificial Neural Network for classification'
)
parser.add_argument(
'-a', '--at... | 0.450118 | 0.274206 |
from functools import partial
from requests_futures.sessions import FuturesSession
from requests.packages.urllib3.util import Retry
from requests.adapters import HTTPAdapter
from django.conf import settings
from wristband.common.utils import extract_version_from_slug
from wristband.providers import providers_config
f... | wristband/apps/providers.py | from functools import partial
from requests_futures.sessions import FuturesSession
from requests.packages.urllib3.util import Retry
from requests.adapters import HTTPAdapter
from django.conf import settings
from wristband.common.utils import extract_version_from_slug
from wristband.providers import providers_config
f... | 0.487551 | 0.159708 |
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from importlib import import_module
from typing import Any, Iterable, List, Optional, Set
from faust_avro.types import float32, int32
__all__ = [
# Types
"AvroSchemaT",
"VisitedT",
# Classes
"AvroRec... | faust_avro/schema.py | from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from importlib import import_module
from typing import Any, Iterable, List, Optional, Set
from faust_avro.types import float32, int32
__all__ = [
# Types
"AvroSchemaT",
"VisitedT",
# Classes
"AvroRec... | 0.927112 | 0.28799 |
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from argparse import ArgumentParser
from pathlib import Path
THISDIR = Path(__file__).resolve().parent
def main():
"""Main entry point"""
parser = ArgumentParser(add_help=False)
parser.add_argument("-h", "--help"... | blackt/__init__.py |
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from argparse import ArgumentParser
from pathlib import Path
THISDIR = Path(__file__).resolve().parent
def main():
"""Main entry point"""
parser = ArgumentParser(add_help=False)
parser.add_argument("-h", "--help"... | 0.399694 | 0.083778 |
import time
from colorama import Fore, Back, Style, init
import sys
import os
init(autoreset=True)
print(Fore.GREEN+"EMYOUNOONE Tarafından Kodlanmıştır ")
print(Fore.GREEN+"www.siberguvenlikblogu.com ")
input("Şifre Oluşturucu Programına Hoş Geldiniz...\n \nDevam Etmek İçin Enter'e Basınız..\n")
os.system('... | sifre_olusturucu.py | import time
from colorama import Fore, Back, Style, init
import sys
import os
init(autoreset=True)
print(Fore.GREEN+"EMYOUNOONE Tarafından Kodlanmıştır ")
print(Fore.GREEN+"www.siberguvenlikblogu.com ")
input("Şifre Oluşturucu Programına Hoş Geldiniz...\n \nDevam Etmek İçin Enter'e Basınız..\n")
os.system('... | 0.030916 | 0.202325 |
import numpy as np
import LMM as lmm
import matplotlib.pyplot as plt
# validates the LMM forward rate simulations using martingale tests and other
# tests
class Validation():
def __init__(self):
swaption_vol_cva_dataset_path = 'Data/SwaptionVolMatrix_5Y.csv'
swap_curve_cva_dataset_path = 'Data/Spot... | Validation.py | import numpy as np
import LMM as lmm
import matplotlib.pyplot as plt
# validates the LMM forward rate simulations using martingale tests and other
# tests
class Validation():
def __init__(self):
swaption_vol_cva_dataset_path = 'Data/SwaptionVolMatrix_5Y.csv'
swap_curve_cva_dataset_path = 'Data/Spot... | 0.60964 | 0.493714 |
from enum import Enum
from functools import wraps
from typing import List, Optional
from fb4.login_bp import LoginForm
from fb4.widgets import LodTable, Link
from flask import flash, url_for, Blueprint
from flask_login import LoginManager, logout_user, current_user, login_user, login_required, UserMixin
from flask_wtf ... | onlinespreadsheet/loginBlueprint.py | from enum import Enum
from functools import wraps
from typing import List, Optional
from fb4.login_bp import LoginForm
from fb4.widgets import LodTable, Link
from flask import flash, url_for, Blueprint
from flask_login import LoginManager, logout_user, current_user, login_user, login_required, UserMixin
from flask_wtf ... | 0.639624 | 0.067026 |
from netforce.model import Model, fields, get_model
from netforce.access import get_active_user, set_active_user
from datetime import *
from dateutil.relativedelta import relativedelta
import time
from netforce.database import get_connection
from netforce.access import get_active_company, check_permission_other
from n... | netforce_service/netforce_service/models/job.py |
from netforce.model import Model, fields, get_model
from netforce.access import get_active_user, set_active_user
from datetime import *
from dateutil.relativedelta import relativedelta
import time
from netforce.database import get_connection
from netforce.access import get_active_company, check_permission_other
from n... | 0.550607 | 0.295351 |
from __future__ import absolute_import
from nose.tools import *
from payoneer_escrow_sdk.authenticator import Authenticator
def setup():
pass
def teardown():
pass
def test_secure_headers():
"""
Verify that secure_headers has the right keys and (certain) values.
We will test the value of the r... | tests/authenticator_tests.py | from __future__ import absolute_import
from nose.tools import *
from payoneer_escrow_sdk.authenticator import Authenticator
def setup():
pass
def teardown():
pass
def test_secure_headers():
"""
Verify that secure_headers has the right keys and (certain) values.
We will test the value of the r... | 0.771413 | 0.555616 |
import settings
import caffe
import numpy as np
import numpy as np
import math, random
import sys, subprocess
from IPython.display import clear_output, Image, display
from scipy.misc import imresize
from numpy.linalg import norm
from numpy.testing import assert_array_equal
import scipy.misc, scipy.io
import patchShow
... | nsfw.py | import settings
import caffe
import numpy as np
import numpy as np
import math, random
import sys, subprocess
from IPython.display import clear_output, Image, display
from scipy.misc import imresize
from numpy.linalg import norm
from numpy.testing import assert_array_equal
import scipy.misc, scipy.io
import patchShow
... | 0.454956 | 0.304623 |
import discord
import asyncio
from arxivpy.arxiv import Arxiv
import json
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
client = discord.Client()
try:
with open(os.path.join(dir_path, "read_papers.json"), "rb") as f:
papers = json.load(f)
except:
papers = {}
try:
with open(os.p... | bot.py | import discord
import asyncio
from arxivpy.arxiv import Arxiv
import json
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
client = discord.Client()
try:
with open(os.path.join(dir_path, "read_papers.json"), "rb") as f:
papers = json.load(f)
except:
papers = {}
try:
with open(os.p... | 0.341802 | 0.118003 |
import sys
import os
import importlib
import ConfigParser
import cea.config
import cea.datamanagement.copy_default_databases
__author__ = "<NAME>"
__copyright__ = "Copyright 2017, Architecture and Building Systems - ETH Zurich"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
... | cea/interfaces/cli/cli.py | import sys
import os
import importlib
import ConfigParser
import cea.config
import cea.datamanagement.copy_default_databases
__author__ = "<NAME>"
__copyright__ = "Copyright 2017, Architecture and Building Systems - ETH Zurich"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
... | 0.216094 | 0.07117 |
import sqlite3
from flask import Flask, render_template, g, redirect, url_for, request, session, flash
DATABASE = 'test.db'
USERNAME = 'admin'
PASSWORD = '<PASSWORD>'
SECRET_KEY = 'this is secret!'
CURRENT_ID = 0
app = Flask(__name__)
app.config.from_object(__name__)
@app.route('/')
def welcome():
return '<h1>Welco... | todolist.py | import sqlite3
from flask import Flask, render_template, g, redirect, url_for, request, session, flash
DATABASE = 'test.db'
USERNAME = 'admin'
PASSWORD = '<PASSWORD>'
SECRET_KEY = 'this is secret!'
CURRENT_ID = 0
app = Flask(__name__)
app.config.from_object(__name__)
@app.route('/')
def welcome():
return '<h1>Welco... | 0.134037 | 0.043224 |
import tempfile
from pathlib import PosixPath
import pyarrow.parquet as pq
import yaml
from cloudpathlib import AnyPath, CloudPath
from cachetools import cached, TTLCache
def get_local_file(file_location):
if isinstance(file_location, PosixPath):
return file_location.as_posix()
elif isinstance(file_... | packages/cardpay-reward-programs/cardpay_reward_programs/utils.py | import tempfile
from pathlib import PosixPath
import pyarrow.parquet as pq
import yaml
from cloudpathlib import AnyPath, CloudPath
from cachetools import cached, TTLCache
def get_local_file(file_location):
if isinstance(file_location, PosixPath):
return file_location.as_posix()
elif isinstance(file_... | 0.316053 | 0.12603 |
import numpy as np
import pandas as pd
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
# Output:
# 0 1.0
# 1 3.0
# 2 5.0
# 3 NaN
# 4 6.0
# 5 8.0
# dtype: float64
dates = pd.date_range('20210506', periods=6)
print(dates)
# Output:
# DatetimeIndex(['2021-05-06', '2021-05-07', '2021-05-08', '2021-05-09... | Pandas/intro.py | import numpy as np
import pandas as pd
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
# Output:
# 0 1.0
# 1 3.0
# 2 5.0
# 3 NaN
# 4 6.0
# 5 8.0
# dtype: float64
dates = pd.date_range('20210506', periods=6)
print(dates)
# Output:
# DatetimeIndex(['2021-05-06', '2021-05-07', '2021-05-08', '2021-05-09... | 0.382372 | 0.319652 |
import pandas as pd
import matplotlib.pyplot as plt
"""# Data Exploration
**Challenge**: How many different colours does the LEGO company produce? Read the colors.csv file in the data folder and find the total number of unique colours. Try using the [.nunique() method](https://pandas.pydata.org/pandas-docs/stable/ref... | Day-073/main.py | import pandas as pd
import matplotlib.pyplot as plt
"""# Data Exploration
**Challenge**: How many different colours does the LEGO company produce? Read the colors.csv file in the data folder and find the total number of unique colours. Try using the [.nunique() method](https://pandas.pydata.org/pandas-docs/stable/ref... | 0.752104 | 0.742025 |
import json
import pandas as pd
import logging
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from localsecret import username, password
from spiceup_labels.config_lizard import patch_labeltype, configure_logger
#%%
def create_lizardrastersource(code, uuid):
key = code
valu... | spiceup_labels/patch_weather_startup_labeltype.py | import json
import pandas as pd
import logging
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from localsecret import username, password
from spiceup_labels.config_lizard import patch_labeltype, configure_logger
#%%
def create_lizardrastersource(code, uuid):
key = code
valu... | 0.398992 | 0.157428 |
from AdjacencyMatrixGraphNode import AdjacencyMatrixGraphNode
class AdjacencyMatrixGraph:
def __init__(self) -> None:
self.matrix = []
self.nodes = []
def adjacent(self, nodeA, nodeB):
i = nodeA.index
j = nodeB.index
if self.matrix[i][j] or self.matrix[j][i]:
... | DataStructures/Graphs/AdjacencyMatrixGraph/AdjacencyMatrixGraph.py | from AdjacencyMatrixGraphNode import AdjacencyMatrixGraphNode
class AdjacencyMatrixGraph:
def __init__(self) -> None:
self.matrix = []
self.nodes = []
def adjacent(self, nodeA, nodeB):
i = nodeA.index
j = nodeB.index
if self.matrix[i][j] or self.matrix[j][i]:
... | 0.586878 | 0.471102 |
if __name__ == "__main__":
from MKVCreator import PrimaryFrame
PrimaryFrame()
from tkinter import Tk, ttk
from Processor import Processor
from Processor.Processor import Props
from Utils.LogUtils import Log
from Utils import UIUtils as UI
class PrimaryFrame:
def __init__ ( self ):
... | MKVRipper/MKVCreator.py | if __name__ == "__main__":
from MKVCreator import PrimaryFrame
PrimaryFrame()
from tkinter import Tk, ttk
from Processor import Processor
from Processor.Processor import Props
from Utils.LogUtils import Log
from Utils import UIUtils as UI
class PrimaryFrame:
def __init__ ( self ):
... | 0.255344 | 0.131118 |
import os
import shutil
import h5py
import numpy as np
import pytest
import yaml
TEST_FILES = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'resources',
)
VOXEL_SIZE = (0.235, 0.15, 0.15)
# common fixtures aimed to reduce the boilerplate in tests
@pytest.fixture
def input_path(tmpdir):
pat... | tests/conftest.py | import os
import shutil
import h5py
import numpy as np
import pytest
import yaml
TEST_FILES = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'resources',
)
VOXEL_SIZE = (0.235, 0.15, 0.15)
# common fixtures aimed to reduce the boilerplate in tests
@pytest.fixture
def input_path(tmpdir):
pat... | 0.326701 | 0.244679 |
import os
from plenum.common.log import getlogger
from sovrin.agent.agent import createAgent, runAgent
from sovrin.agent.constants import EVENT_NOTIFY_MSG
from sovrin.agent.exception import NonceNotFound
from sovrin.client.client import Client
from sovrin.client.wallet.wallet import Wallet
from sovrin.common.config_u... | sovrin/test/agent/thrift.py | import os
from plenum.common.log import getlogger
from sovrin.agent.agent import createAgent, runAgent
from sovrin.agent.constants import EVENT_NOTIFY_MSG
from sovrin.agent.exception import NonceNotFound
from sovrin.client.client import Client
from sovrin.client.wallet.wallet import Wallet
from sovrin.common.config_u... | 0.367838 | 0.141193 |
from catalyst import dl
from catalyst.contrib.data.nlp import LanguageModelingDataset
from catalyst.core import MetricAggregationCallback
import pandas as pd
import pytest # noqa: F401
import torch
from torch.utils.data import DataLoader
from transformers import (
AutoConfig,
AutoTokenizer,
BertForMaskedLM... | src/test.py | from catalyst import dl
from catalyst.contrib.data.nlp import LanguageModelingDataset
from catalyst.core import MetricAggregationCallback
import pandas as pd
import pytest # noqa: F401
import torch
from torch.utils.data import DataLoader
from transformers import (
AutoConfig,
AutoTokenizer,
BertForMaskedLM... | 0.821939 | 0.346099 |
from utils.generate import generate_data
import starry
import numpy as np
import matplotlib.pyplot as plt
import os
# Settings
ydeg = 15
smoothing = 0
# Array of inclinations
incs = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
veq = 60000.0 # m/s
# Plot the true map
fig, ax = plt.subplots(4, 3, figsize=(15, 10))... | src/figures/inclinations.py | from utils.generate import generate_data
import starry
import numpy as np
import matplotlib.pyplot as plt
import os
# Settings
ydeg = 15
smoothing = 0
# Array of inclinations
incs = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
veq = 60000.0 # m/s
# Plot the true map
fig, ax = plt.subplots(4, 3, figsize=(15, 10))... | 0.627609 | 0.356951 |
import logging
import time
import datetime
import random
import weaved
# BEGIN Configuration
# Weaved related configuration
PLUG_IP = '192.168.1.201' # Assumes the Smart Plug is configured for SSH and IR blaster
PLUG_USER = 'root' # Assumes password-less (key based) SSH authentication is set up
# ... | noburglar.py | import logging
import time
import datetime
import random
import weaved
# BEGIN Configuration
# Weaved related configuration
PLUG_IP = '192.168.1.201' # Assumes the Smart Plug is configured for SSH and IR blaster
PLUG_USER = 'root' # Assumes password-less (key based) SSH authentication is set up
# ... | 0.381911 | 0.161386 |
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from PIL import Image
class create_data():
"""create_data.py: Converts all of the .wav files into spectrograms"""
@staticmethod
def create_spectrograms():
"""Creates spectrograms from all of the... | create_spectrograms.py | import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from PIL import Image
class create_data():
"""create_data.py: Converts all of the .wav files into spectrograms"""
@staticmethod
def create_spectrograms():
"""Creates spectrograms from all of the... | 0.431345 | 0.431345 |
from antlr4 import *
if __name__ is not None and "." in __name__:
from .SABParser import SABParser
else:
from SABParser import SABParser
# This class defines a complete listener for a parse tree produced by SABParser.
class SABListener(ParseTreeListener):
# Enter a parse tree produced by SABParser#s.
... | SABListener.py | from antlr4 import *
if __name__ is not None and "." in __name__:
from .SABParser import SABParser
else:
from SABParser import SABParser
# This class defines a complete listener for a parse tree produced by SABParser.
class SABListener(ParseTreeListener):
# Enter a parse tree produced by SABParser#s.
... | 0.390708 | 0.05175 |
from flask.app import Flask
from sqlalchemy.sql.schema import ForeignKey
from .db import db, ma
from datetime import datetime as datetime2
from sqlalchemy.orm import relationship,backref
from .default_method_result import DefaultMethodResult
from sqlalchemy.dialects.postgresql import JSON, UUID
from sqlalchemy.sql.exp... | request-management-api/request_api/models/FOIRequestComments.py | from flask.app import Flask
from sqlalchemy.sql.schema import ForeignKey
from .db import db, ma
from datetime import datetime as datetime2
from sqlalchemy.orm import relationship,backref
from .default_method_result import DefaultMethodResult
from sqlalchemy.dialects.postgresql import JSON, UUID
from sqlalchemy.sql.exp... | 0.395835 | 0.05328 |
import urwid
from console.ui.images.pane import ImagePane
from console.ui.containers.pane import ContainerPane
from console.widgets.tabs import Tab, TabFrame
from console.modes import modemap
class ImagesTab(Tab):
label = "images"
mode = {
'ctrl n': ('next-image', 'set focus on the next image'),
... | console/ui/layout.py | import urwid
from console.ui.images.pane import ImagePane
from console.ui.containers.pane import ContainerPane
from console.widgets.tabs import Tab, TabFrame
from console.modes import modemap
class ImagesTab(Tab):
label = "images"
mode = {
'ctrl n': ('next-image', 'set focus on the next image'),
... | 0.467089 | 0.223144 |
import unittest
# internal distend imports
from distend import serializer
class TestSerializer(unittest.TestCase):
def test_get_replace_function(self):
"""test serializer.get_replace_function,
returns replace_multiple function
"""
replace_multiple_true = True
replace_multi... | tests/test_serializer.py | import unittest
# internal distend imports
from distend import serializer
class TestSerializer(unittest.TestCase):
def test_get_replace_function(self):
"""test serializer.get_replace_function,
returns replace_multiple function
"""
replace_multiple_true = True
replace_multi... | 0.643889 | 0.292734 |
from discord.ext.commands.errors import BadArgument, MissingRequiredArgument, CommandNotFound
import asyncio
class EventRegistry:
def __init__(self, instance):
self.instance = instance
self.add_handler(self._on_message_process_commands, 1000, event_name="on_message")
self.add_handler(sel... | src/bot/events.py | from discord.ext.commands.errors import BadArgument, MissingRequiredArgument, CommandNotFound
import asyncio
class EventRegistry:
def __init__(self, instance):
self.instance = instance
self.add_handler(self._on_message_process_commands, 1000, event_name="on_message")
self.add_handler(sel... | 0.510985 | 0.061989 |
import sys
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtCore import Qt, QRect
class Cardinal(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(280, 170, 600, 600)
self.scale = 3
self.offset_X = 0
... | core/cardinal.py | import sys
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtCore import Qt, QRect
class Cardinal(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(280, 170, 600, 600)
self.scale = 3
self.offset_X = 0
... | 0.443841 | 0.254657 |
import hashlib
import base64
from Crypto import Random
from Crypto.Cipher import AES
from lib.crypt import crypt
from Crypto.Cipher import Blowfish
class AESCipher:
def __init__(self, key, src_filepath, dst_filepath):
self.src_filepath = src_filepath
self.dst_filepath = dst_filepath
self.... | algorithms.py | import hashlib
import base64
from Crypto import Random
from Crypto.Cipher import AES
from lib.crypt import crypt
from Crypto.Cipher import Blowfish
class AESCipher:
def __init__(self, key, src_filepath, dst_filepath):
self.src_filepath = src_filepath
self.dst_filepath = dst_filepath
self.... | 0.591605 | 0.162181 |
import torch
import torch.nn.functional as F
import dgl
from dgl.nn import GraphConv, AvgPooling, MaxPooling
from utils import topk, get_batch_id
class SAGPool(torch.nn.Module):
"""The Self-Attention Pooling layer in paper
`Self Attention Graph Pooling <https://arxiv.org/pdf/1904.08082.pdf>`
Args:
... | examples/pytorch/sagpool/layer.py | import torch
import torch.nn.functional as F
import dgl
from dgl.nn import GraphConv, AvgPooling, MaxPooling
from utils import topk, get_batch_id
class SAGPool(torch.nn.Module):
"""The Self-Attention Pooling layer in paper
`Self Attention Graph Pooling <https://arxiv.org/pdf/1904.08082.pdf>`
Args:
... | 0.963239 | 0.649745 |
from hypothesis import given
from tests.utils import (KeysView,
KeysViewsPair,
KeysViewsTriplet,
is_left_subtree_less_than_right_subtree,
to_height,
to_max_binary_tree_height,
... | tests/views_tests/keys_view_tests/test_intersect.py | from hypothesis import given
from tests.utils import (KeysView,
KeysViewsPair,
KeysViewsTriplet,
is_left_subtree_less_than_right_subtree,
to_height,
to_max_binary_tree_height,
... | 0.875335 | 0.696359 |
import argparse
import pathlib
import random
import sys
import time
import cv2 as cv
import numpy as np
import pandas as pd
from xgboost import XGBClassifier
from matplotlib import colors
filename2class = {}
filename2class["n"] = "background"
filename2class["y"] = "yellow"
filename2class["r"] = "red"
filename2class[... | scripts/train_xgb_tree.py | import argparse
import pathlib
import random
import sys
import time
import cv2 as cv
import numpy as np
import pandas as pd
from xgboost import XGBClassifier
from matplotlib import colors
filename2class = {}
filename2class["n"] = "background"
filename2class["y"] = "yellow"
filename2class["r"] = "red"
filename2class[... | 0.501221 | 0.279583 |
import numpy
from openfermioncirq.optimization import (
OptimizationParams,
OptimizationResult,
OptimizationTrialResult)
from openfermioncirq.testing import ExampleAlgorithm
def test_optimization_result_init():
result = OptimizationResult(
optimal_value=0.339,
opt... | openfermioncirq/optimization/result_test.py |
import numpy
from openfermioncirq.optimization import (
OptimizationParams,
OptimizationResult,
OptimizationTrialResult)
from openfermioncirq.testing import ExampleAlgorithm
def test_optimization_result_init():
result = OptimizationResult(
optimal_value=0.339,
opt... | 0.698432 | 0.608536 |
import logging
# logging.basicConfig(format='%(message)s', level=logging.INFO)
DEBUG_SUCCESS_NUM = 1001
DEBUG_FAILED_NUM = 1002
logging.addLevelName(DEBUG_SUCCESS_NUM, "SUCCESS")
logging.addLevelName(DEBUG_FAILED_NUM, "FAILED")
def debug_success(self, message, *args, **kws):
if self.isEnabledFor(DEBUG_SUCCESS_NU... | toolbox/utils/Log.py | import logging
# logging.basicConfig(format='%(message)s', level=logging.INFO)
DEBUG_SUCCESS_NUM = 1001
DEBUG_FAILED_NUM = 1002
logging.addLevelName(DEBUG_SUCCESS_NUM, "SUCCESS")
logging.addLevelName(DEBUG_FAILED_NUM, "FAILED")
def debug_success(self, message, *args, **kws):
if self.isEnabledFor(DEBUG_SUCCESS_NU... | 0.447702 | 0.091707 |
import numpy as np
from fusion_engine_client.analysis.file_reader import FileReader, MessageData, TimeAlignmentMode
from fusion_engine_client.messages import *
def setup():
data = {
PoseMessage.MESSAGE_TYPE: MessageData(PoseMessage.MESSAGE_TYPE, None),
PoseAuxMessage.MESSAGE_TYPE: MessageData(Pos... | python/tests/test_file_reader.py | import numpy as np
from fusion_engine_client.analysis.file_reader import FileReader, MessageData, TimeAlignmentMode
from fusion_engine_client.messages import *
def setup():
data = {
PoseMessage.MESSAGE_TYPE: MessageData(PoseMessage.MESSAGE_TYPE, None),
PoseAuxMessage.MESSAGE_TYPE: MessageData(Pos... | 0.501953 | 0.418103 |
from __future__ import absolute_import, unicode_literals
import logging
import os.path
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
import polib
from .util import app_name_from_filepath
logger = logging... | mobetta/models.py | from __future__ import absolute_import, unicode_literals
import logging
import os.path
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
import polib
from .util import app_name_from_filepath
logger = logging... | 0.657868 | 0.08163 |
from ..snescpu.addressing import get_addressing_mode
from ..snescpu.disasm import disassemble
from ..snescpu.instructions import get_instruction
from ..snescpu.states import (DisassembleState, DumpState)
# A dictionary of subroutines with following bytes as arguments.
# key: the address of subroutine
# value: the corr... | dqutils/dq3/disasm.py | from ..snescpu.addressing import get_addressing_mode
from ..snescpu.disasm import disassemble
from ..snescpu.instructions import get_instruction
from ..snescpu.states import (DisassembleState, DumpState)
# A dictionary of subroutines with following bytes as arguments.
# key: the address of subroutine
# value: the corr... | 0.333612 | 0.552479 |
import copy
import os
import pytest
import salt.utils.files
from tests.support.mock import patch
def test_safe_rm():
with patch("os.remove") as os_remove_mock:
salt.utils.files.safe_rm("dummy_tgt")
assert os_remove_mock.called is True
def test_safe_rm_exceptions(tmp_path):
assert (
... | tests/pytests/unit/utils/test_files.py | import copy
import os
import pytest
import salt.utils.files
from tests.support.mock import patch
def test_safe_rm():
with patch("os.remove") as os_remove_mock:
salt.utils.files.safe_rm("dummy_tgt")
assert os_remove_mock.called is True
def test_safe_rm_exceptions(tmp_path):
assert (
... | 0.384565 | 0.424591 |
import io
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from pytoshop import codecs
from pytoshop import enums
@pytest.mark.parametrize("depth", (8, 16))
def test_zip_with_prediction(depth):
np.random.seed(0)
dtype = codecs.color_depth_dtype_map[depth]
x = np.random.... | tests/test_codecs.py |
import io
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from pytoshop import codecs
from pytoshop import enums
@pytest.mark.parametrize("depth", (8, 16))
def test_zip_with_prediction(depth):
np.random.seed(0)
dtype = codecs.color_depth_dtype_map[depth]
x = np.random.... | 0.598195 | 0.742865 |
import numpy as np
from ._base_network import _baseNetwork
class SoftmaxRegression(_baseNetwork):
def __init__(self, input_size=28*28, num_classes=10):
'''
A single layer softmax regression. The network is composed by:
a linear layer without bias => (optional ReLU activation) => Softmax
... | hw1 Two-layer-network/models/softmax_regression.py | import numpy as np
from ._base_network import _baseNetwork
class SoftmaxRegression(_baseNetwork):
def __init__(self, input_size=28*28, num_classes=10):
'''
A single layer softmax regression. The network is composed by:
a linear layer without bias => (optional ReLU activation) => Softmax
... | 0.883488 | 0.498901 |
import numpy as np
import pandas as pd
import pytest
from pydicom import dcmread
from dicom_csv.spatial import (
get_orientation_matrix,
get_image_position_patient,
get_slice_locations,
get_image_plane,
Plane,
_get_slices_deltas,
get_pixel_spacing,
get_image_size,
order_series
)
@... | tests/test_spatial.py | import numpy as np
import pandas as pd
import pytest
from pydicom import dcmread
from dicom_csv.spatial import (
get_orientation_matrix,
get_image_position_patient,
get_slice_locations,
get_image_plane,
Plane,
_get_slices_deltas,
get_pixel_spacing,
get_image_size,
order_series
)
@... | 0.275519 | 0.541348 |
from numpy import loadtxt, degrees, arcsin, arctan2, sort, unique, ones, zeros_like, array
from mpl_toolkits.basemap import Basemap
import reverse_geocoder as rg
import randomcolor
def domino(lol):
# Takes a list (length n) of lists (length 2)
# and returns a list of indices order,
# such that lol[order[i]... | helpers.py | from numpy import loadtxt, degrees, arcsin, arctan2, sort, unique, ones, zeros_like, array
from mpl_toolkits.basemap import Basemap
import reverse_geocoder as rg
import randomcolor
def domino(lol):
# Takes a list (length n) of lists (length 2)
# and returns a list of indices order,
# such that lol[order[i]... | 0.375134 | 0.447641 |
import json
import requests
# Constants for base profile URL's.
# Might be worth adding config for this,
# but as this is only used here and none
# of this is sensitive, no need for now
BASE_URL = 'https://hl7.org/fhir/'
BASE_FILE_TYPE = '.profile.json'
# Again, only need a cache here, slightly more cohesive and woul... | src/lib/base_definitions.py | import json
import requests
# Constants for base profile URL's.
# Might be worth adding config for this,
# but as this is only used here and none
# of this is sensitive, no need for now
BASE_URL = 'https://hl7.org/fhir/'
BASE_FILE_TYPE = '.profile.json'
# Again, only need a cache here, slightly more cohesive and woul... | 0.206334 | 0.121503 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('product', '0009_review_product_created_at'),
('account', '0001_initial'),
migrations.swappable_dependen... | Project/checkout/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('product', '0009_review_product_created_at'),
('account', '0001_initial'),
migrations.swappable_dependen... | 0.541894 | 0.149656 |
from absl.testing import absltest
from absl.testing import parameterized
import haiku as hk
import numpy as np
from hierarchical_transformer_memory.hierarchical_attention import htm_attention
def _build_queries_and_memory(query_length, num_memories, mem_chunk_size,
batch_size=2, embedd... | hierarchical_transformer_memory/hierarchical_attention/htm_attention_test.py | from absl.testing import absltest
from absl.testing import parameterized
import haiku as hk
import numpy as np
from hierarchical_transformer_memory.hierarchical_attention import htm_attention
def _build_queries_and_memory(query_length, num_memories, mem_chunk_size,
batch_size=2, embedd... | 0.831554 | 0.514095 |
from PIL import Image, ImageFilter, ImageDraw, ImageFont # image manipulation
import os # For dir making
import secrets # For Handling FileExisting Error
import cv2
import numpy
class ImageHandler:
def __init__(self, _image_file:str) -> None:
self._image_file = _image_file
self._image_file_extensio... | src/EasyFileHandling/imagehandler.py | from PIL import Image, ImageFilter, ImageDraw, ImageFont # image manipulation
import os # For dir making
import secrets # For Handling FileExisting Error
import cv2
import numpy
class ImageHandler:
def __init__(self, _image_file:str) -> None:
self._image_file = _image_file
self._image_file_extensio... | 0.383295 | 0.140071 |
import logging
import numpy as np
import hypothesis.strategies as hst
from hypothesis import HealthCheck, given, example, settings
from qcodes.dataset.measurements import Measurement
@given(n_points=hst.integers(min_value=1, max_value=100))
@example(n_points=5)
@settings(deadline=None, suppress_health_check=(Health... | qcodes/tests/dataset/measurement/test_shapes.py | import logging
import numpy as np
import hypothesis.strategies as hst
from hypothesis import HealthCheck, given, example, settings
from qcodes.dataset.measurements import Measurement
@given(n_points=hst.integers(min_value=1, max_value=100))
@example(n_points=5)
@settings(deadline=None, suppress_health_check=(Health... | 0.620737 | 0.478163 |
import copy
import tempfile
from pathlib import Path
from typing import Optional, List, Tuple, Set, Dict
import numpy as np
from joblib import Memory
from sklearn.base import BaseEstimator, TransformerMixin
from python.handwritten_baseline.pipeline.data.base import Dataset
from python.handwritten_baseline.pipeline.mo... | python/handwritten_baseline/pipeline/model/feature_extr/base_mixin.py | import copy
import tempfile
from pathlib import Path
from typing import Optional, List, Tuple, Set, Dict
import numpy as np
from joblib import Memory
from sklearn.base import BaseEstimator, TransformerMixin
from python.handwritten_baseline.pipeline.data.base import Dataset
from python.handwritten_baseline.pipeline.mo... | 0.827061 | 0.527864 |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List
from nuplan.planning.metrics.metric_result import MetricStatistics
@dataclass
class MetricFileKey:
metric_name: str
scenario_name: str
scenario_type: str
planner_name: str
def seriali... | nuplan/planning/metrics/metric_file.py | from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List
from nuplan.planning.metrics.metric_result import MetricStatistics
@dataclass
class MetricFileKey:
metric_name: str
scenario_name: str
scenario_type: str
planner_name: str
def seriali... | 0.93196 | 0.231256 |
import glob
import json
import os
from setuptools import find_packages
from setuptools import setup
# python3 setup.py register -r pypitest
# UNIX:
# rm -rf ./dist
# python3 setup.py sdist bdist_wheel
# twine upload dist/measure*
# python3 conda-recipe/conda-builder.py
# WINDOWS:
# rmdir dist /s /q
# python setup.p... | setup.py | import glob
import json
import os
from setuptools import find_packages
from setuptools import setup
# python3 setup.py register -r pypitest
# UNIX:
# rm -rf ./dist
# python3 setup.py sdist bdist_wheel
# twine upload dist/measure*
# python3 conda-recipe/conda-builder.py
# WINDOWS:
# rmdir dist /s /q
# python setup.p... | 0.438304 | 0.122025 |
from django.conf import settings
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordResetForm
from allauth.account.forms import EmailAwarePasswordResetTokenGenerator
from allauth.account.models import EmailAddress
from allauth.account.utils import user_pk_to_url_str
... | server/apps/authentication/serializers.py | from django.conf import settings
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordResetForm
from allauth.account.forms import EmailAwarePasswordResetTokenGenerator
from allauth.account.models import EmailAddress
from allauth.account.utils import user_pk_to_url_str
... | 0.60964 | 0.099383 |
from db_works import db_connect, db_tables
import datetime
def get_settings(interval_param_):
db_schema_name, db_table_name, db_settings_table_name = db_tables()
cursor, cnxn = db_connect()
# interval parameter: current - API data; daily_hist - data from daily files; monthly_hist - data from monthly fil... | stock_dwh_functions.py |
from db_works import db_connect, db_tables
import datetime
def get_settings(interval_param_):
db_schema_name, db_table_name, db_settings_table_name = db_tables()
cursor, cnxn = db_connect()
# interval parameter: current - API data; daily_hist - data from daily files; monthly_hist - data from monthly fil... | 0.199191 | 0.250311 |
from unittest import TestCase
from chibi.snippet.xml import guaranteed_list, compress_dummy_list
class test_guaranteed_list(TestCase):
def setUp( self ):
self.example = {
'args': 'nmap -oX - -sn 172.16.58.3/24',
'debugging': {'level': '0'},
'host': {
'... | tests/snippet/xml.py | from unittest import TestCase
from chibi.snippet.xml import guaranteed_list, compress_dummy_list
class test_guaranteed_list(TestCase):
def setUp( self ):
self.example = {
'args': 'nmap -oX - -sn 172.16.58.3/24',
'debugging': {'level': '0'},
'host': {
'... | 0.487063 | 0.305386 |
import httplib2
import json
import random
import requests
import string
from functools import wraps
from database_setup import Base, Category, Item, User
from flask import (Flask,
flash,
jsonify,
make_response,
render_template,
... | item-catalog/project.py | import httplib2
import json
import random
import requests
import string
from functools import wraps
from database_setup import Base, Category, Item, User
from flask import (Flask,
flash,
jsonify,
make_response,
render_template,
... | 0.438184 | 0.079032 |
import numpy as np
import matplotlib.pyplot as plt
class Error(Exception):
pass
class InitializationError(Error):
def __init__(self, message):
self.message = message
class SierpinskiTriangle(object):
"""
Reference http://bopace.github.io/python/2016/06/09/python-turtle-sierp... | pyfractals/sierpinski_triangle.py | import numpy as np
import matplotlib.pyplot as plt
class Error(Exception):
pass
class InitializationError(Error):
def __init__(self, message):
self.message = message
class SierpinskiTriangle(object):
"""
Reference http://bopace.github.io/python/2016/06/09/python-turtle-sierp... | 0.574753 | 0.325869 |
def dem_from_bbox(bbox, crs=3857, resolution=2048, path=None):
"""
:param bbox: bounding box as [xmin,ymin,xmax,ymax]
:param crs: crs for bounding box
:param path: As an option, save to a local filepath with extension .tif
:return: DEM image
"""
import requests
from pyproj import Trans... | pyvf/dems.py | def dem_from_bbox(bbox, crs=3857, resolution=2048, path=None):
"""
:param bbox: bounding box as [xmin,ymin,xmax,ymax]
:param crs: crs for bounding box
:param path: As an option, save to a local filepath with extension .tif
:return: DEM image
"""
import requests
from pyproj import Trans... | 0.706798 | 0.571288 |
from django.http import JsonResponse
from ..models import Project, ModelClass, DefaultAttribute
import json
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from pprint import pprint
import pathlib
import os
@csrf_exempt
@require_POST
def create_or_update_mode... | website/backend/webserver/api/views/model_classes.py | from django.http import JsonResponse
from ..models import Project, ModelClass, DefaultAttribute
import json
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from pprint import pprint
import pathlib
import os
@csrf_exempt
@require_POST
def create_or_update_mode... | 0.227041 | 0.08043 |
import random
number = random.randrange(0,101)
print(number)
#2 завдання
numb = int(input("Введіть рандомне число від 0 до 10: "))
numb2 = random.randrange(0,11)
print("Випадає число: " ,numb2)
if numb == numb2:
print("Ти вийграв!!!")
else:
print("Ти програв =(")
#3 завдання
pryclad = 100 - 50
print(pryclad)
... | classwork11.py | import random
number = random.randrange(0,101)
print(number)
#2 завдання
numb = int(input("Введіть рандомне число від 0 до 10: "))
numb2 = random.randrange(0,11)
print("Випадає число: " ,numb2)
if numb == numb2:
print("Ти вийграв!!!")
else:
print("Ти програв =(")
#3 завдання
pryclad = 100 - 50
print(pryclad)
... | 0.195479 | 0.389198 |
import os
import autoprocess.errors
from autoprocess.parsers import distl
from autoprocess.utils import log, misc, programs, xdsio
_logger = log.get_module_logger(__name__)
def harvest_initialize():
if misc.file_requirements('X-CORRECTIONS.cbf', 'Y-CORRECTIONS.cbf', 'BKGINIT.cbf', 'BLANK.cbf', 'GAIN.cbf'):
... | autoprocess/engine/spots.py | import os
import autoprocess.errors
from autoprocess.parsers import distl
from autoprocess.utils import log, misc, programs, xdsio
_logger = log.get_module_logger(__name__)
def harvest_initialize():
if misc.file_requirements('X-CORRECTIONS.cbf', 'Y-CORRECTIONS.cbf', 'BKGINIT.cbf', 'BLANK.cbf', 'GAIN.cbf'):
... | 0.278747 | 0.078997 |
from sims4.tuning.tunable import HasTunableSingletonFactory, AutoFactoryInit
from sims4.tuning.tunable_base import GroupNames
import services, sims4.tuning.tunable
class AllCompletionType(HasTunableSingletonFactory, AutoFactoryInit):
FACTORY_TUNABLES = {'description': '\n All of the Objectives as part o... | Scripts/simulation/event_testing/milestone.py | from sims4.tuning.tunable import HasTunableSingletonFactory, AutoFactoryInit
from sims4.tuning.tunable_base import GroupNames
import services, sims4.tuning.tunable
class AllCompletionType(HasTunableSingletonFactory, AutoFactoryInit):
FACTORY_TUNABLES = {'description': '\n All of the Objectives as part o... | 0.588889 | 0.493714 |
import pyexasol
import _config as config
import multiprocessing
import pyexasol.callback as cb
import pandas
import pprint
printer = pprint.PrettyPrinter(indent=4, width=140)
class ImportProc(multiprocessing.Process):
def __init__(self, node):
self.node = node
self.read_pipe, self.write_pipe = ... | examples/b04_parallel_import.py | import pyexasol
import _config as config
import multiprocessing
import pyexasol.callback as cb
import pandas
import pprint
printer = pprint.PrettyPrinter(indent=4, width=140)
class ImportProc(multiprocessing.Process):
def __init__(self, node):
self.node = node
self.read_pipe, self.write_pipe = ... | 0.422147 | 0.08389 |
import pandas as pd
import matplotlib.pyplot as plt
from pandas.core.frame import DataFrame
from alphax.src.api.base import BaseAPI, TimeSeriesAPI, TechIndicatorsAPI
from copy import copy, deepcopy
class MACD:
""" Return the moving average convergence/divergence time series in two
json objects as data and meta... | alphax/src/tools/indicator/macd.py | import pandas as pd
import matplotlib.pyplot as plt
from pandas.core.frame import DataFrame
from alphax.src.api.base import BaseAPI, TimeSeriesAPI, TechIndicatorsAPI
from copy import copy, deepcopy
class MACD:
""" Return the moving average convergence/divergence time series in two
json objects as data and meta... | 0.852199 | 0.469155 |
import torchvision.transforms as transforms
from typing import Callable
from .norm import normalize
from .utils import MultiCropTransform
from .mocov2 import MocoTransform
__all__ = ['ressl_transform']
class ReSSLTransform(MocoTransform):
def large(self, split: str = 'train', norm: str = 'imagenet') -> Callabl... | sslic/data/transforms/ressl.py | import torchvision.transforms as transforms
from typing import Callable
from .norm import normalize
from .utils import MultiCropTransform
from .mocov2 import MocoTransform
__all__ = ['ressl_transform']
class ReSSLTransform(MocoTransform):
def large(self, split: str = 'train', norm: str = 'imagenet') -> Callabl... | 0.861538 | 0.507507 |
from . import Reaction
class Enzyme:
"""
The enzyme class has a few components:
* The subunit(s) that make up the enzyme
* The genes that encode those subunit(s)
* The reactions that this enzyme is connected to.
:ivar name: the name of the enzyme object
:type name: str
:ivar rol... | PyFBA/metabolism/enzyme.py | from . import Reaction
class Enzyme:
"""
The enzyme class has a few components:
* The subunit(s) that make up the enzyme
* The genes that encode those subunit(s)
* The reactions that this enzyme is connected to.
:ivar name: the name of the enzyme object
:type name: str
:ivar rol... | 0.824144 | 0.665546 |
from wiserHeatingAPI import wiserHub
import json
import sys
dev="false" # set to true to see raw data
# Get Wiser Parameters from keyfile
try:
with open('wiserkeys.params', 'r') as f:
data = f.read().split('\n')
except FileNotFoundError as e:
print("{}, {}/{}".format(e.strerror, 'wiserkeys.params', key... | systemstatus.py | from wiserHeatingAPI import wiserHub
import json
import sys
dev="false" # set to true to see raw data
# Get Wiser Parameters from keyfile
try:
with open('wiserkeys.params', 'r') as f:
data = f.read().split('\n')
except FileNotFoundError as e:
print("{}, {}/{}".format(e.strerror, 'wiserkeys.params', key... | 0.145996 | 0.072472 |
import numpy as np
import PointwiseFunctions.AnalyticSolutions.Hydro.SmoothFlow as hydro
import Evolution.Systems.NewtonianEuler.TimeDerivative as flux
def soln_error(face_mesh_velocity, outward_directed_normal_covector, coords,
time, dim):
return None
_soln_pressure = 1.0
_soln_adiabatic_index... | tests/Unit/Evolution/Systems/NewtonianEuler/BoundaryConditions/DirichletAnalytic.py |
import numpy as np
import PointwiseFunctions.AnalyticSolutions.Hydro.SmoothFlow as hydro
import Evolution.Systems.NewtonianEuler.TimeDerivative as flux
def soln_error(face_mesh_velocity, outward_directed_normal_covector, coords,
time, dim):
return None
_soln_pressure = 1.0
_soln_adiabatic_index... | 0.734596 | 0.369116 |
import torch
from torch import nn
import torch.nn.functional as F
import os
import numpy as np
from utility import *
import pandas as pd
from kornia.filters import filter2D
import imageio
import math
from collections import OrderedDict
import random
def save_models(gs, ds, location):
folder = create_folder("Saved... | TestModels/SinGAN_model.py | import torch
from torch import nn
import torch.nn.functional as F
import os
import numpy as np
from utility import *
import pandas as pd
from kornia.filters import filter2D
import imageio
import math
from collections import OrderedDict
import random
def save_models(gs, ds, location):
folder = create_folder("Saved... | 0.526586 | 0.371507 |
import gitFunctions
import actions
from termcolor import colored
path = "../data/paths.txt"
def print_all_paths():
try:
with open(path) as file:
for line in file:
print(line, end="")
except Exception as e:
print(e)
def close_app():
pass
def print_help():
... | pythonGitManager/comands.py | import gitFunctions
import actions
from termcolor import colored
path = "../data/paths.txt"
def print_all_paths():
try:
with open(path) as file:
for line in file:
print(line, end="")
except Exception as e:
print(e)
def close_app():
pass
def print_help():
... | 0.081182 | 0.126246 |
import os,unittest
import pandas as pd
from igf_data.illumina.samplesheet import SampleSheet
from igf_data.utils.fileutils import get_temp_dir,remove_dir
from igf_data.utils.samplesheet_utils import get_formatted_samplesheet_per_lane
from igf_data.utils.samplesheet_utils import samplesheet_validation_and_metadata_check... | test/utils/samplesheet_utils_test.py | import os,unittest
import pandas as pd
from igf_data.illumina.samplesheet import SampleSheet
from igf_data.utils.fileutils import get_temp_dir,remove_dir
from igf_data.utils.samplesheet_utils import get_formatted_samplesheet_per_lane
from igf_data.utils.samplesheet_utils import samplesheet_validation_and_metadata_check... | 0.106848 | 0.293354 |
from datetime import datetime
from . import db
from .relations import UserFeatures
from .mixins import GenericMixin, NameMixin
class Role(db.Model, GenericMixin, NameMixin):
'''User roles table'''
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), un... | requester/database/models.py | from datetime import datetime
from . import db
from .relations import UserFeatures
from .mixins import GenericMixin, NameMixin
class Role(db.Model, GenericMixin, NameMixin):
'''User roles table'''
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), un... | 0.770896 | 0.058696 |
import numpy
from tomo2D import phantom2D
from tomo2D import ellipse
import random
pi=numpy.pi
sin=numpy.sin
cos=numpy.cos
sqrt=numpy.sqrt
def bar_object():
ph=phantom2D()
e=ellipse(0.,0.,1.0,5.0,0.5,0.)
ph.add_component(e)
e=ellipse(0.1,0.,.5,.05,0.1,0.4)
ph.add_component(e)
e=ellipse(-0.5,-0.... | largescale_code/phantoms_tomo2D.py | import numpy
from tomo2D import phantom2D
from tomo2D import ellipse
import random
pi=numpy.pi
sin=numpy.sin
cos=numpy.cos
sqrt=numpy.sqrt
def bar_object():
ph=phantom2D()
e=ellipse(0.,0.,1.0,5.0,0.5,0.)
ph.add_component(e)
e=ellipse(0.1,0.,.5,.05,0.1,0.4)
ph.add_component(e)
e=ellipse(-0.5,-0.... | 0.299515 | 0.331877 |