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, urlparse
from lib import helpers
from urlresolver import common
from urlresolver.resolver import UrlResolver, ResolverError
class StreamplayResolver(UrlResolver):
name = "streamplay"
domains = ["streamplay.to", "streamplay.club"]
pattern = '(?://|\.)(streamplay\.(?:to|club))/(?:embed-|player-)?(... | script.module.urlresolver/lib/urlresolver/plugins/streamplay.py | import re, urlparse
from lib import helpers
from urlresolver import common
from urlresolver.resolver import UrlResolver, ResolverError
class StreamplayResolver(UrlResolver):
name = "streamplay"
domains = ["streamplay.to", "streamplay.club"]
pattern = '(?://|\.)(streamplay\.(?:to|club))/(?:embed-|player-)?(... | 0.219505 | 0.15704 |
import pandas as pd
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
import matplotlib.pyplot as plt
i... | other_methode.py | import pandas as pd
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
import matplotlib.pyplot as plt
i... | 0.484624 | 0.554893 |
import os
import unittest
from fix_path import fix_sys_path
fix_sys_path(__file__)
from storage import Storage
from cache import CacheInRam, CacheOnDisk, Cache
from gluon.dal import DAL, Field
oldcwd = None
def setUpModule():
global oldcwd
if oldcwd is None:
oldcwd = os.getcwd()
if not os.... | gluon/tests/test_cache.py | import os
import unittest
from fix_path import fix_sys_path
fix_sys_path(__file__)
from storage import Storage
from cache import CacheInRam, CacheOnDisk, Cache
from gluon.dal import DAL, Field
oldcwd = None
def setUpModule():
global oldcwd
if oldcwd is None:
oldcwd = os.getcwd()
if not os.... | 0.18352 | 0.250609 |
import numpy as np
import paddle
import re
from .abc_interpreter import Interpreter
from ..data_processor.readers import preprocess_inputs, preprocess_save_path
from ..data_processor.visualizer import explanation_to_vis, show_vis_explanation, save_image
class TAMInterpreter(Interpreter):
"""
Transition Atten... | interpretdl/interpreter/transition_attention_maps.py | import numpy as np
import paddle
import re
from .abc_interpreter import Interpreter
from ..data_processor.readers import preprocess_inputs, preprocess_save_path
from ..data_processor.visualizer import explanation_to_vis, show_vis_explanation, save_image
class TAMInterpreter(Interpreter):
"""
Transition Atten... | 0.848628 | 0.489076 |
import argparse
import ray
from ray import tune
from ray.rllib.examples.env.stateless_cartpole import StatelessCartPole
from ray.rllib.examples.models.trajectory_view_utilizing_models import \
FrameStackingCartPoleModel, TorchFrameStackingCartPoleModel
from ray.rllib.models.catalog import ModelCatalog
from ray.rll... | rllib/examples/trajectory_view_api.py | import argparse
import ray
from ray import tune
from ray.rllib.examples.env.stateless_cartpole import StatelessCartPole
from ray.rllib.examples.models.trajectory_view_utilizing_models import \
FrameStackingCartPoleModel, TorchFrameStackingCartPoleModel
from ray.rllib.models.catalog import ModelCatalog
from ray.rll... | 0.72594 | 0.247342 |
import time
class Logger:
def __init__(self, print_steps, writer=None):
"""Notice: 需要显式的关闭writer. `writer.close()`"""
self.writer = writer
self.print_steps = print_steps
self.steps_each_epoch = None
# ----------------
self.epoch = None
self.lr = None
... | utils/tools/logger.py | import time
class Logger:
def __init__(self, print_steps, writer=None):
"""Notice: 需要显式的关闭writer. `writer.close()`"""
self.writer = writer
self.print_steps = print_steps
self.steps_each_epoch = None
# ----------------
self.epoch = None
self.lr = None
... | 0.600188 | 0.235416 |
import os
from abc import abstractmethod
from enum import Enum
from typing import List, Optional, Union
from ordered_set import OrderedSet
ELEMENT_ATTRIBUTE_PREFIX = "}ELEMENTATTRIBUTES_"
class Order(Enum):
ASC = 1
DESC = 2
BASC = 3
BDESC = 4
def __str__(self):
return self.name
@cl... | mdxpy/mdx.py | import os
from abc import abstractmethod
from enum import Enum
from typing import List, Optional, Union
from ordered_set import OrderedSet
ELEMENT_ATTRIBUTE_PREFIX = "}ELEMENTATTRIBUTES_"
class Order(Enum):
ASC = 1
DESC = 2
BASC = 3
BDESC = 4
def __str__(self):
return self.name
@cl... | 0.832815 | 0.246692 |
import numpy as np
import matplotlib.pyplot as plt
import monai
def preview_image(image_array, normalize_by="volume", cmap=None, figsize=(12, 12), threshold=None):
"""
Display three orthogonal slices of the given 3D image.
image_array is assumed to be of shape (H,W,D)
If a number is provided for thr... | deep_atlas/utils.py | import numpy as np
import matplotlib.pyplot as plt
import monai
def preview_image(image_array, normalize_by="volume", cmap=None, figsize=(12, 12), threshold=None):
"""
Display three orthogonal slices of the given 3D image.
image_array is assumed to be of shape (H,W,D)
If a number is provided for thr... | 0.861072 | 0.78572 |
from gi.repository import Gtk, Gdk, GdkPixbuf
from modules import _global as glob,models
from designs import search
import gi
gi.require_version('Gtk', '3.0')
class ToolBar(Gtk.Toolbar):
def __init__(self):
Gtk.Toolbar.__init__(self)
# =>back & forward buttons for get back & next words searched
... | designs/menu.py | from gi.repository import Gtk, Gdk, GdkPixbuf
from modules import _global as glob,models
from designs import search
import gi
gi.require_version('Gtk', '3.0')
class ToolBar(Gtk.Toolbar):
def __init__(self):
Gtk.Toolbar.__init__(self)
# =>back & forward buttons for get back & next words searched
... | 0.242116 | 0.069447 |
import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it gives an embedding of the Twitch Brasilians dataset.
The default hyperparameters give a good quality representation without grid search.
Representations are sorted by node identifiers.
"""
pa... | src/parser.py | import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it gives an embedding of the Twitch Brasilians dataset.
The default hyperparameters give a good quality representation without grid search.
Representations are sorted by node identifiers.
"""
pa... | 0.712232 | 0.25397 |
import functools
from abc import ABC
from typing import Optional
import torch
from falkon.options import FalkonOptions
from falkon.sparse.sparse_ops import sparse_matmul
from falkon.sparse.sparse_tensor import SparseTensor
from . import Kernel, KeopsKernelMixin
__all__ = ("LinearKernel", "PolynomialKernel", "Exponen... | falkon/kernels/dot_prod_kernel.py | import functools
from abc import ABC
from typing import Optional
import torch
from falkon.options import FalkonOptions
from falkon.sparse.sparse_ops import sparse_matmul
from falkon.sparse.sparse_tensor import SparseTensor
from . import Kernel, KeopsKernelMixin
__all__ = ("LinearKernel", "PolynomialKernel", "Exponen... | 0.914896 | 0.501465 |
from pathlib import Path
from asyncio import Future
import pytest
import yaml
from simcore_service_deployment_agent import docker_registries_watcher
@pytest.fixture
def valid_docker_config(here):
with Path(here / "mocks" / "valid_docker_config.yaml").open() as fp:
return yaml.safe_load(fp)
def _assert... | services/deployment-agent/tests/test_docker_registries_watcher.py |
from pathlib import Path
from asyncio import Future
import pytest
import yaml
from simcore_service_deployment_agent import docker_registries_watcher
@pytest.fixture
def valid_docker_config(here):
with Path(here / "mocks" / "valid_docker_config.yaml").open() as fp:
return yaml.safe_load(fp)
def _assert... | 0.5083 | 0.185007 |
import pylearn2
from pylearn2.utils.serial import read_bin_lush_matrix, load_train_file
import numpy as np
pylearn2_path = pylearn2.__path__[0]
example_bin_lush_path = pylearn2_path + '/utils/tests/example_bin_lush/'
yaml_path = pylearn2_path + '/utils/tests/'
def test_read_bin_lush_matrix_ubyte_scalar():
"""
... | pylearn2/utils/tests/test_serial.py | import pylearn2
from pylearn2.utils.serial import read_bin_lush_matrix, load_train_file
import numpy as np
pylearn2_path = pylearn2.__path__[0]
example_bin_lush_path = pylearn2_path + '/utils/tests/example_bin_lush/'
yaml_path = pylearn2_path + '/utils/tests/'
def test_read_bin_lush_matrix_ubyte_scalar():
"""
... | 0.575707 | 0.531939 |
import sys
import unittest
import pikli
class TestCommand(unittest.TestCase):
worked = False
def test_root_command(self):
"""
Tests that a single command(root) works with the run function
Command string: <script name>(root)
"""
def run_func(arg):
T... | tests/test_command.py | import sys
import unittest
import pikli
class TestCommand(unittest.TestCase):
worked = False
def test_root_command(self):
"""
Tests that a single command(root) works with the run function
Command string: <script name>(root)
"""
def run_func(arg):
T... | 0.174024 | 0.461745 |
import unittest
from werkzeug.exceptions import NotFound
from flask_mongoengine import ListFieldPagination, MongoEngine, Pagination
from tests import FlaskMongoEngineTestCase
class PaginationTestCase(FlaskMongoEngineTestCase):
def setUp(self):
super(PaginationTestCase, self).setUp()
self.db_name... | tests/test_pagination.py | import unittest
from werkzeug.exceptions import NotFound
from flask_mongoengine import ListFieldPagination, MongoEngine, Pagination
from tests import FlaskMongoEngineTestCase
class PaginationTestCase(FlaskMongoEngineTestCase):
def setUp(self):
super(PaginationTestCase, self).setUp()
self.db_name... | 0.49048 | 0.329877 |
from typing import Tuple
import aioredis
from discord import Server, Channel, User
from .BasePlugin import BasePlugin
from . import Bot
from .Enums import RedisStorageScope
class RedisManager(object):
def __init__(self, bot: "Bot.Bot", address: Tuple[str, int]):
self._bot = bot # type: Bot.Bot
... | NintbotForDiscord/Redis.py | from typing import Tuple
import aioredis
from discord import Server, Channel, User
from .BasePlugin import BasePlugin
from . import Bot
from .Enums import RedisStorageScope
class RedisManager(object):
def __init__(self, bot: "Bot.Bot", address: Tuple[str, int]):
self._bot = bot # type: Bot.Bot
... | 0.754463 | 0.108898 |
################ mylis: Tiny Scheme Environment in Python 3.10
## Additional runtime support by <NAME> for lis.py by
## <NAME> (c) 2010-18; See http://norvig.com/lispy.html
import functools as ft
import itertools as it
import operator as op
import math
import readline # "unused" import to enable readline in input()... | mylis/mylis_2/mylis.py |
################ mylis: Tiny Scheme Environment in Python 3.10
## Additional runtime support by <NAME> for lis.py by
## <NAME> (c) 2010-18; See http://norvig.com/lispy.html
import functools as ft
import itertools as it
import operator as op
import math
import readline # "unused" import to enable readline in input()... | 0.557845 | 0.19962 |
from collections import namedtuple
import re
from BTrees.IIBTree import IIBTree
from oursql import ProgrammingError
from reportsbot.task import Task
from reportsbot.util import join_full_title
__all__ = ["UpdateProjectIndex"]
Project = namedtuple("Project", ["id", "title", "categories"])
Page = namedtuple("Page", [... | tasks/update_project_index.py | from collections import namedtuple
import re
from BTrees.IIBTree import IIBTree
from oursql import ProgrammingError
from reportsbot.task import Task
from reportsbot.util import join_full_title
__all__ = ["UpdateProjectIndex"]
Project = namedtuple("Project", ["id", "title", "categories"])
Page = namedtuple("Page", [... | 0.72952 | 0.18418 |
from __future__ import annotations
from typing import Optional
from kubernetes.client.api_client import ApiClient
from pipeline_control.adapters.job_repository.job_repository import JobRepository
from pipeline_control.adapters.kubernetes_objects.data_generator_job import (
DataGeneratorJobConfiguration,
)
from ... | pipeline_control/src/pipeline_control/service_layer/handlers/data_generator_job_handler.py |
from __future__ import annotations
from typing import Optional
from kubernetes.client.api_client import ApiClient
from pipeline_control.adapters.job_repository.job_repository import JobRepository
from pipeline_control.adapters.kubernetes_objects.data_generator_job import (
DataGeneratorJobConfiguration,
)
from ... | 0.85344 | 0.071982 |
from typing import Pattern, List
from recognizers_text import RegExpUtility
from ...resources.chinese_date_time import ChineseDateTime, BaseDateTime
from ..extractors import DateTimeExtractor
from ..base_merged import MergedExtractorConfiguration
from ..base_holiday import BaseHolidayExtractor
from .duration_extract... | Python/libraries/recognizers-date-time/recognizers_date_time/date_time/chinese/merged_extractor_config.py |
from typing import Pattern, List
from recognizers_text import RegExpUtility
from ...resources.chinese_date_time import ChineseDateTime, BaseDateTime
from ..extractors import DateTimeExtractor
from ..base_merged import MergedExtractorConfiguration
from ..base_holiday import BaseHolidayExtractor
from .duration_extract... | 0.840619 | 0.245277 |
import json
import logging
from collections import namedtuple
from datetime import datetime
from pathlib import Path
from PIL import Image
import numpy as np
import cv2
from ..baseStrategy import baseStrategy
from ....common import id2rgb, write_to_json
logger = logging.getLogger("superannotate-python-sdk")
class ... | superannotate/input_converters/converters/coco_converters/coco_converter.py | import json
import logging
from collections import namedtuple
from datetime import datetime
from pathlib import Path
from PIL import Image
import numpy as np
import cv2
from ..baseStrategy import baseStrategy
from ....common import id2rgb, write_to_json
logger = logging.getLogger("superannotate-python-sdk")
class ... | 0.449151 | 0.123921 |
import os
import requests
import sys
import time
PUBLIC_IP = sys.argv[1]
MODEL_PKL_FILE = sys.argv[2]
if len(sys.argv) > 3:
PASSWORD = open(sys.argv[3]).read()
else:
PASSWORD = os.environ['THE_PWD']
CDSW_API = 'http://cdsw.%s.nip.io/api/v1' % (PUBLIC_IP,)
CDSW_ALTUS_API = 'http://cdsw.%s.nip.io/api/altus-ds-... | setup/terraform/resources/cdsw_setup.py |
import os
import requests
import sys
import time
PUBLIC_IP = sys.argv[1]
MODEL_PKL_FILE = sys.argv[2]
if len(sys.argv) > 3:
PASSWORD = open(sys.argv[3]).read()
else:
PASSWORD = os.environ['THE_PWD']
CDSW_API = 'http://cdsw.%s.nip.io/api/v1' % (PUBLIC_IP,)
CDSW_ALTUS_API = 'http://cdsw.%s.nip.io/api/altus-ds-... | 0.125815 | 0.04679 |
k = (
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235... | sha2_512.py | k = (
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235... | 0.3295 | 0.285344 |
import sqlite3
import time
from json_abs import *
from cep import *
import gd
import discord
from discord.ext import commands
client = gd.Client()
class MMLevel:
def __init__(self, lID: int, lName="", lAuthor="", lDifficulty=0, lDemon=0, lLength=-2, lRqS=-1, lIsRated=False, lastRequest=0, timesSent=0, timesRequeste... | db.py | import sqlite3
import time
from json_abs import *
from cep import *
import gd
import discord
from discord.ext import commands
client = gd.Client()
class MMLevel:
def __init__(self, lID: int, lName="", lAuthor="", lDifficulty=0, lDemon=0, lLength=-2, lRqS=-1, lIsRated=False, lastRequest=0, timesSent=0, timesRequeste... | 0.490724 | 0.100392 |
import os
from rox import _
def report_patherror(message, path):
"""Display a <Cancel>/<Retry>/<Examine> dialog.
This will raise an OSError exception if the user selects Cancel, or
will return successfully if the user chooses to retry."""
from rox import g, filer, toplevel_ref, toplevel_unref, ButtonMixed
topleve... | old_logen/pylogen/rox/fileutils.py | import os
from rox import _
def report_patherror(message, path):
"""Display a <Cancel>/<Retry>/<Examine> dialog.
This will raise an OSError exception if the user selects Cancel, or
will return successfully if the user chooses to retry."""
from rox import g, filer, toplevel_ref, toplevel_unref, ButtonMixed
topleve... | 0.475605 | 0.099077 |
import os
import torch
import torch.nn as nn
import numpy as np
from tensorboardX import SummaryWriter
from config import AugmentConfig
import utils
from models.augment_cnn import AugmentCNN
import copy
config = AugmentConfig()
device = torch.device("cuda")
# tensorboard
writer = SummaryWriter(log_dir=os.path.join(... | augment-ignore.py | import os
import torch
import torch.nn as nn
import numpy as np
from tensorboardX import SummaryWriter
from config import AugmentConfig
import utils
from models.augment_cnn import AugmentCNN
import copy
config = AugmentConfig()
device = torch.device("cuda")
# tensorboard
writer = SummaryWriter(log_dir=os.path.join(... | 0.884252 | 0.241411 |
import json
import magic
import base64
from pppine.encoders.json import UniversalJSONEncoder
from bson.json_util import object_hook
from string import digits
def replace_at_index(string: str, new_char: str, index: int, no_fail: bool = False):
"""
Replace a string's character at the specified index.
:para... | pppine/python/general.py | import json
import magic
import base64
from pppine.encoders.json import UniversalJSONEncoder
from bson.json_util import object_hook
from string import digits
def replace_at_index(string: str, new_char: str, index: int, no_fail: bool = False):
"""
Replace a string's character at the specified index.
:para... | 0.669529 | 0.299822 |
import logging
import sys
import six
from .segmenter import Segmenter
from .chunk import Chunk, ChunkList
_DEPENDENT_POS_FORWARD = set()
_DEPENDENT_POS_BACKWARD = {u'助詞', u'助動詞'}
_DEPENDENT_LABEL_FORWARD = set()
_DEPENDENT_LABEL_BACKWARD = {u'非自立'}
class MecabSegmenter(Segmenter):
"""MeCab Segmenter.
Attributes:... | budou/mecabsegmenter.py | import logging
import sys
import six
from .segmenter import Segmenter
from .chunk import Chunk, ChunkList
_DEPENDENT_POS_FORWARD = set()
_DEPENDENT_POS_BACKWARD = {u'助詞', u'助動詞'}
_DEPENDENT_LABEL_FORWARD = set()
_DEPENDENT_LABEL_BACKWARD = {u'非自立'}
class MecabSegmenter(Segmenter):
"""MeCab Segmenter.
Attributes:... | 0.40698 | 0.1929 |
import os
from django.test import TestCase
from django.urls import reverse
from model_bakery.baker import make
class IntegrationTest(TestCase):
def setUp(self):
if 'INTEGRATION_TEST' not in os.environ:
self.skipTest(
"Integration tests shouldn't be run along with unit tests"
... | lupa/tests/test_db_integration.py | import os
from django.test import TestCase
from django.urls import reverse
from model_bakery.baker import make
class IntegrationTest(TestCase):
def setUp(self):
if 'INTEGRATION_TEST' not in os.environ:
self.skipTest(
"Integration tests shouldn't be run along with unit tests"
... | 0.33928 | 0.183045 |
import os
import os.path as op
from copy import deepcopy
from collections import defaultdict
import logging
import re
import numpy as np
import nibabel as nib
from nipype.interfaces.base import (
TraitedSpec, traits, BaseInterface, BaseInterfaceInputSpec, File,
Directory, isdefined)
from banana.exceptions impor... | banana/interfaces/phase.py | import os
import os.path as op
from copy import deepcopy
from collections import defaultdict
import logging
import re
import numpy as np
import nibabel as nib
from nipype.interfaces.base import (
TraitedSpec, traits, BaseInterface, BaseInterfaceInputSpec, File,
Directory, isdefined)
from banana.exceptions impor... | 0.656878 | 0.248312 |
# These methods won't be on the 2nd mini test (no algorithm implementation)
# so I will verify if they are correct after the test
# (should at least be really close to correct)
from math import sin, sqrt
limm = 1e-5
def f(x):
return sin(x) ** 2
def const_search(xi, xf, h):
print("const_search")
# cha... | Pratical/Class10/tercos-aurea.py |
# These methods won't be on the 2nd mini test (no algorithm implementation)
# so I will verify if they are correct after the test
# (should at least be really close to correct)
from math import sin, sqrt
limm = 1e-5
def f(x):
return sin(x) ** 2
def const_search(xi, xf, h):
print("const_search")
# cha... | 0.374219 | 0.544014 |
import torch
from torchvision.models.resnet import resnet50
import vision_transformer as vits
dependencies = ["torch", "torchvision"]
def dino_vits16(pretrained=True, **kwargs):
"""
ViT-Small/16x16 pre-trained with DINO.
Achieves 74.5% top-1 accuracy on ImageNet with k-NN classification.
"""
mod... | dino/hubconf.py | import torch
from torchvision.models.resnet import resnet50
import vision_transformer as vits
dependencies = ["torch", "torchvision"]
def dino_vits16(pretrained=True, **kwargs):
"""
ViT-Small/16x16 pre-trained with DINO.
Achieves 74.5% top-1 accuracy on ImageNet with k-NN classification.
"""
mod... | 0.800263 | 0.382084 |
PROJECT_PATH = "./"
DATA_PATH = "/mnt/Datasets/DIOR/"
DATA = {"CLASSES":['airplane','airport','baseballfield','basketballcourt','bridge','chimney',
'dam','Expressway-Service-area','Expressway-toll-station','golffield','groundtrackfield','harbor',
'overpass','ship','stadium','storagetank','tenniscourt... | config/cfg_lodet.py |
PROJECT_PATH = "./"
DATA_PATH = "/mnt/Datasets/DIOR/"
DATA = {"CLASSES":['airplane','airport','baseballfield','basketballcourt','bridge','chimney',
'dam','Expressway-Service-area','Expressway-toll-station','golffield','groundtrackfield','harbor',
'overpass','ship','stadium','storagetank','tenniscourt... | 0.242206 | 0.216995 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import prince
from sklearn.cluster import DBSCAN
import itertools
from cmca import CMCA
from ccmca import CCMCA
plt.style.use('ggplot')
## Set up color
tableau10 = {
'blue': '#507AA6',
'orange': '#F08E39',
'red': '#DF585C',
'teal': ... | Replication Python and R Codes/Figure_3/MCA_all_Result_UTAS2012.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import prince
from sklearn.cluster import DBSCAN
import itertools
from cmca import CMCA
from ccmca import CCMCA
plt.style.use('ggplot')
## Set up color
tableau10 = {
'blue': '#507AA6',
'orange': '#F08E39',
'red': '#DF585C',
'teal': ... | 0.436142 | 0.398114 |
from megskull.graph import NodeFilter, FpropEnv
from megskull.opr.all import AssertEqual, DataProvider, BatchNormalization
from megskull.utils.logconf import get_logger
from meghair.utils import io
import megbrain as mgb
import argparse
import struct
import re
import os
import numpy as np
import cv2
logger = get_lo... | lite/tools/dump_model_mgb.py |
from megskull.graph import NodeFilter, FpropEnv
from megskull.opr.all import AssertEqual, DataProvider, BatchNormalization
from megskull.utils.logconf import get_logger
from meghair.utils import io
import megbrain as mgb
import argparse
import struct
import re
import os
import numpy as np
import cv2
logger = get_lo... | 0.611034 | 0.184804 |
import unittest
import ctypes
import errno
import os
import tempfile
from pathlib import Path
from g1.files import xattrs
from g1.files import _xattrs
class XattrsTestBase(unittest.TestCase):
def setUp(self):
super().setUp()
self._tempfile = tempfile.NamedTemporaryFile() # pylint: disable=cons... | py/g1/files/tests/test_xattrs.py | import unittest
import ctypes
import errno
import os
import tempfile
from pathlib import Path
from g1.files import xattrs
from g1.files import _xattrs
class XattrsTestBase(unittest.TestCase):
def setUp(self):
super().setUp()
self._tempfile = tempfile.NamedTemporaryFile() # pylint: disable=cons... | 0.37399 | 0.40439 |
from __future__ import print_function, unicode_literals
import socket
import time
import redis
from config import *
class Store(object):
def __init__(self):
"""
将结果存储至中转Redis服务器
"""
self.redis_client = redis.Redis(host=REDIS_RESULT_HOST)
def store_into_redis(self, info_dic... | IOC/store.py | from __future__ import print_function, unicode_literals
import socket
import time
import redis
from config import *
class Store(object):
def __init__(self):
"""
将结果存储至中转Redis服务器
"""
self.redis_client = redis.Redis(host=REDIS_RESULT_HOST)
def store_into_redis(self, info_dic... | 0.329176 | 0.187337 |
import datetime
from src import ModuleManager, utils
PRUNE_TIMEDELTA = datetime.timedelta(weeks=2)
SETTING_NAME = "inactive-channels"
SETTING = utils.BoolSetting(
SETTING_NAME, "Whether or not to leave inactive channels after 2 weeks"
)
MODE_SETTING_NAME = "inactive-channel-modes"
MODE_SETTING = utils.BoolSett... | modules/inactive_channels.py | import datetime
from src import ModuleManager, utils
PRUNE_TIMEDELTA = datetime.timedelta(weeks=2)
SETTING_NAME = "inactive-channels"
SETTING = utils.BoolSetting(
SETTING_NAME, "Whether or not to leave inactive channels after 2 weeks"
)
MODE_SETTING_NAME = "inactive-channel-modes"
MODE_SETTING = utils.BoolSett... | 0.54359 | 0.122156 |
import numpy as np
from scipy.stats.distributions import rv_continuous
__all__ = ['simulation_kelly']
class simulation_dist(rv_continuous):
def _pdf(self, x):
# eq 110
return 0.796248 * np.exp(x) / (1 + np.exp(2.75 * x))
def simulation_kelly(size=50, low=-10, high=10, alpha=1, beta=0.5,
... | astroML/datasets/kelly2007test.py | import numpy as np
from scipy.stats.distributions import rv_continuous
__all__ = ['simulation_kelly']
class simulation_dist(rv_continuous):
def _pdf(self, x):
# eq 110
return 0.796248 * np.exp(x) / (1 + np.exp(2.75 * x))
def simulation_kelly(size=50, low=-10, high=10, alpha=1, beta=0.5,
... | 0.915167 | 0.67994 |
from django.core.exceptions import ImproperlyConfigured
from django.template.response import TemplateResponse
from ....checkout import app
class SingleStepCheckoutApp(app.CheckoutApp):
BillingForm = None
checkout_templates = [
'satchless/checkout/checkout.html'
]
def __init__(self, *args, **k... | satchless/contrib/checkout/singlestep/app.py | from django.core.exceptions import ImproperlyConfigured
from django.template.response import TemplateResponse
from ....checkout import app
class SingleStepCheckoutApp(app.CheckoutApp):
BillingForm = None
checkout_templates = [
'satchless/checkout/checkout.html'
]
def __init__(self, *args, **k... | 0.521715 | 0.122523 |
import sys
import getopt
from tshark import tshark
import pcaptolist
import mscgenhandler
def replacestrings(text):
string_to_replace = [
["\"", "\\\""],
["→", "->"]
]
ret = text
for strings in string_to_replace:
ret = ret.replace(strings[0], strings[1])
return ret
def ... | pcaptomsc.py | import sys
import getopt
from tshark import tshark
import pcaptolist
import mscgenhandler
def replacestrings(text):
string_to_replace = [
["\"", "\\\""],
["→", "->"]
]
ret = text
for strings in string_to_replace:
ret = ret.replace(strings[0], strings[1])
return ret
def ... | 0.198685 | 0.309297 |
from __future__ import annotations
import sys
from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import Any, Sequence
from griffe.agents.extensions import Extensions
from griffe.agents.inspector import inspect
from griffe.agents.visitor import patch_ast, visit
from grif... | src/griffe/loader.py | from __future__ import annotations
import sys
from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import Any, Sequence
from griffe.agents.extensions import Extensions
from griffe.agents.inspector import inspect
from griffe.agents.visitor import patch_ast, visit
from grif... | 0.67694 | 0.201754 |
import numpy as np
import torch
import random
from tqdm import tqdm
import gc
import sys
import argparse
import os
from HCLMP.core import train, test
'''
Pytorch implementation of the paper "Materials representation and transfer learning for multi-property prediction"
Author: <NAME>, Cornell University, USA
Contact: <... | run_HCLMP.py | import numpy as np
import torch
import random
from tqdm import tqdm
import gc
import sys
import argparse
import os
from HCLMP.core import train, test
'''
Pytorch implementation of the paper "Materials representation and transfer learning for multi-property prediction"
Author: <NAME>, Cornell University, USA
Contact: <... | 0.410047 | 0.178383 |
__all__ = ("ROS1Package", "ROS1PackageDatabase",)
import os
import typing
import typing as t # noqa # This is a mypy workaround
from typing import Any, Collection, Dict, List
import attr
import dockerblade
from loguru import logger
from .action import ROS1ActionFormat
from .msg import ROS1MsgFormat
from .srv impor... | src/roswire/ros1/package.py | __all__ = ("ROS1Package", "ROS1PackageDatabase",)
import os
import typing
import typing as t # noqa # This is a mypy workaround
from typing import Any, Collection, Dict, List
import attr
import dockerblade
from loguru import logger
from .action import ROS1ActionFormat
from .msg import ROS1MsgFormat
from .srv impor... | 0.619471 | 0.173954 |
import requests
import re
import Metar
class BotHandler:
def __init__(self, token):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
def get_updates(self, offset=None, timeout=30):
method = 'getUpdates'
params = {'timeout': timeout, 'offset': ... | tbot.py | import requests
import re
import Metar
class BotHandler:
def __init__(self, token):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
def get_updates(self, offset=None, timeout=30):
method = 'getUpdates'
params = {'timeout': timeout, 'offset': ... | 0.35869 | 0.062245 |
from otp.ai.AIBaseGlobal import *
from direct.distributed.ClockDelta import *
from direct.fsm import StateData
from direct.directnotify import DirectNotifyGlobal
import random
from direct.task import Task
from toontown.toonbase import ToontownGlobals
import CCharChatter
import CCharPaths
class CharLonelyStateAI(StateD... | toontown/classicchars/CharStateDatasAI.py | from otp.ai.AIBaseGlobal import *
from direct.distributed.ClockDelta import *
from direct.fsm import StateData
from direct.directnotify import DirectNotifyGlobal
import random
from direct.task import Task
from toontown.toonbase import ToontownGlobals
import CCharChatter
import CCharPaths
class CharLonelyStateAI(StateD... | 0.346762 | 0.060696 |
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class EduOneCardBalanceQueryResult(object):
def __init__(self):
self._agent_code = None
self._balance = None
self._card_name = None
self._card_no = None
self._last_update_time = None
se... | alipay/aop/api/domain/EduOneCardBalanceQueryResult.py | import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class EduOneCardBalanceQueryResult(object):
def __init__(self):
self._agent_code = None
self._balance = None
self._card_name = None
self._card_no = None
self._last_update_time = None
se... | 0.519521 | 0.094302 |
from math import ceil
from sharpy.plans.acts import GridBuilding
from sc2.ids.unit_typeid import UnitTypeId
class AutoPylon(GridBuilding):
"""Builds pylons automatically when needed based on predicted supply growth speed."""
def __init__(self):
super().__init__(UnitTypeId.PYLON, 0)
async def ex... | sharpy/plans/acts/protoss/auto_pylon.py | from math import ceil
from sharpy.plans.acts import GridBuilding
from sc2.ids.unit_typeid import UnitTypeId
class AutoPylon(GridBuilding):
"""Builds pylons automatically when needed based on predicted supply growth speed."""
def __init__(self):
super().__init__(UnitTypeId.PYLON, 0)
async def ex... | 0.818628 | 0.387256 |
import numpy as np
from ...colors import Color
from ...io import MouseEvent, MouseEventType
from ..text_widget import TextWidget, SizeHint, Anchor, Size
from ..scroll_view import ScrollView
from ._legend import _Legend
from ._traces import _Traces, TICK_WIDTH, TICK_HALF
PLOT_SIZES = [SizeHint(x, x) for x in (1.0, 1.2... | nurses_2/widgets/line_plot/line_plot.py | import numpy as np
from ...colors import Color
from ...io import MouseEvent, MouseEventType
from ..text_widget import TextWidget, SizeHint, Anchor, Size
from ..scroll_view import ScrollView
from ._legend import _Legend
from ._traces import _Traces, TICK_WIDTH, TICK_HALF
PLOT_SIZES = [SizeHint(x, x) for x in (1.0, 1.2... | 0.873512 | 0.421433 |
from joblib import Parallel, delayed
from trlib.experiments.results import ExperimentResult
from trlib.algorithms.callbacks import get_callbacks
import numpy as np
class Experiment:
"""
Base class for all experiments. An experiment consists of running multiple algorithms multiple times.
"""
def __... | trlib/experiments/experiment.py | from joblib import Parallel, delayed
from trlib.experiments.results import ExperimentResult
from trlib.algorithms.callbacks import get_callbacks
import numpy as np
class Experiment:
"""
Base class for all experiments. An experiment consists of running multiple algorithms multiple times.
"""
def __... | 0.840979 | 0.287293 |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v10.resources",
marshal="google.ads.googleads.v10",
manifest={"SmartCampaignSetting",},
)
class SmartCampaignSetting(proto.Message):
r"""Settings for configuring Smart campaigns.
This message has `oneof`_ fi... | google/ads/googleads/v10/resources/types/smart_campaign_setting.py | import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v10.resources",
marshal="google.ads.googleads.v10",
manifest={"SmartCampaignSetting",},
)
class SmartCampaignSetting(proto.Message):
r"""Settings for configuring Smart campaigns.
This message has `oneof`_ fi... | 0.764276 | 0.335079 |
from os import listdir, system, getuid, chdir
from getpass import getpass
import subprocess
from shutil import move
import time
import threading
import pathlib
from Config import WifiConfig, Services
if (getuid() != 0):
print("You should run this script with sudo!\nsudo python3 install.py")
exit()
toNull = " > /dev... | CoffeeMachine/install.py | from os import listdir, system, getuid, chdir
from getpass import getpass
import subprocess
from shutil import move
import time
import threading
import pathlib
from Config import WifiConfig, Services
if (getuid() != 0):
print("You should run this script with sudo!\nsudo python3 install.py")
exit()
toNull = " > /dev... | 0.093756 | 0.051534 |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# Adapted from https://www.tensorflow.org/tutorials/structured_data/time_series#recurrent_neural_network
class WindowGenerator:
def __init__(self, input_width, label_width, shift,
dt_train, dt_test, dt_val,
... | kTsnn/src/nets/window_gen.py | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# Adapted from https://www.tensorflow.org/tutorials/structured_data/time_series#recurrent_neural_network
class WindowGenerator:
def __init__(self, input_width, label_width, shift,
dt_train, dt_test, dt_val,
... | 0.831451 | 0.590189 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class Vulnerability(object):
"""
A vulnerability found from scans in a compartment
"""
#: A constant which... | src/oci/vulnerability_scanning/models/vulnerability.py |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class Vulnerability(object):
"""
A vulnerability found from scans in a compartment
"""
#: A constant which... | 0.816699 | 0.281276 |
from datetime import datetime
import requests
from PyQt5 import QtWidgets, QtCore
import clientui
class MessengerWindow(QtWidgets.QMainWindow, clientui.Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.pressed.connect(self.button_pushed)
se... | Messenger LiveChat/messenger.py | from datetime import datetime
import requests
from PyQt5 import QtWidgets, QtCore
import clientui
class MessengerWindow(QtWidgets.QMainWindow, clientui.Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.pressed.connect(self.button_pushed)
se... | 0.256366 | 0.042642 |
import click
from ruamel import yaml
from calm.dsl.api import get_resource_api, get_api_client
from calm.dsl.providers import get_provider_interface
from .constants import GCP as gcp
Provider = get_provider_interface()
class GcpVmProvider(Provider):
provider_type = "GCP_VM"
package_name = __name__
spe... | calm/dsl/providers/plugins/gcp_vm/main.py | import click
from ruamel import yaml
from calm.dsl.api import get_resource_api, get_api_client
from calm.dsl.providers import get_provider_interface
from .constants import GCP as gcp
Provider = get_provider_interface()
class GcpVmProvider(Provider):
provider_type = "GCP_VM"
package_name = __name__
spe... | 0.5144 | 0.10217 |
import os
import ntpath
import logging
from PIL import Image, ImageFile
import PIL.ExifTags
from pictureloader.Metadata import Metadata
ImageFile.LOAD_TRUNCATED_IMAGES = True
logger = logging.getLogger(__name__)
class Picture(object):
def __init__(self, file_path):
self.file_path = file_path
sel... | src/photoorganizer/pictureloader/Picture.py | import os
import ntpath
import logging
from PIL import Image, ImageFile
import PIL.ExifTags
from pictureloader.Metadata import Metadata
ImageFile.LOAD_TRUNCATED_IMAGES = True
logger = logging.getLogger(__name__)
class Picture(object):
def __init__(self, file_path):
self.file_path = file_path
sel... | 0.205296 | 0.044702 |
#-------------------------------------------------------------------------------
# Boost Library Methods
#-------------------------------------------------------------------------------
# SCons Imports
from SCons.Script import AlwaysBuild, Flatten
# Cuppa Imports
from cuppa.colourise import colour_items
from cuppa... | cuppa/dependencies/boost/boost_library_methods.py |
#-------------------------------------------------------------------------------
# Boost Library Methods
#-------------------------------------------------------------------------------
# SCons Imports
from SCons.Script import AlwaysBuild, Flatten
# Cuppa Imports
from cuppa.colourise import colour_items
from cuppa... | 0.334698 | 0.060418 |
import pytest
import numpy as np
@pytest.mark.parametrize("filename, expected", [
("folder/file.csv", "file"),
("a/b.csv", "b"),
("test_data/test_data9.csv", "test_data9"),
("folder/23402.cs... | test_output.py | import pytest
import numpy as np
@pytest.mark.parametrize("filename, expected", [
("folder/file.csv", "file"),
("a/b.csv", "b"),
("test_data/test_data9.csv", "test_data9"),
("folder/23402.cs... | 0.697506 | 0.734072 |
import numpy as np
from .player import Player
class Game:
'''Template of the game class for creating a new game'''
def __init__(self):
self.board = None
self.player1 = None
self.player2 = None
self.chance = None
self.player_dict = None
def register_player1(self, pl... | tictactoeadarbha/game.py | import numpy as np
from .player import Player
class Game:
'''Template of the game class for creating a new game'''
def __init__(self):
self.board = None
self.player1 = None
self.player2 = None
self.chance = None
self.player_dict = None
def register_player1(self, pl... | 0.438304 | 0.267363 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import requests
import json
from rasa_core_sdk import Action
from weather import Weather, Unit
from googletrans import Translator
import wikipedia
logger ... | actions.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import requests
import json
from rasa_core_sdk import Action
from weather import Weather, Unit
from googletrans import Translator
import wikipedia
logger ... | 0.506103 | 0.067362 |
from __future__ import absolute_import, unicode_literals, print_function
import os
import unittest
from httmock import urlmatch, HTTMock, response
from wechatpy import WeChatOAuth
from wechatpy.exceptions import WeChatClientException
from wechatpy.utils import json
_TESTS_PATH = os.path.abspath(os.path.dirname(__fi... | tests/test_oauth.py | from __future__ import absolute_import, unicode_literals, print_function
import os
import unittest
from httmock import urlmatch, HTTMock, response
from wechatpy import WeChatOAuth
from wechatpy.exceptions import WeChatClientException
from wechatpy.utils import json
_TESTS_PATH = os.path.abspath(os.path.dirname(__fi... | 0.383641 | 0.073796 |
import os,sys
import pickle
import threading
from Queue import Queue
from pixiv_api import Pixiv
import pixivdl
import Tkinter
import ttk
import tkFileDialog
import tkMessageBox
class Application(Tkinter.Frame):
def __init__(self,master=None):
Tkinter.Frame.__init__(self,master)
master.title("pixi... | pixivdl-gui.py |
import os,sys
import pickle
import threading
from Queue import Queue
from pixiv_api import Pixiv
import pixivdl
import Tkinter
import ttk
import tkFileDialog
import tkMessageBox
class Application(Tkinter.Frame):
def __init__(self,master=None):
Tkinter.Frame.__init__(self,master)
master.title("pixi... | 0.17515 | 0.055875 |
import requests
from urllib.request import urlopen
from pydantic import BaseModel # type:ignore
from typing import Optional
from mabel.logging import get_logger # type:ignore
class GetRequestModel(BaseModel):
url: str
username: Optional[str] = None
password: Optional[str] = None
headers: Optional[di... | src/internals/adapters/http/http_download_adapter.py | import requests
from urllib.request import urlopen
from pydantic import BaseModel # type:ignore
from typing import Optional
from mabel.logging import get_logger # type:ignore
class GetRequestModel(BaseModel):
url: str
username: Optional[str] = None
password: Optional[str] = None
headers: Optional[di... | 0.767777 | 0.113604 |
import os
import cv2
import sys
import time
import ssim
import imageio
import tensorflow as tf
import scipy.misc as sm
import scipy.io as sio
import numpy as np
import skimage.measure as measure
from mcnet import MCNET
from utils import *
from os import listdir, makedirs, system
from os.path import exists
from argpar... | src/test_kth.py | import os
import cv2
import sys
import time
import ssim
import imageio
import tensorflow as tf
import scipy.misc as sm
import scipy.io as sio
import numpy as np
import skimage.measure as measure
from mcnet import MCNET
from utils import *
from os import listdir, makedirs, system
from os.path import exists
from argpar... | 0.167287 | 0.132992 |
from __future__ import annotations
from django.core.validators import MinValueValidator
from django.db import models
from pydis_site.apps.api.models.mixins import ModelReprMixin
class Role(ModelReprMixin, models.Model):
"""
A role on our Discord server.
The comparison operators <, <=, >, >=, ==, != act... | pydis_site/apps/api/models/bot/role.py | from __future__ import annotations
from django.core.validators import MinValueValidator
from django.db import models
from pydis_site.apps.api.models.mixins import ModelReprMixin
class Role(ModelReprMixin, models.Model):
"""
A role on our Discord server.
The comparison operators <, <=, >, >=, ==, != act... | 0.905671 | 0.218669 |
import logging
from datetime import datetime, timedelta
import homeassistant.core as ha
from custom_components.irrigation_unlimited.irrigation_unlimited import (
IUCoordinator,
)
_LOGGER = logging.getLogger(__name__)
test_config_dir = "tests/configs/"
NO_CHECK: bool = False
# Shh, quiet now.
def quiet_mode() -... | tests/iu_test_support.py | import logging
from datetime import datetime, timedelta
import homeassistant.core as ha
from custom_components.irrigation_unlimited.irrigation_unlimited import (
IUCoordinator,
)
_LOGGER = logging.getLogger(__name__)
test_config_dir = "tests/configs/"
NO_CHECK: bool = False
# Shh, quiet now.
def quiet_mode() -... | 0.524882 | 0.299678 |
from odoo.tests import common
class TestGroupBooleans(common.TransactionCase):
def setUp(self):
super(TestGroupBooleans, self).setUp()
self.Model = self.env['test_read_group.aggregate.boolean']
def test_no_value(self):
groups = self.Model.read_group(
domain=[],
... | odoo-13.0/odoo/addons/test_read_group/tests/test_group_operator.py | from odoo.tests import common
class TestGroupBooleans(common.TransactionCase):
def setUp(self):
super(TestGroupBooleans, self).setUp()
self.Model = self.env['test_read_group.aggregate.boolean']
def test_no_value(self):
groups = self.Model.read_group(
domain=[],
... | 0.400749 | 0.426142 |
import os
import sys
import textwrap
from Cython.Compiler.CmdLine import parse_command_line
from Cython.Compiler.Main import create_default_resultobj, CompilationSource
from Cython.Compiler import Pipeline
from Cython.Compiler.Scanning import FileSourceDescriptor
from Cython.Compiler.Visitor import TreeVisitor, PrintT... | 2020/CythonParser/pyx_gen.py | import os
import sys
import textwrap
from Cython.Compiler.CmdLine import parse_command_line
from Cython.Compiler.Main import create_default_resultobj, CompilationSource
from Cython.Compiler import Pipeline
from Cython.Compiler.Scanning import FileSourceDescriptor
from Cython.Compiler.Visitor import TreeVisitor, PrintT... | 0.476336 | 0.172625 |
import gzip
import lzma
import bz2
import io
import builtins
WRITE_MODE = "wt"
class ReusableFile(object):
"""
Class which emulates the builtin file except that calling iter() on it will return separate
iterators on different file handlers (which are automatically closed when iteration stops). This
... | functional/io.py | import gzip
import lzma
import bz2
import io
import builtins
WRITE_MODE = "wt"
class ReusableFile(object):
"""
Class which emulates the builtin file except that calling iter() on it will return separate
iterators on different file handlers (which are automatically closed when iteration stops). This
... | 0.677367 | 0.130285 |
import warnings
import numpy as np
from scipy.interpolate import interp1d
import astropy.units as u
import plasmapy.particles
from plasmapy.particles.exceptions import InvalidParticleError
import fiasco
from fiasco.io import DataIndexer
__all__ = ['list_elements', 'list_ions', 'proton_electron_ratio']
def list_ele... | fiasco/fiasco.py | import warnings
import numpy as np
from scipy.interpolate import interp1d
import astropy.units as u
import plasmapy.particles
from plasmapy.particles.exceptions import InvalidParticleError
import fiasco
from fiasco.io import DataIndexer
__all__ = ['list_elements', 'list_ions', 'proton_electron_ratio']
def list_ele... | 0.802981 | 0.348728 |
import urllib.request
import json
import re
import os
BASE_URL = 'https://quantiacs.com'
# BASE_URL='https://staging-2.quantnet-ai.ru'
TOC_SECTION = 'Examples'
curdir = os.path.abspath(os.path.dirname(__file__))
# print(curdir)
os.makedirs(curdir + '/examples', exist_ok=True)
for f in os.listdir(curdir + '/examples'... | en/source/pull_examples.py | import urllib.request
import json
import re
import os
BASE_URL = 'https://quantiacs.com'
# BASE_URL='https://staging-2.quantnet-ai.ru'
TOC_SECTION = 'Examples'
curdir = os.path.abspath(os.path.dirname(__file__))
# print(curdir)
os.makedirs(curdir + '/examples', exist_ok=True)
for f in os.listdir(curdir + '/examples'... | 0.081964 | 0.097219 |
import os
import socket
import json
import time
# Local imports
import processes.ggpPlayerProcess
import util.config_help
import networking.working as NET
# Setting up logging:
# https://docs.python.org/2/howto/logging.html#configuring-logging-for-a-library
import logging
LOG = logging.getLogger(__name__)
LOG.add... | src/main/python/worker.py | import os
import socket
import json
import time
# Local imports
import processes.ggpPlayerProcess
import util.config_help
import networking.working as NET
# Setting up logging:
# https://docs.python.org/2/howto/logging.html#configuring-logging-for-a-library
import logging
LOG = logging.getLogger(__name__)
LOG.add... | 0.200088 | 0.066085 |
from __future__ import annotations
import asyncio
import logging
from collections.abc import Callable, Coroutine
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar
from ... import utils
from ...abc import BaseUser
from ...enums import IntEnum
from ...models import register
from ...protobufs import EMsg, GCMsg, ... | steam/ext/_gc/state.py | from __future__ import annotations
import asyncio
import logging
from collections.abc import Callable, Coroutine
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar
from ... import utils
from ...abc import BaseUser
from ...enums import IntEnum
from ...models import register
from ...protobufs import EMsg, GCMsg, ... | 0.672869 | 0.057414 |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class CdpNeighborRemote(RemoteModel):
"""
The CDP table entries for the device.
| ``CDPNeighborID:`` The internal NetMRI identifier for this CDP table entry.
| ``attribute type:`` number
| ... | infoblox_netmri/api/remote/models/cdp_neighbor_remote.py | from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class CdpNeighborRemote(RemoteModel):
"""
The CDP table entries for the device.
| ``CDPNeighborID:`` The internal NetMRI identifier for this CDP table entry.
| ``attribute type:`` number
| ... | 0.840095 | 0.614249 |
def weasels(string):
weasels = [
"most",
"many",
"various",
"some",
"a lot",
"several",
"few",
"often",
"probably",
"huge",
"tiny",
"very",
"fairly",
"extremely",
"exceedingly",
... | opm/weaselWords/weaselWords.py |
def weasels(string):
weasels = [
"most",
"many",
"various",
"some",
"a lot",
"several",
"few",
"often",
"probably",
"huge",
"tiny",
"very",
"fairly",
"extremely",
"exceedingly",
... | 0.33939 | 0.398641 |
import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
import time
from PIL import Image
import plotly.express as px
import pickle
import umap
import plotly.figure_factory as ff
import tensorflow a... | webapp/my_app.py | import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
import time
from PIL import Image
import plotly.express as px
import pickle
import umap
import plotly.figure_factory as ff
import tensorflow a... | 0.553505 | 0.226035 |
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list("JQKA")
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for ra... | books/FluentPython/cp11_protocols.py | import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list("JQKA")
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for ra... | 0.673514 | 0.253653 |
from unittest import TestCase, main
from unittest.mock import patch, MagicMock, call
from monolith_filemanager.file import FileMap, Singleton
class TestFileMap(TestCase):
def setUp(self):
Singleton._instances = {}
def tearDown(self):
Singleton._instances = {}
@patch("monolith_filemanage... | tests/file/test_map.py | from unittest import TestCase, main
from unittest.mock import patch, MagicMock, call
from monolith_filemanager.file import FileMap, Singleton
class TestFileMap(TestCase):
def setUp(self):
Singleton._instances = {}
def tearDown(self):
Singleton._instances = {}
@patch("monolith_filemanage... | 0.652463 | 0.481515 |
from pants.backend.python.register import build_file_aliases
from pants.base.exceptions import TargetDefinitionException
from pants.testutil.test_base import TestBase
class TestPythonBinary(TestBase):
@classmethod
def alias_groups(self):
return build_file_aliases()
def setUp(self):
super... | tests/python/pants_test/targets/test_python_binary.py |
from pants.backend.python.register import build_file_aliases
from pants.base.exceptions import TargetDefinitionException
from pants.testutil.test_base import TestBase
class TestPythonBinary(TestBase):
@classmethod
def alias_groups(self):
return build_file_aliases()
def setUp(self):
super... | 0.75101 | 0.339773 |
import unittest
from pysapets.eagle import Eagle
from pysapets.animal import Animal
import pysapets.constants as constants
from unittest.mock import patch
from io import StringIO
from copy import deepcopy
class EagleTest(unittest.TestCase):
def setUp(self):
self.eagle = Eagle()
self.friends = [self.eagle, A... | utils/boilerplate/test_eagle.py | import unittest
from pysapets.eagle import Eagle
from pysapets.animal import Animal
import pysapets.constants as constants
from unittest.mock import patch
from io import StringIO
from copy import deepcopy
class EagleTest(unittest.TestCase):
def setUp(self):
self.eagle = Eagle()
self.friends = [self.eagle, A... | 0.490236 | 0.669515 |
import base64
import csv
import io
import mapnik
from itertools import groupby
from os.path import dirname
from shapely.geometry import box, Point
from sys import path, stdin, stderr
from tilebrute.core import print_status, inc_counter, emit, which, merc_srs
try:
from gdal2tiles import GlobalMercator
except Imp... | src/main/python/tilebrute/draw_tiles.py |
import base64
import csv
import io
import mapnik
from itertools import groupby
from os.path import dirname
from shapely.geometry import box, Point
from sys import path, stdin, stderr
from tilebrute.core import print_status, inc_counter, emit, which, merc_srs
try:
from gdal2tiles import GlobalMercator
except Imp... | 0.450843 | 0.291488 |
import numpy as np
class Meter(object):
def __init__(self, name, val, avg):
self.name = name
self.val = val
self.avg = avg
def __repr__(self):
return "{name}: {val:.6f} ({avg:.6f})".format(
name=self.name, val=self.val, avg=self.avg
)
def __format__(se... | utils/average_meter_helper.py | import numpy as np
class Meter(object):
def __init__(self, name, val, avg):
self.name = name
self.val = val
self.avg = avg
def __repr__(self):
return "{name}: {val:.6f} ({avg:.6f})".format(
name=self.name, val=self.val, avg=self.avg
)
def __format__(se... | 0.657098 | 0.215289 |
import functools
import fractions
import math
import re
from collections import OrderedDict
import sys
# define useful methods
# read line from file split it according to separator and convert it to type
def process_input_line(input_file,
input_mapping=int,
... | src/2018/firstc/C.py | import functools
import fractions
import math
import re
from collections import OrderedDict
import sys
# define useful methods
# read line from file split it according to separator and convert it to type
def process_input_line(input_file,
input_mapping=int,
... | 0.097675 | 0.157817 |
import logging
from typing import Any, Dict, List, Optional, TypedDict, Union
from utility import Utility
log: logging.Logger = logging.getLogger(__name__)
class ElderChallenges(TypedDict):
"""Structure of elder_challenges.csv"""
id: int
ref: str
name: str
desc: str
amount: int
loot: in... | ModernWarfare/XAssets/challenges.py | import logging
from typing import Any, Dict, List, Optional, TypedDict, Union
from utility import Utility
log: logging.Logger = logging.getLogger(__name__)
class ElderChallenges(TypedDict):
"""Structure of elder_challenges.csv"""
id: int
ref: str
name: str
desc: str
amount: int
loot: in... | 0.776835 | 0.46557 |
from rx import Observable
from rx.observer import AbstractObserver
from rx.anonymousobservable import AnonymousObservable
from rx.internal import extensionmethod
@extensionmethod(Observable, alias="tap")
def do_action(self, on_next=None, on_error=None, on_completed=None,
observer=None):
"""Invokes a... | rx/linq/observable/doaction.py | from rx import Observable
from rx.observer import AbstractObserver
from rx.anonymousobservable import AnonymousObservable
from rx.internal import extensionmethod
@extensionmethod(Observable, alias="tap")
def do_action(self, on_next=None, on_error=None, on_completed=None,
observer=None):
"""Invokes a... | 0.862887 | 0.250219 |
import platform
import wget
import requests
import os
import pickle
from zipfile import ZipFile
from os.path import expanduser
def get_savedir(savedir=None):
if savedir:
os.makedirs(savedir, exist_ok=True)
return savedir
pf = platform.system()
if pf == "Windows":
savedir = "C:\wor... | word2word/utils.py | import platform
import wget
import requests
import os
import pickle
from zipfile import ZipFile
from os.path import expanduser
def get_savedir(savedir=None):
if savedir:
os.makedirs(savedir, exist_ok=True)
return savedir
pf = platform.system()
if pf == "Windows":
savedir = "C:\wor... | 0.207215 | 0.082586 |
import copy
import datetime
import unittest
from unittest import mock
from unittest.mock import Mock, MagicMock
from freezegun import freeze_time
from airflow.models import TaskInstance
from airflow.models import Connection
from airflow.settings import Session
from airflow.utils import timezone
from airflow.utils.stat... | tests/test_sentry_hook.py | import copy
import datetime
import unittest
from unittest import mock
from unittest.mock import Mock, MagicMock
from freezegun import freeze_time
from airflow.models import TaskInstance
from airflow.models import Connection
from airflow.settings import Session
from airflow.utils import timezone
from airflow.utils.stat... | 0.382949 | 0.314314 |
import unittest
def parse(s):
lines = [line.strip() for line in s.strip().splitlines()]
res = []
for line in lines:
li = []
for e in line:
if e == '*':
li.append(None)
else:
li.append(int(e))
res.append(li)
return res
def... | quizzes/00.organize.me/Cracking the Coding Interview/sudoku.py |
import unittest
def parse(s):
lines = [line.strip() for line in s.strip().splitlines()]
res = []
for line in lines:
li = []
for e in line:
if e == '*':
li.append(None)
else:
li.append(int(e))
res.append(li)
return res
def... | 0.245808 | 0.331282 |
import sys
sys.path.append("/datagrid/personal/neoral/repos/raft_debug")
sys.path.append('core')
import argparse
import os
import numpy as np
import torch
from PIL import Image
from RAFT.core.raft import RAFT
import RAFT.core.utils.flow_gen as flow_gen
from tqdm import tqdm
from RAFT.core.utils.utils import InputPad... | RAFT/generate_flow_scripts/kitti_generator.py | import sys
sys.path.append("/datagrid/personal/neoral/repos/raft_debug")
sys.path.append('core')
import argparse
import os
import numpy as np
import torch
from PIL import Image
from RAFT.core.raft import RAFT
import RAFT.core.utils.flow_gen as flow_gen
from tqdm import tqdm
from RAFT.core.utils.utils import InputPad... | 0.368633 | 0.230378 |
import logging
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
LOGGER = logging.getLogger(__name__)
logging.basicConfig(filename='module.log',level=logging.INFO, format=LOG_FORMAT)
from playlist import Playlist
class Player:
def __init__(self, ... | modules/player/player.py | import logging
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
LOGGER = logging.getLogger(__name__)
logging.basicConfig(filename='module.log',level=logging.INFO, format=LOG_FORMAT)
from playlist import Playlist
class Player:
def __init__(self, ... | 0.107842 | 0.057019 |
import uuid
import json
import os.path as path
import IPython
web_assets_dir = path.join(path.dirname(path.realpath(__file__)), 'web_assets')
class TextualHeatmap:
"""Create interactive textual heatmaps for Jupiter notebooks.
This is useful for PyTorch or pure TensorFlow. You should properly use
`KerasLe... | textualheatmap/textual_heatmap.py | import uuid
import json
import os.path as path
import IPython
web_assets_dir = path.join(path.dirname(path.realpath(__file__)), 'web_assets')
class TextualHeatmap:
"""Create interactive textual heatmaps for Jupiter notebooks.
This is useful for PyTorch or pure TensorFlow. You should properly use
`KerasLe... | 0.780662 | 0.425844 |
import pygame as pg
from pygame.locals import *
from connect_4_images import * # BLIT, RECT, SCREEN
from connect_4_scene_switch import *
from _connect4_logic import *
class OPTIONS1():
def __init__(self):
self.gear_bottom_right = ROTATE(image.GEAR,(1336,610),1.5)
self.gear_bottom = ROTATE(image.GE... | Connect4Game-x64/connect_4_options.py |
import pygame as pg
from pygame.locals import *
from connect_4_images import * # BLIT, RECT, SCREEN
from connect_4_scene_switch import *
from _connect4_logic import *
class OPTIONS1():
def __init__(self):
self.gear_bottom_right = ROTATE(image.GEAR,(1336,610),1.5)
self.gear_bottom = ROTATE(image.GE... | 0.09259 | 0.067608 |
# 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
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | tests/transforms/test_hamiltonian_expand.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
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.866923 | 0.608972 |
def get_sql(company, conn, start_date, end_date, gl_code, all_types=False):
sql = ("""
SELECT
{1} AS "[DATE]", {1} AS "[DATE]"
, b.gl_code
, a.source_code
, COALESCE(op.tran_tot, 0) AS "[REAL2]"
, COALESCE(cl.tran_tot, 0) - COALESCE(op.tran_tot, ... | aib/sql/gl_mvmt_per_type.py | def get_sql(company, conn, start_date, end_date, gl_code, all_types=False):
sql = ("""
SELECT
{1} AS "[DATE]", {1} AS "[DATE]"
, b.gl_code
, a.source_code
, COALESCE(op.tran_tot, 0) AS "[REAL2]"
, COALESCE(cl.tran_tot, 0) - COALESCE(op.tran_tot, ... | 0.25618 | 0.172416 |
from .._utils import IntermediateLayerGetter
from ..utils import load_state_dict_from_url
from .. import resnet
from .. import resnet_divnormei
from .. import resnet_divnorm
from .fcn import FCN, FCNHead
from .deeplabv3 import DeepLabV3, DeepLabHead
__all__ = ['fcn_resnet50', 'fcn_resnet101', 'deeplabv3_resnet50', ... | semseg/models/segmentation/segmentation.py | from .._utils import IntermediateLayerGetter
from ..utils import load_state_dict_from_url
from .. import resnet
from .. import resnet_divnormei
from .. import resnet_divnorm
from .fcn import FCN, FCNHead
from .deeplabv3 import DeepLabV3, DeepLabHead
__all__ = ['fcn_resnet50', 'fcn_resnet101', 'deeplabv3_resnet50', ... | 0.714827 | 0.253249 |
cr# -*- coding: utf-8 -*-
"""
This script is used to plot cohen'd using circle format.
"""
import numpy as np
import pytest
import scipy.io as sio
import matplotlib.pyplot as plt
from mne.viz import plot_connectivity_circle, circular_layout
def test_plot_connectivity_circle():
"""
Test plotting connectivity ... | eslearn/SSD_classification/Visulization/lc_plot_average_cohen_circle.py | cr# -*- coding: utf-8 -*-
"""
This script is used to plot cohen'd using circle format.
"""
import numpy as np
import pytest
import scipy.io as sio
import matplotlib.pyplot as plt
from mne.viz import plot_connectivity_circle, circular_layout
def test_plot_connectivity_circle():
"""
Test plotting connectivity ... | 0.369429 | 0.441492 |
import pygame as pg
import random
import os
class Obstacle():
def __init__(self, vel):
self.x = 830
self.vel = vel
self.path = os.getcwd() + '/' + 'sprites' + '/'
def update(self):
self.x -= self.vel
def draw(self, window):
pass
def draw_hitbox... | library/Obstacles.py | import pygame as pg
import random
import os
class Obstacle():
def __init__(self, vel):
self.x = 830
self.vel = vel
self.path = os.getcwd() + '/' + 'sprites' + '/'
def update(self):
self.x -= self.vel
def draw(self, window):
pass
def draw_hitbox... | 0.202838 | 0.067209 |
from torch.utils.data import Dataset, IterableDataset, DataLoader
from itertools import cycle, islice
from . import AuthInfo, Range, Configuration, ZookeeperInstance, AccumuloConnector, Authorizations, Key, AccumuloBase
class AccumuloCluster(AccumuloBase, IterableDataset):
def __init__(self, instance: str , zooke... | sharkbite/torch.py | from torch.utils.data import Dataset, IterableDataset, DataLoader
from itertools import cycle, islice
from . import AuthInfo, Range, Configuration, ZookeeperInstance, AccumuloConnector, Authorizations, Key, AccumuloBase
class AccumuloCluster(AccumuloBase, IterableDataset):
def __init__(self, instance: str , zooke... | 0.749912 | 0.207155 |
import time
from SX127x.LoRa import *
from SX127x.board_config import BOARD
BOARD.setup()
BOARD.reset()
class mylora(LoRa):
def __init__(self, verbose=False):
super(mylora, self).__init__(verbose)
self.set_mode(MODE.SLEEP)
self.set_dio_mapping([0] * 6)
self.var=0
self.coun... | code/radio_tests/loraTwoWay.py | import time
from SX127x.LoRa import *
from SX127x.board_config import BOARD
BOARD.setup()
BOARD.reset()
class mylora(LoRa):
def __init__(self, verbose=False):
super(mylora, self).__init__(verbose)
self.set_mode(MODE.SLEEP)
self.set_dio_mapping([0] * 6)
self.var=0
self.coun... | 0.177454 | 0.097433 |