code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
from sklearn.me... | securitas/utils.py | from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
from sklearn.me... | 0.280715 | 0.326164 |
import matplotlib.pyplot as plt
import numpy as np
from filterpy.common import Q_discrete_white_noise
from numpy.random import randn
from filterpy.kalman import UnscentedKalmanFilter as UKF
from filterpy.kalman import MerweScaledSigmaPoints
import book_format
book_format.set_style()
class INSim:
def __init__(sel... | SOC_Photon/Battery State/EKF/sandbox/Ex 20 lag UKF.py | import matplotlib.pyplot as plt
import numpy as np
from filterpy.common import Q_discrete_white_noise
from numpy.random import randn
from filterpy.kalman import UnscentedKalmanFilter as UKF
from filterpy.kalman import MerweScaledSigmaPoints
import book_format
book_format.set_style()
class INSim:
def __init__(sel... | 0.761716 | 0.687768 |
import numpy as np
# Values used in the paper
use_minX = np.array([-7.9118004, 0., -9.394201, 0., -3.9944992, 0., -4.2058992, 0., -2.851099, 0., -6.1702003, 0., -4.963501, 0., -6.359, 0., -5.72029], dtype=np.float32)
use_maxX = np.array([5.9019985, 0.5281896, 5.8084, 0.46895373, 2.9131012, 0.52544963, 3.900301, 0.450... | convert_csv_to_npy.py |
import numpy as np
# Values used in the paper
use_minX = np.array([-7.9118004, 0., -9.394201, 0., -3.9944992, 0., -4.2058992, 0., -2.851099, 0., -6.1702003, 0., -4.963501, 0., -6.359, 0., -5.72029], dtype=np.float32)
use_maxX = np.array([5.9019985, 0.5281896, 5.8084, 0.46895373, 2.9131012, 0.52544963, 3.900301, 0.450... | 0.606964 | 0.512205 |
import argparse
import torch
import utils
import os
import pickle
import gym
import envs
from torch.utils import data
import numpy as np
from collections import defaultdict
import modules
import matplotlib.pyplot as plt
import matplotlib as mpl
import ffmpeg
input_shape = None
def load_env():
global input_shape
... | visual_shapes.py | import argparse
import torch
import utils
import os
import pickle
import gym
import envs
from torch.utils import data
import numpy as np
from collections import defaultdict
import modules
import matplotlib.pyplot as plt
import matplotlib as mpl
import ffmpeg
input_shape = None
def load_env():
global input_shape
... | 0.608594 | 0.392511 |
import pprint
import re # noqa: F401
import six
from ubiops.configuration import Configuration
class EnvironmentVariableCopy(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
o... | ubiops/models/environment_variable_copy.py | import pprint
import re # noqa: F401
import six
from ubiops.configuration import Configuration
class EnvironmentVariableCopy(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
o... | 0.698227 | 0.107766 |
import os
import tempfile
import logging
import signal
import pytest
from pybnb.common import inf, nan
from pybnb.misc import (
_cast_to_float_or_int,
MPI_InterruptHandler,
metric_format,
time_format,
get_gap_labels,
as_stream,
get_default_args,
get_keyword_docs,
get_simple_logger,... | src/tests/test_misc.py | import os
import tempfile
import logging
import signal
import pytest
from pybnb.common import inf, nan
from pybnb.misc import (
_cast_to_float_or_int,
MPI_InterruptHandler,
metric_format,
time_format,
get_gap_labels,
as_stream,
get_default_args,
get_keyword_docs,
get_simple_logger,... | 0.553505 | 0.588475 |
import tensorflow as tf
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import ConvLSTM2D, Conv2D
from tensorflow.keras.layers import MaxPooling2D, UpSampling2D, Concatenate
from tensorflow.keras.layers import BatchNormalization, Activation, Dropout, TimeDistributed
# Conv layer.
def conv_layer(... | modules/old/model_convlstm.py | import tensorflow as tf
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import ConvLSTM2D, Conv2D
from tensorflow.keras.layers import MaxPooling2D, UpSampling2D, Concatenate
from tensorflow.keras.layers import BatchNormalization, Activation, Dropout, TimeDistributed
# Conv layer.
def conv_layer(... | 0.871092 | 0.654343 |
from __future__ import absolute_import
from __future__ import print_function
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
fr... | hyperparameter_tuning/keras_bring_your_own/trainer/start.py | from __future__ import absolute_import
from __future__ import print_function
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
fr... | 0.899348 | 0.357511 |
import datetime
from bs4 import BeautifulSoup
from flask import current_app, url_for
from flask_sqlalchemy import BaseQuery
from sqlalchemy_searchable import SearchQueryMixin, make_searchable
from sqlalchemy_utils.types import TSVectorType
from app.extensions import db
from lib.model_utils import GetOr404Mixin, GetOr... | app/blueprints/notes/models.py | import datetime
from bs4 import BeautifulSoup
from flask import current_app, url_for
from flask_sqlalchemy import BaseQuery
from sqlalchemy_searchable import SearchQueryMixin, make_searchable
from sqlalchemy_utils.types import TSVectorType
from app.extensions import db
from lib.model_utils import GetOr404Mixin, GetOr... | 0.547706 | 0.107204 |
if __name__ == "__main__":
import sys
sys.path.append("..")
del sys
from fenalib.assert_utils import assert_type
from fenalib.lexical_token import Token
from fenalib.nodes import CmdNode, StmtNode, ProgramNode
class TreePostfixTraversal:
"""
Visitor from https://ruslanspivak.com/
"""
def... | fenalib/node_visitors.py | if __name__ == "__main__":
import sys
sys.path.append("..")
del sys
from fenalib.assert_utils import assert_type
from fenalib.lexical_token import Token
from fenalib.nodes import CmdNode, StmtNode, ProgramNode
class TreePostfixTraversal:
"""
Visitor from https://ruslanspivak.com/
"""
def... | 0.523664 | 0.345326 |
import scipy.misc
import random
import os
train_set = []
test_set = []
"""
Load set of images in a directory.
This will automatically allocate a
random 20% of the images as a test set
data_dir: path to directory containing images
"""
def load_dataset(data_dir):
img_files = os.listdir(data_dir)
test_size ... | data.py |
import scipy.misc
import random
import os
train_set = []
test_set = []
"""
Load set of images in a directory.
This will automatically allocate a
random 20% of the images as a test set
data_dir: path to directory containing images
"""
def load_dataset(data_dir):
img_files = os.listdir(data_dir)
test_size ... | 0.517327 | 0.430656 |
from dataclasses import dataclass, field
import datetime
import io
import itertools as it
import json
from typing import Dict, Union, List
import pandas as pd
import requests
from redfin import Redfin
from dask import delayed
from dask.distributed import Client, as_completed
REDFIN_ENDPOINT='https://www.redfin.com/s... | yellowtail/agent.py | from dataclasses import dataclass, field
import datetime
import io
import itertools as it
import json
from typing import Dict, Union, List
import pandas as pd
import requests
from redfin import Redfin
from dask import delayed
from dask.distributed import Client, as_completed
REDFIN_ENDPOINT='https://www.redfin.com/s... | 0.738103 | 0.143728 |
import argparse
import shutil
from commands import compile_jupyter
from commands import compile_latex
from commands import compile_latex_project
from commands import copy_meta_file
JUPYTER_SRC_PATH = './jupyter'
LATEX_SRC_PATH = './latex'
OUTPUT_ROOT_PATH = './out'
OUTPUT_JUPYTER_PATH = '{}/{}'.format(OUTPUT_ROOT... | app/__main__.py | import argparse
import shutil
from commands import compile_jupyter
from commands import compile_latex
from commands import compile_latex_project
from commands import copy_meta_file
JUPYTER_SRC_PATH = './jupyter'
LATEX_SRC_PATH = './latex'
OUTPUT_ROOT_PATH = './out'
OUTPUT_JUPYTER_PATH = '{}/{}'.format(OUTPUT_ROOT... | 0.322633 | 0.068944 |
import numpy as np
import os
import argparse
def check_size(submission_file):
max_size = 60*1024*1024
if os.path.getsize(submission_file) > max_size:
raise IOError,"File size exceeds the specified maximum size, which is 60M for the server."
def remove_ignored_det(dt_box, ig_box):
remain_box = []
... | demo/python/evaluate.py | import numpy as np
import os
import argparse
def check_size(submission_file):
max_size = 60*1024*1024
if os.path.getsize(submission_file) > max_size:
raise IOError,"File size exceeds the specified maximum size, which is 60M for the server."
def remove_ignored_det(dt_box, ig_box):
remain_box = []
... | 0.38445 | 0.290402 |
from gi.repository import PeasGtk
from gi.repository import GObject
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gio
import os
import json
class discord_status_prefs(GObject.Object, PeasGtk.Configurable):
__gtype_name__ = "discord_status_prefs"
object = GObject.property(ty... | status_prefs.py | from gi.repository import PeasGtk
from gi.repository import GObject
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gio
import os
import json
class discord_status_prefs(GObject.Object, PeasGtk.Configurable):
__gtype_name__ = "discord_status_prefs"
object = GObject.property(ty... | 0.399929 | 0.055978 |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import unittest
from netease_im import ImClient
from netease_im import components
from netease_im.constants.params import *
KEY = '271f99c2ad5a414459fc02071eb1e405'
SECRET = '<KEY>'
BASE_URI = 'https://api.netease.im/nimserver'
def suite():
"""Define all the tests o... | netease_im/tests/netease_im/components/test_user.py |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import unittest
from netease_im import ImClient
from netease_im import components
from netease_im.constants.params import *
KEY = '271f99c2ad5a414459fc02071eb1e405'
SECRET = '<KEY>'
BASE_URI = 'https://api.netease.im/nimserver'
def suite():
"""Define all the tests o... | 0.585575 | 0.162712 |
import numpy as np
import cv2
import os
from tqdm import tqdm
import random
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.patches as patches
import pickle
from glob import glob
import imgaug as ia
from imgaug import augmenters as iaa
from shapely.geometry import Polygon
cardW=63
c... | code/deck.py | import numpy as np
import cv2
import os
from tqdm import tqdm
import random
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.patches as patches
import pickle
from glob import glob
import imgaug as ia
from imgaug import augmenters as iaa
from shapely.geometry import Polygon
cardW=63
c... | 0.442637 | 0.138958 |
from django.db import models
class Network(models.Model):
"""定义台网信息"""
code = models.CharField(max_length=50, unique=True, verbose_name="台网代码")
name = models.CharField(max_length=50, blank=True, verbose_name="台网名称")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(... | backend/basicinfo/models.py | from django.db import models
class Network(models.Model):
"""定义台网信息"""
code = models.CharField(max_length=50, unique=True, verbose_name="台网代码")
name = models.CharField(max_length=50, blank=True, verbose_name="台网名称")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(... | 0.653127 | 0.284697 |
import numpy as np
from htm import HTM
from Jos import Jo
from JRxs import JRx
from JRys import JRy
from JRzs import JRz
from Jo_dots import Jo_dot
from JRx_dots import JRx_dot
from JRy_dots import JRy_dot
from JRz_dots import JRz_dot
class Baxter(HTM, Jo, JRx, JRy, JRz, Jo_dot, JRx_dot, JRy_dot, JRz_dot):
... | misc/baxter/src_py/integral.py | import numpy as np
from htm import HTM
from Jos import Jo
from JRxs import JRx
from JRys import JRy
from JRzs import JRz
from Jo_dots import Jo_dot
from JRx_dots import JRx_dot
from JRy_dots import JRy_dot
from JRz_dots import JRz_dot
class Baxter(HTM, Jo, JRx, JRy, JRz, Jo_dot, JRx_dot, JRy_dot, JRz_dot):
... | 0.270866 | 0.117876 |
import argparse
import os
import numpy as np
import torch as t
from torch.optim import Adam
from utils.batch_loader import BatchLoader
from utils.parameters import Parameters
from model.rvae_dilated import RVAE_dilated
if __name__ == "__main__":
if not os.path.exists('data/word_embeddings.npy'):
raise F... | train.py | import argparse
import os
import numpy as np
import torch as t
from torch.optim import Adam
from utils.batch_loader import BatchLoader
from utils.parameters import Parameters
from model.rvae_dilated import RVAE_dilated
if __name__ == "__main__":
if not os.path.exists('data/word_embeddings.npy'):
raise F... | 0.566019 | 0.092155 |
import math
from . import gan_layer_architecture_shapes
from . import image_masks
def get_generator_config():
"""Gets generator config.
Returns:
Dictionary of generator configs.
"""
generator_dict = dict()
# Which paper to use for generator architecture: "berg", "GANomaly".
generato... | proganomaly_modules/training_module/trainer/defaults.py |
import math
from . import gan_layer_architecture_shapes
from . import image_masks
def get_generator_config():
"""Gets generator config.
Returns:
Dictionary of generator configs.
"""
generator_dict = dict()
# Which paper to use for generator architecture: "berg", "GANomaly".
generato... | 0.802672 | 0.456955 |
import os
import sys
import traceback
import pathlib
import json
from dynamicmethod import dynamicmethod
from .file_utils import FileWrapper
__all__ = ['TNode', 'is_file_path', 'open_file']
def get_traceback(exc=None):
"""Get the exception traceback or the system traceback."""
_, _, sys_tb = sys.exc_info()... | tnode/interface.py | import os
import sys
import traceback
import pathlib
import json
from dynamicmethod import dynamicmethod
from .file_utils import FileWrapper
__all__ = ['TNode', 'is_file_path', 'open_file']
def get_traceback(exc=None):
"""Get the exception traceback or the system traceback."""
_, _, sys_tb = sys.exc_info()... | 0.530966 | 0.126273 |
from six import text_type
from typing import Union
from zerver.lib.test_classes import WebhookTestCase
class BitbucketHookTests(WebhookTestCase):
STREAM_NAME = 'bitbucket'
URL_TEMPLATE = "/api/v1/external/bitbucket?payload={payload}&stream={stream}"
FIXTURE_DIR_NAME = 'bitbucket'
EXPECTED_SUBJECT = u"R... | zerver/webhooks/bitbucket/tests.py | from six import text_type
from typing import Union
from zerver.lib.test_classes import WebhookTestCase
class BitbucketHookTests(WebhookTestCase):
STREAM_NAME = 'bitbucket'
URL_TEMPLATE = "/api/v1/external/bitbucket?payload={payload}&stream={stream}"
FIXTURE_DIR_NAME = 'bitbucket'
EXPECTED_SUBJECT = u"R... | 0.615666 | 0.205675 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from scipy.stats import pearsonr, spearmanr
from seqeval.metrics import classification_report, precision_score, recall_score, f1_score
from sklearn.metrics import f1_score as classification_f1_score
def get_... | nlp_architect/utils/metrics.py |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from scipy.stats import pearsonr, spearmanr
from seqeval.metrics import classification_report, precision_score, recall_score, f1_score
from sklearn.metrics import f1_score as classification_f1_score
def get_... | 0.674694 | 0.606935 |
import os
import uuid
import hashlib
import json
import tempfile
import secrets
import zipfile
from glob import glob
from django.core.exceptions import ValidationError
from django.utils.module_loading import import_string
from django.conf import settings
from django.db import models
from django.utils.translation import... | django_walletpass/models.py | import os
import uuid
import hashlib
import json
import tempfile
import secrets
import zipfile
from glob import glob
from django.core.exceptions import ValidationError
from django.utils.module_loading import import_string
from django.conf import settings
from django.db import models
from django.utils.translation import... | 0.40028 | 0.069573 |
import datetime
from typing import Sequence
import requests
from bs4 import BeautifulSoup
from bot.currency import Currency
from .base import BaseParser
import logging
logger = logging.getLogger("bot.parsers.belgazprombank_parser")
class BelgazpromParser(BaseParser):
is_active = True
BASE_URL = 'http://be... | bot/parsers/belgazprombank_parser.py |
import datetime
from typing import Sequence
import requests
from bs4 import BeautifulSoup
from bot.currency import Currency
from .base import BaseParser
import logging
logger = logging.getLogger("bot.parsers.belgazprombank_parser")
class BelgazpromParser(BaseParser):
is_active = True
BASE_URL = 'http://be... | 0.761006 | 0.151781 |
import jsonlines
import spacy
import numpy as np
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from embedding import WordEmbeddingFeature
from sentiment_features import SentimentFeature
from bag_of_words import BagOfWordsFeature
from utils import WSCProblem
import argparse
def load_file(fil... | svm-rank/main.py | import jsonlines
import spacy
import numpy as np
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from embedding import WordEmbeddingFeature
from sentiment_features import SentimentFeature
from bag_of_words import BagOfWordsFeature
from utils import WSCProblem
import argparse
def load_file(fil... | 0.720663 | 0.307735 |
import argparse, textwrap
parser = argparse.ArgumentParser(
description=textwrap.dedent(
"""\
A python script to fetch submissions and comments using PRAW API
"""
),
usage='Use "python3 %(prog)s -h" for more information',
formatter_class=argparse.RawTextHelpFormatter,
... | args.py | import argparse, textwrap
parser = argparse.ArgumentParser(
description=textwrap.dedent(
"""\
A python script to fetch submissions and comments using PRAW API
"""
),
usage='Use "python3 %(prog)s -h" for more information',
formatter_class=argparse.RawTextHelpFormatter,
... | 0.405331 | 0.175467 |
import numpy as np
import matplotlib.pyplot as plt
import visa
import time
import math
class DSO6012A(object):
def __init__(self):
scopeID = "USB0::0x0957::0x1722::MY45002264::INSTR" # For DSO6012A
#scopeID = "USB0::0x0957::0x1798::MY54231293::INSTR" # For DSO-X-2014A
rm = visa.ResourceManager()
... | drivers/oscilloscope/dso6012a.py | import numpy as np
import matplotlib.pyplot as plt
import visa
import time
import math
class DSO6012A(object):
def __init__(self):
scopeID = "USB0::0x0957::0x1722::MY45002264::INSTR" # For DSO6012A
#scopeID = "USB0::0x0957::0x1798::MY54231293::INSTR" # For DSO-X-2014A
rm = visa.ResourceManager()
... | 0.150653 | 0.153486 |
from pyrpc import serializers
import json
from django.test import TestCase
class AppTestCase(TestCase):
def test_is_description_line(self):
line = 'Test'
assert(serializers.is_description_line(line))
line = '@param'
assert(not serializers.is_description_line(line))
... | tests/test_serializers.py | from pyrpc import serializers
import json
from django.test import TestCase
class AppTestCase(TestCase):
def test_is_description_line(self):
line = 'Test'
assert(serializers.is_description_line(line))
line = '@param'
assert(not serializers.is_description_line(line))
... | 0.773131 | 0.475727 |
import io
import re
from pathlib import Path
from typing import List, Tuple, Union
import h5py
import numpy
from mlxtk.tools.wave_function import get_spfs, load_wave_function
RE_TIME = re.compile(r"^\s+(.+)\s+\[au\]$")
RE_ELEMENT = re.compile(r"^\s*\((.+)\,(.+)\)$")
def read_first_frame(path: str) -> str:
fram... | mlxtk/inout/psi.py | import io
import re
from pathlib import Path
from typing import List, Tuple, Union
import h5py
import numpy
from mlxtk.tools.wave_function import get_spfs, load_wave_function
RE_TIME = re.compile(r"^\s+(.+)\s+\[au\]$")
RE_ELEMENT = re.compile(r"^\s*\((.+)\,(.+)\)$")
def read_first_frame(path: str) -> str:
fram... | 0.57678 | 0.322219 |
# coding: utf-8
"""
Submarine Experiment API
The Submarine REST API allows you to create, list, and get experiments. TheAPI is hosted under the /v1/jobs route on the Submarine server. For example,to list experiments on a server hosted at http://localhost:8080, accesshttp://localhost:8080/api/v1/jobs/ # noqa... | submarine-sdk/pysubmarine/submarine/job/models/job_spec.py |
# coding: utf-8
"""
Submarine Experiment API
The Submarine REST API allows you to create, list, and get experiments. TheAPI is hosted under the /v1/jobs route on the Submarine server. For example,to list experiments on a server hosted at http://localhost:8080, accesshttp://localhost:8080/api/v1/jobs/ # noqa... | 0.568416 | 0.16872 |
import ast
import numpy as np
def listify(obj):
"""Wrap all non-list or tuple objects in a list.
Provides a simple way to accept flexible arguments.
"""
if obj is None:
return []
else:
return obj if isinstance(obj, (list, tuple, type(None))) else [obj]
def spacify(string, n=2):... | bambi/utils.py | import ast
import numpy as np
def listify(obj):
"""Wrap all non-list or tuple objects in a list.
Provides a simple way to accept flexible arguments.
"""
if obj is None:
return []
else:
return obj if isinstance(obj, (list, tuple, type(None))) else [obj]
def spacify(string, n=2):... | 0.775945 | 0.445228 |
import logging
import os
import codecs
import random
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union, Dict
from filelock import FileLock
from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available, RobertaModel, BertPreTrainedModel, XLMRobertaConfi... | demo_srl_utils.py | import logging
import os
import codecs
import random
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union, Dict
from filelock import FileLock
from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available, RobertaModel, BertPreTrainedModel, XLMRobertaConfi... | 0.759448 | 0.439928 |
import logging
import os
import time
from typing import Dict, Optional
from eth_typing.evm import ChecksumAddress
from web3 import Web3
CONFIG_KEY_WEB3_INTERVAL = "web3_interval"
CONFIG_KEY_WEB3_LAST_CALL = "web3_last_call"
logger = logging.getLogger("moonworm.deployment")
VERBOSE = os.environ.get("MOONWORM_VERBOSE"... | moonworm/deployment.py | import logging
import os
import time
from typing import Dict, Optional
from eth_typing.evm import ChecksumAddress
from web3 import Web3
CONFIG_KEY_WEB3_INTERVAL = "web3_interval"
CONFIG_KEY_WEB3_LAST_CALL = "web3_last_call"
logger = logging.getLogger("moonworm.deployment")
VERBOSE = os.environ.get("MOONWORM_VERBOSE"... | 0.804636 | 0.088505 |
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from optbinning import OptimalBinning
import math
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
import plotly.express as px
def DistributionPlot(Df, PlotVar):
'''
Plots the distribution of a given variable ... | SpotifyFunctions.py | import pandas as pd
import numpy as np
import plotly.graph_objects as go
from optbinning import OptimalBinning
import math
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
import plotly.express as px
def DistributionPlot(Df, PlotVar):
'''
Plots the distribution of a given variable ... | 0.703142 | 0.486941 |
from time import sleep
import numpy as np
from json import loads
from .constant import CLOSE, SIZELAYERONE
from .qfunction import Qfunction
from .state import State
from .toolbox import Toolbox
from .dataset import Dataset
from .communication import Communication
import torch
__all__ = ["Agent"]
class Agent():
... | regularflow/utils_regularflow/agent.py | from time import sleep
import numpy as np
from json import loads
from .constant import CLOSE, SIZELAYERONE
from .qfunction import Qfunction
from .state import State
from .toolbox import Toolbox
from .dataset import Dataset
from .communication import Communication
import torch
__all__ = ["Agent"]
class Agent():
... | 0.249539 | 0.102484 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Plantain',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=... | debolemix/dbolemix/bolemix/migrations/0001_initial.py |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Plantain',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=... | 0.661267 | 0.197425 |
from __future__ import division
import math
import random
import collections
import numpy as np
import scipy.stats as ss
__all__ = [
'DiscreteDist',
'TruncatedZipfDist',
'means_confidence_interval',
'proportions_confidence_interval',
'cdf',
'pdf',
]
class Discr... | icarus/tools/stats.py | from __future__ import division
import math
import random
import collections
import numpy as np
import scipy.stats as ss
__all__ = [
'DiscreteDist',
'TruncatedZipfDist',
'means_confidence_interval',
'proportions_confidence_interval',
'cdf',
'pdf',
]
class Discr... | 0.913638 | 0.585931 |
import unittest
import numpy as np
from trajectory import ParallelTrajectory
class TestParallelTrajectory(unittest.TestCase):
def setUp(self):
self.trajectory = ParallelTrajectory(2)
def test_discounted_returns(self):
self.add_rewards(step=1, parallel_rewards=[1, 1], parallel_dones=[False, Fa... | soccer-twos-ppo/test_trajectory.py | import unittest
import numpy as np
from trajectory import ParallelTrajectory
class TestParallelTrajectory(unittest.TestCase):
def setUp(self):
self.trajectory = ParallelTrajectory(2)
def test_discounted_returns(self):
self.add_rewards(step=1, parallel_rewards=[1, 1], parallel_dones=[False, Fa... | 0.604516 | 0.692746 |
import threading
from oslo_log import log as logging
from kingbird.common import consts
from kingbird.common import exceptions
from kingbird.db.sqlalchemy import api as db_api
from kingbird.drivers.openstack import glance_adapter
from kingbird.drivers.openstack.glance_v2 import GlanceClient
from kingbird.drivers.ope... | kingbird/engine/image_sync_manager.py |
import threading
from oslo_log import log as logging
from kingbird.common import consts
from kingbird.common import exceptions
from kingbird.db.sqlalchemy import api as db_api
from kingbird.drivers.openstack import glance_adapter
from kingbird.drivers.openstack.glance_v2 import GlanceClient
from kingbird.drivers.ope... | 0.598195 | 0.095476 |
import threading
import time
import getpass
import rpyc
import urwid
# TODO global scope variable are evil
screen = None
class Service(rpyc.Service):
def on_connect(self):
global screen
if not screen:
return
screen.addSysMessage("Watcher connected")
def ... | debugger.py | import threading
import time
import getpass
import rpyc
import urwid
# TODO global scope variable are evil
screen = None
class Service(rpyc.Service):
def on_connect(self):
global screen
if not screen:
return
screen.addSysMessage("Watcher connected")
def ... | 0.118985 | 0.065425 |
class DataTable(object):
def __init__(self, colNames, rows):
if not colNames:
raise Exception("Error: Must pass column names to constructor.")
if not rows:
raise Exception("Error: Must rows to constructor.")
self._colNames = colNames
self._rows = rows
def getColumnNames(self):
return s... | HDMA/HDMA-SocialMediaAPI-dev/underConstruction/IntegrationAPI/pythonAPI/DataFactory/DataTable.py | class DataTable(object):
def __init__(self, colNames, rows):
if not colNames:
raise Exception("Error: Must pass column names to constructor.")
if not rows:
raise Exception("Error: Must rows to constructor.")
self._colNames = colNames
self._rows = rows
def getColumnNames(self):
return s... | 0.265214 | 0.255576 |
file = open('advent-day-19.txt',newline='')
inputdata = file.read().splitlines()
sample = ['0: 4 1 5','1: 2 3 | 3 2','2: 4 4 | 5 5','3: 4 5 | 5 4','4: "a"','5: "b"','',
'ababbb','bababa','abbbab','aaabbb','aaaabbb']
def format_input(inputdata):
rules = {}
for line in inputdata[:inputdata.index('')]:... | advent-day-19.py | file = open('advent-day-19.txt',newline='')
inputdata = file.read().splitlines()
sample = ['0: 4 1 5','1: 2 3 | 3 2','2: 4 4 | 5 5','3: 4 5 | 5 4','4: "a"','5: "b"','',
'ababbb','bababa','abbbab','aaabbb','aaaabbb']
def format_input(inputdata):
rules = {}
for line in inputdata[:inputdata.index('')]:... | 0.226784 | 0.359617 |
import dropbox
import json
import logging
import requests
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from allauth.socialaccount.models import SocialToken
from books.utils import DropboxParser
from libraries.models import LibraryImpo... | libraries/management/commands/run_import_job.py | import dropbox
import json
import logging
import requests
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from allauth.socialaccount.models import SocialToken
from books.utils import DropboxParser
from libraries.models import LibraryImpo... | 0.225929 | 0.039881 |
__author__ = '<NAME>'
import deploy
import unittest
class ArgParserTests(unittest.TestCase):
def setUp(self):
pass
def test_username_nopass(self):
error, args, config = deploy.parse_args(["-u", "bob"])
self.assertEqual('You need to specify either -l/--list or both -u/--username and -... | src/test_argparse.py | __author__ = '<NAME>'
import deploy
import unittest
class ArgParserTests(unittest.TestCase):
def setUp(self):
pass
def test_username_nopass(self):
error, args, config = deploy.parse_args(["-u", "bob"])
self.assertEqual('You need to specify either -l/--list or both -u/--username and -... | 0.229276 | 0.243721 |
import pytest
from app.services import reddit_service
from app.util.raffler import Raffler
from app.jobs.raffle_job import raffle
from app.db.models.raffle import Raffle
from tests.helpers import raffler_params
from tests.factories import UserFactory
@pytest.fixture(autouse=True)
def patch_raffler_class(monkeypatch)... | tests/jobs/test_raffle_job.py | import pytest
from app.services import reddit_service
from app.util.raffler import Raffler
from app.jobs.raffle_job import raffle
from app.db.models.raffle import Raffle
from tests.helpers import raffler_params
from tests.factories import UserFactory
@pytest.fixture(autouse=True)
def patch_raffler_class(monkeypatch)... | 0.494629 | 0.255048 |
import os
import sys
import time
import unittest
import k3proc
import k3ut
dd = k3ut.dd
this_base = os.path.dirname(__file__)
class TestProc(unittest.TestCase):
foo_fn = '/tmp/foo'
def _read_file(self, fn):
try:
with open(fn, 'r') as f:
cont = f.read()
... | k3proc/test/test_proc.py | import os
import sys
import time
import unittest
import k3proc
import k3ut
dd = k3ut.dd
this_base = os.path.dirname(__file__)
class TestProc(unittest.TestCase):
foo_fn = '/tmp/foo'
def _read_file(self, fn):
try:
with open(fn, 'r') as f:
cont = f.read()
... | 0.306735 | 0.211987 |
import os
import platform
import re
import shutil
import subprocess
import sys
from datetime import datetime
from typing import NoReturn
import packaging.version
import psutil
from executors.controls import restart
from executors.logger import logger
from modules.audio import listener, speaker
from modules.conditions... | executors/system.py | import os
import platform
import re
import shutil
import subprocess
import sys
from datetime import datetime
from typing import NoReturn
import packaging.version
import psutil
from executors.controls import restart
from executors.logger import logger
from modules.audio import listener, speaker
from modules.conditions... | 0.569374 | 0.204382 |
import unittest
from idblib import FileSection, binary_search, makeStringIO
class TestFileSection(unittest.TestCase):
""" unittest for FileSection object """
def test_file(self):
s = makeStringIO(b"0123456789abcdef")
fh = FileSection(s, 3, 11)
self.assertEqual(fh.read(3), b"345")
... | test_idblib.py | import unittest
from idblib import FileSection, binary_search, makeStringIO
class TestFileSection(unittest.TestCase):
""" unittest for FileSection object """
def test_file(self):
s = makeStringIO(b"0123456789abcdef")
fh = FileSection(s, 3, 11)
self.assertEqual(fh.read(3), b"345")
... | 0.594551 | 0.47658 |
import json
import pandas as pd
import numpy as np
import os
from os.path import isfile, join
import datetime
import matplotlib.pyplot as plt
project_dir = os.path.dirname(os.path.dirname(os.getcwd()))
out_path = os.path.join(project_dir, "data", "pecan")
fig_path = os.path.join(project_dir, "data", "pecan_info")
de... | load_data/anlyse_ps_data.py | import json
import pandas as pd
import numpy as np
import os
from os.path import isfile, join
import datetime
import matplotlib.pyplot as plt
project_dir = os.path.dirname(os.path.dirname(os.getcwd()))
out_path = os.path.join(project_dir, "data", "pecan")
fig_path = os.path.join(project_dir, "data", "pecan_info")
de... | 0.252661 | 0.245893 |
import os
import pickle
import warnings
from typing import Any, Dict, Optional, Union
import gym
import numpy as np
from stable_baselines3.common.callbacks import EventCallback, BaseCallback
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.vec_env import DummyVecEnv, VecEn... | sb3/stable_baselines_ex/common/callbacks_ex.py | import os
import pickle
import warnings
from typing import Any, Dict, Optional, Union
import gym
import numpy as np
from stable_baselines3.common.callbacks import EventCallback, BaseCallback
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.vec_env import DummyVecEnv, VecEn... | 0.852951 | 0.339198 |
import os
from enum import Enum
from typing import List, Optional
import PIL.Image
import matplotlib
import numpy
import tensorflow as tf
from matplotlib import pyplot as plt
TFHUB_MODEL_LOAD_FORMAT = 'TFHUB_MODEL_LOAD_FORMAT'
COMPRESSED = 'COMPRESSED'
FIGSIZE = 'figure.figsize'
GRID = 'axes.grid'
INPUT_PATH = 'Nemup... | src/main/python/utils.py | import os
from enum import Enum
from typing import List, Optional
import PIL.Image
import matplotlib
import numpy
import tensorflow as tf
from matplotlib import pyplot as plt
TFHUB_MODEL_LOAD_FORMAT = 'TFHUB_MODEL_LOAD_FORMAT'
COMPRESSED = 'COMPRESSED'
FIGSIZE = 'figure.figsize'
GRID = 'axes.grid'
INPUT_PATH = 'Nemup... | 0.873323 | 0.453262 |
from .context import Context
class Industry(Context):
class Patent(Context):
def list(self, year, mode, pref_code, city_code, patent_holder_id, sort1, sort2, offset, add_tec=[]):
param = {
'year': year,
'mode': mode,
'prefCode': pref_code,
... | resaspy/industry.py | from .context import Context
class Industry(Context):
class Patent(Context):
def list(self, year, mode, pref_code, city_code, patent_holder_id, sort1, sort2, offset, add_tec=[]):
param = {
'year': year,
'mode': mode,
'prefCode': pref_code,
... | 0.616705 | 0.203193 |
from copy import deepcopy
from dataclasses import dataclass
from typing import (
Any, Dict, Generic, Hashable, Iterator, List,
Mapping, MutableMapping, Tuple, TypeVar, Union
)
Key = TypeVar("Key")
Value = TypeVar("Value")
@dataclass
class KeyValue(Generic[Key, Value]):
"""
Element of Map for unhasha... | pycaches/nohashmap.py | from copy import deepcopy
from dataclasses import dataclass
from typing import (
Any, Dict, Generic, Hashable, Iterator, List,
Mapping, MutableMapping, Tuple, TypeVar, Union
)
Key = TypeVar("Key")
Value = TypeVar("Value")
@dataclass
class KeyValue(Generic[Key, Value]):
"""
Element of Map for unhasha... | 0.901692 | 0.329715 |
from string import ascii_lowercase, ascii_uppercase
from .errors import UnitExecutionError, UnitOutputError
# Caesar Cipher
def encode_caesar_cipher(message: str, key: int):
if not isinstance(message, str):
raise UnitExecutionError("message must be str")
if not isinstance(key, int):
raise UnitExecutionError("k... | units/cryptography.py | from string import ascii_lowercase, ascii_uppercase
from .errors import UnitExecutionError, UnitOutputError
# Caesar Cipher
def encode_caesar_cipher(message: str, key: int):
if not isinstance(message, str):
raise UnitExecutionError("message must be str")
if not isinstance(key, int):
raise UnitExecutionError("k... | 0.327991 | 0.108921 |
from __future__ import absolute_import, division, unicode_literals
from datetime import timedelta
import json
import re
import pywikibot
from pywikibot.bot import WikidataBot
from pywikibot.exceptions import (LockedPageError, NoCreateError, NoPageError, PageSaveRelatedError)
import logger
logger = logger.get_logger("b... | create_items_bot.py | from __future__ import absolute_import, division, unicode_literals
from datetime import timedelta
import json
import re
import pywikibot
from pywikibot.bot import WikidataBot
from pywikibot.exceptions import (LockedPageError, NoCreateError, NoPageError, PageSaveRelatedError)
import logger
logger = logger.get_logger("b... | 0.391406 | 0.122497 |
import random
import numpy as np
import mask
import sklearn
from joblib import Parallel, delayed
import tensorflow as tf
import losses
from Cube2Dataset import encode_mask
class ImageGenerator:
def __init__(self, image_names, gts, illuminants=2, size=(512, 1024), ang_dist=3, encode=True):
self.image_name... | collage_generator.py | import random
import numpy as np
import mask
import sklearn
from joblib import Parallel, delayed
import tensorflow as tf
import losses
from Cube2Dataset import encode_mask
class ImageGenerator:
def __init__(self, image_names, gts, illuminants=2, size=(512, 1024), ang_dist=3, encode=True):
self.image_name... | 0.541409 | 0.336672 |
from hashcash import check
import random
import string
import sys
import os
import SocketServer
import hashlib
import os
import subprocess
import socket
import sys
import threading
import codecs
import time
def readline(sock):
data = ''
while not data.endswith("\n"):
x = sock.recv(1)
if len(x) < 1... | src/pow.py | from hashcash import check
import random
import string
import sys
import os
import SocketServer
import hashlib
import os
import subprocess
import socket
import sys
import threading
import codecs
import time
def readline(sock):
data = ''
while not data.endswith("\n"):
x = sock.recv(1)
if len(x) < 1... | 0.210848 | 0.050261 |
import logging
import time
from apscheduler.schedulers.background import BackgroundScheduler
from zvt import init_log
from zvt.domain import *
from zvt.informer.informer import EmailInformer
logger = logging.getLogger(__name__)
sched = BackgroundScheduler()
@sched.scheduled_job('cron', hour=15, minute=30,day_of_w... | script/data_runner.py | import logging
import time
from apscheduler.schedulers.background import BackgroundScheduler
from zvt import init_log
from zvt.domain import *
from zvt.informer.informer import EmailInformer
logger = logging.getLogger(__name__)
sched = BackgroundScheduler()
@sched.scheduled_job('cron', hour=15, minute=30,day_of_w... | 0.313945 | 0.179279 |
from argparse import (
ArgumentParser,
Namespace,
)
import torch
from torch import nn
from torch.nn import functional as F
from utils.misc import optional_string
from .gaussian_smoothing import GaussianSmoothing
class DegradeArguments:
@staticmethod
def add_arguments(parser: ArgumentParser):
... | models/degrade.py | from argparse import (
ArgumentParser,
Namespace,
)
import torch
from torch import nn
from torch.nn import functional as F
from utils.misc import optional_string
from .gaussian_smoothing import GaussianSmoothing
class DegradeArguments:
@staticmethod
def add_arguments(parser: ArgumentParser):
... | 0.875999 | 0.552238 |
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from tinymce import models as tinymce_models
from taggit_autosuggest.managers import TaggableManager
from modelpage.current_user import get_curr... | modelpage/channel/models.py | from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from tinymce import models as tinymce_models
from taggit_autosuggest.managers import TaggableManager
from modelpage.current_user import get_curr... | 0.524882 | 0.106505 |
pgeocode_country_codes = {
'Andorra': 'AD',
'Argentina': 'AR',
'American Samoa': 'AS',
'Austria': 'AT',
'Australia': 'AU',
'Åland Islands': 'AX',
'Bangladesh': 'BD',
'Belgium': 'BE',
'Bulgaria': 'BG',
'Bermuda': 'BM',
'Brazil': 'BR',
'Belarus': 'BY',
'Canada': 'CA',
... | batch_geocoder/pgeocode_country_codes.py | pgeocode_country_codes = {
'Andorra': 'AD',
'Argentina': 'AR',
'American Samoa': 'AS',
'Austria': 'AT',
'Australia': 'AU',
'Åland Islands': 'AX',
'Bangladesh': 'BD',
'Belgium': 'BE',
'Bulgaria': 'BG',
'Bermuda': 'BM',
'Brazil': 'BR',
'Belarus': 'BY',
'Canada': 'CA',
... | 0.414069 | 0.407569 |
from datetime import timedelta
from typing import List, Optional, Tuple
import hypothesis.strategies as st
import numpy as np
import numpy.testing as npt
import pandas as pd
import pandas.testing as tm
import pyarrow as pa
import pytest
from hypothesis import example, given, settings
# fmt: off
import fletcher as fr
... | tests/test_algorithms.py | from datetime import timedelta
from typing import List, Optional, Tuple
import hypothesis.strategies as st
import numpy as np
import numpy.testing as npt
import pandas as pd
import pandas.testing as tm
import pyarrow as pa
import pytest
from hypothesis import example, given, settings
# fmt: off
import fletcher as fr
... | 0.88539 | 0.607081 |
from itertools import groupby
from pathlib import Path
from typing import List
from invoke import Result, task
from termcolor import cprint
from tasks.utils import PROJECT_INFO, ensure_reports_dir, paths_to_str, print_header, to_pathlib_path
_REPORTS_DIR = PROJECT_INFO.reports_directory / "typecheck/junit.xml"
def... | tasks/typecheck.py | from itertools import groupby
from pathlib import Path
from typing import List
from invoke import Result, task
from termcolor import cprint
from tasks.utils import PROJECT_INFO, ensure_reports_dir, paths_to_str, print_header, to_pathlib_path
_REPORTS_DIR = PROJECT_INFO.reports_directory / "typecheck/junit.xml"
def... | 0.648021 | 0.264985 |
import logging
from os import uname
from os.path import isfile
from time import time
from ast import literal_eval
import settings
from functions.filesystem.remove_file import remove_file
skyline_app = 'thunder'
skyline_app_logger = '%sLog' % skyline_app
logger = logging.getLogger(skyline_app_logger)
# The failover ... | skyline/functions/thunder/check_thunder_failover_key.py | import logging
from os import uname
from os.path import isfile
from time import time
from ast import literal_eval
import settings
from functions.filesystem.remove_file import remove_file
skyline_app = 'thunder'
skyline_app_logger = '%sLog' % skyline_app
logger = logging.getLogger(skyline_app_logger)
# The failover ... | 0.340156 | 0.090574 |
import random, math
#Removes leading zeros after decimal and/or approximate to 4dp
def trimval(thelist):
''' Takes in number list or float and removes leading zeros '''
if type(thelist) == list:
temp = []
for i in thelist:
if type(i) == int:
temp.append(i)
else:
temp.append(float('%.4f' % i))
the... | eventsim/discrete.py | import random, math
#Removes leading zeros after decimal and/or approximate to 4dp
def trimval(thelist):
''' Takes in number list or float and removes leading zeros '''
if type(thelist) == list:
temp = []
for i in thelist:
if type(i) == int:
temp.append(i)
else:
temp.append(float('%.4f' % i))
the... | 0.403567 | 0.410461 |
import theano
from theano import tensor as T
from theano.tensor.nnet import conv
import numpy as np
class HexConvLayer:
def __init__(self, rng, input, input_shape, num_D5_filters, num_D3_filters, params = None):
W3_bound = np.sqrt(6. / (7*(input_shape[1] + num_D3_filters)))
W5_bound = np.sqrt(6. / ... | layers.py | import theano
from theano import tensor as T
from theano.tensor.nnet import conv
import numpy as np
class HexConvLayer:
def __init__(self, rng, input, input_shape, num_D5_filters, num_D3_filters, params = None):
W3_bound = np.sqrt(6. / (7*(input_shape[1] + num_D3_filters)))
W5_bound = np.sqrt(6. / ... | 0.389082 | 0.573649 |
'''Game manager module.'''
# pylint: disable=fixme, line-too-long, invalid-name, undefined-variable
# pylint: disable=too-many-branches, too-many-statements, too-many-arguments
from random import randint
import pygame
from pygame.locals import * # pylint: disable=wildcard-import, unused-wildcard-import
from pygame.time... | manager.py | '''Game manager module.'''
# pylint: disable=fixme, line-too-long, invalid-name, undefined-variable
# pylint: disable=too-many-branches, too-many-statements, too-many-arguments
from random import randint
import pygame
from pygame.locals import * # pylint: disable=wildcard-import, unused-wildcard-import
from pygame.time... | 0.406391 | 0.169784 |
import types
from typing import Dict, Sequence
from pysaurus.core.functions import is_valid_attribute_name
from pysaurus.core.override import Override
__fn_types__ = (
types.FunctionType,
types.MethodType,
types.BuiltinMethodType,
types.BuiltinFunctionType,
types.ClassMethodDescriptorType,
cla... | pysaurus/core/jsonable.py | import types
from typing import Dict, Sequence
from pysaurus.core.functions import is_valid_attribute_name
from pysaurus.core.override import Override
__fn_types__ = (
types.FunctionType,
types.MethodType,
types.BuiltinMethodType,
types.BuiltinFunctionType,
types.ClassMethodDescriptorType,
cla... | 0.84241 | 0.24655 |
import xml.etree.ElementTree as ET
from collections import defaultdict
def _parse_node_names_single_file(filename: str) -> dict:
node_names = {}
tree = ET.parse(filename)
root = tree.getroot()
for node in root.findall("./graph/node"):
data = node.find("./data[@key='d0']")
node_id = n... | traceml_parser.py | import xml.etree.ElementTree as ET
from collections import defaultdict
def _parse_node_names_single_file(filename: str) -> dict:
node_names = {}
tree = ET.parse(filename)
root = tree.getroot()
for node in root.findall("./graph/node"):
data = node.find("./data[@key='d0']")
node_id = n... | 0.463687 | 0.247248 |
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from django.utils.decora... | server/apps/ota/views.py | import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from django.utils.decora... | 0.441191 | 0.063019 |
import tensorflow as tf
import math
import numpy as np
class Classifier(object):
def __init__(self, batch_size, network,
observation_dim=814,
learning_rate=3e-4,
optimizer=tf.train.AdamOptimizer,
image_ch_dim=1,
num_labels = 10,
... | models/classifier.py | import tensorflow as tf
import math
import numpy as np
class Classifier(object):
def __init__(self, batch_size, network,
observation_dim=814,
learning_rate=3e-4,
optimizer=tf.train.AdamOptimizer,
image_ch_dim=1,
num_labels = 10,
... | 0.841305 | 0.243316 |
from django.urls import path,re_path,include
from . import views
app_name='reviews.planning'
urlpatterns = [
re_path(r'^save_source/$', views.save_source, name='save_source'),
re_path(r'^remove_source/$', views.remove_source_from_review, name='remove_source_from_review'),
re_path(r'^suggested_sources/$', ... | parsifal/reviews/planning/urls.py |
from django.urls import path,re_path,include
from . import views
app_name='reviews.planning'
urlpatterns = [
re_path(r'^save_source/$', views.save_source, name='save_source'),
re_path(r'^remove_source/$', views.remove_source_from_review, name='remove_source_from_review'),
re_path(r'^suggested_sources/$', ... | 0.269902 | 0.073663 |
import mysql.connector
import os
class Uploader:
def __init__(self, extracted_data):
self.extracted_data = extracted_data
def upload(self):
self.connect()
self.insert()
self.close()
def connect(self):
root_pass = os.environ.get('MARIADB_ROOT_PASSWORD')
# r... | scraper_extractor/components/uploader.py | import mysql.connector
import os
class Uploader:
def __init__(self, extracted_data):
self.extracted_data = extracted_data
def upload(self):
self.connect()
self.insert()
self.close()
def connect(self):
root_pass = os.environ.get('MARIADB_ROOT_PASSWORD')
# r... | 0.252292 | 0.069542 |
"""DeeWebDemo: web server and front-end for Dee demoCluster"""
__version__ = "0.12"
__author__ = "<NAME>"
__copyright__ = "Copyright (C) 2007 <NAME>"
__license__ = "MIT" #see Licence.txt for licence information
import re
import webbrowser
import mimetypes
from Dee import *
from demoCluster import *
im... | DeeWebDemo.py | """DeeWebDemo: web server and front-end for Dee demoCluster"""
__version__ = "0.12"
__author__ = "<NAME>"
__copyright__ = "Copyright (C) 2007 <NAME>"
__license__ = "MIT" #see Licence.txt for licence information
import re
import webbrowser
import mimetypes
from Dee import *
from demoCluster import *
im... | 0.170854 | 0.099121 |
import urllib
import requests
import os
import base64
import uuid
import json
import asyncio
import eth_keys
import binascii
from Crypto.Hash import keccak
from .config import EdenConfig
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Utility functions
# Request for Gets
def req... | eden_client_api/api.py | import urllib
import requests
import os
import base64
import uuid
import json
import asyncio
import eth_keys
import binascii
from Crypto.Hash import keccak
from .config import EdenConfig
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Utility functions
# Request for Gets
def req... | 0.335677 | 0.080828 |
from rich import console
import untangle
import click
from typing import Tuple, List
from tempfile import TemporaryDirectory
from shutil import unpack_archive, copyfile
from os.path import join, isdir
from os import makedirs, getcwd
from rich.progress import track
from rich.console import Console
def shortname(fname:... | moodle_extract/main.py | from rich import console
import untangle
import click
from typing import Tuple, List
from tempfile import TemporaryDirectory
from shutil import unpack_archive, copyfile
from os.path import join, isdir
from os import makedirs, getcwd
from rich.progress import track
from rich.console import Console
def shortname(fname:... | 0.602529 | 0.279085 |
import asyncio, itertools, random, math
from app.utils.misc import convert_to_equiv_emoji_digits
from app.music.music import Music
from app.music.embed import MusicEmbed
class Playlist(asyncio.Queue):
def __init__(self, music_list: list=[], **kwargs):
super().__init__(**kwargs)
self.__page_q... | app/music/playlist.py | import asyncio, itertools, random, math
from app.utils.misc import convert_to_equiv_emoji_digits
from app.music.music import Music
from app.music.embed import MusicEmbed
class Playlist(asyncio.Queue):
def __init__(self, music_list: list=[], **kwargs):
super().__init__(**kwargs)
self.__page_q... | 0.646349 | 0.18054 |
"""Unit tests for the "create_workspace_activity_feed" module."""
import unittest
from unittest import mock
from google.auth.transport import requests
from . import create_workspace_activity_feed
class CreateFeedTest(unittest.TestCase):
@mock.patch.object(requests, "AuthorizedSession", autospec=True)
@mock.pa... | feeds/create_workspace_activity_feed_test.py | """Unit tests for the "create_workspace_activity_feed" module."""
import unittest
from unittest import mock
from google.auth.transport import requests
from . import create_workspace_activity_feed
class CreateFeedTest(unittest.TestCase):
@mock.patch.object(requests, "AuthorizedSession", autospec=True)
@mock.pa... | 0.751922 | 0.480296 |
from __future__ import print_function
import requests
import getpass
import time
import StringIO
import subprocess
import numpy as np
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def requests_retry_session(
retries=10,
backoff_factor=0.3,
status_forcelis... | scripts/mhealth_client.py | from __future__ import print_function
import requests
import getpass
import time
import StringIO
import subprocess
import numpy as np
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def requests_retry_session(
retries=10,
backoff_factor=0.3,
status_forcelis... | 0.604399 | 0.138753 |
from __future__ import absolute_import, unicode_literals, print_function
from email.utils import parseaddr
from zope.component import createObject
from gs.group.list.command import CommandResult, CommandABC
from gs.group.member.base import user_member_of_group
from gs.group.member.leave.base import leave_group
from Pro... | gs/group/member/leave/command/listcommand.py | from __future__ import absolute_import, unicode_literals, print_function
from email.utils import parseaddr
from zope.component import createObject
from gs.group.list.command import CommandResult, CommandABC
from gs.group.member.base import user_member_of_group
from gs.group.member.leave.base import leave_group
from Pro... | 0.521715 | 0.056731 |
import asyncio
from typing import List, TYPE_CHECKING, Any, Dict
from txdbus import client # type: ignore
from txdbus.objects import ( # type: ignore
DBusObject,
DBusProperty,
RemoteDBusObject
)
from txdbus.interface import DBusInterface, Property # type: ignore
from bleak.backends... | bless/backends/bluezdbus/dbus/service.py | import asyncio
from typing import List, TYPE_CHECKING, Any, Dict
from txdbus import client # type: ignore
from txdbus.objects import ( # type: ignore
DBusObject,
DBusProperty,
RemoteDBusObject
)
from txdbus.interface import DBusInterface, Property # type: ignore
from bleak.backends... | 0.817137 | 0.097734 |
import argparse
from pathlib import Path
import re
import subprocess
import sys
CPP_EXTENSIONS = ('.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx', '.h')
PY_EXTENSIONS = ('.py',)
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--py', action='store_true', default=Fals... | code_quality.py | import argparse
from pathlib import Path
import re
import subprocess
import sys
CPP_EXTENSIONS = ('.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx', '.h')
PY_EXTENSIONS = ('.py',)
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--py', action='store_true', default=Fals... | 0.294316 | 0.073364 |
import argparse
import logging
import textwrap
import solcx
import sys
from cliff.show import ShowOne
class SolcShow(ShowOne):
"""Show solc compiler information"""
log = logging.getLogger(__name__)
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.formatter... | ether_py/solc/show.py |
import argparse
import logging
import textwrap
import solcx
import sys
from cliff.show import ShowOne
class SolcShow(ShowOne):
"""Show solc compiler information"""
log = logging.getLogger(__name__)
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.formatter... | 0.298185 | 0.097519 |
from typing import Sequence, Any, Union
from pyexlatex.logic.format.sizing import adjust_to_full_size_and_center, adjust_to_size
from pyexlatex.presentation.beamer.frame.frame import Frame
from pyexlatex.figure.models.graphic import Graphic
from pyexlatex.models.format.fills import VFill, HFill
from pyexlatex.models.f... | pyexlatex/presentation/beamer/templates/frames/graphic.py | from typing import Sequence, Any, Union
from pyexlatex.logic.format.sizing import adjust_to_full_size_and_center, adjust_to_size
from pyexlatex.presentation.beamer.frame.frame import Frame
from pyexlatex.figure.models.graphic import Graphic
from pyexlatex.models.format.fills import VFill, HFill
from pyexlatex.models.f... | 0.932191 | 0.394901 |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List
from reamber.osu.OsuSample import OsuSample
from reamber.osu.OsuSampleSet import OsuSampleSet
from reamber.osu.lists.OsuSampleList import OsuSampleList
class OsuMapMode:
""" This determines the mode of the map.
... | reamber/osu/OsuMapMeta.py | from __future__ import annotations
from dataclasses import dataclass, field
from typing import List
from reamber.osu.OsuSample import OsuSample
from reamber.osu.OsuSampleSet import OsuSampleSet
from reamber.osu.lists.OsuSampleList import OsuSampleList
class OsuMapMode:
""" This determines the mode of the map.
... | 0.737347 | 0.41324 |
import dolfinx.fem as _fem
import numpy as np
import pytest
from dolfinx.graph import create_adjacencylist
from dolfinx.io import XDMFFile
from dolfinx.mesh import meshtags, locate_entities_boundary
from mpi4py import MPI
import dolfinx_contact
import dolfinx_contact.cpp
from dolfinx_contact.meshing import convert_me... | python/tests/test_projection.py |
import dolfinx.fem as _fem
import numpy as np
import pytest
from dolfinx.graph import create_adjacencylist
from dolfinx.io import XDMFFile
from dolfinx.mesh import meshtags, locate_entities_boundary
from mpi4py import MPI
import dolfinx_contact
import dolfinx_contact.cpp
from dolfinx_contact.meshing import convert_me... | 0.601594 | 0.480905 |
import scipy.optimize as spo
import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime as dt
plt.style.use("ggplot")
# selected equities and time frame
stocks = ["AAPL", "GOOG", "TSLA", "BABA", "ETH-USD"]
start = dt(2017, 12, 31)
end = dt(2021, 1, 1)
... | portfolio_optimiser/optimiser.py | import scipy.optimize as spo
import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime as dt
plt.style.use("ggplot")
# selected equities and time frame
stocks = ["AAPL", "GOOG", "TSLA", "BABA", "ETH-USD"]
start = dt(2017, 12, 31)
end = dt(2021, 1, 1)
... | 0.796055 | 0.654577 |
class Hash:
#funcion inicial, con esta funcion siempre se va
#a iniciar cuando llamemos a un objeto de la clase
#en este caso se inicia un arreglo vacio con un tamanio fijo
#para caso practico el tamanio sera de 5
def __init__(self):
self.size = 5
self.map = [None] * self.size
# _get_pos, es el metodo con ... | tarea1/Hash_Directory.py |
class Hash:
#funcion inicial, con esta funcion siempre se va
#a iniciar cuando llamemos a un objeto de la clase
#en este caso se inicia un arreglo vacio con un tamanio fijo
#para caso practico el tamanio sera de 5
def __init__(self):
self.size = 5
self.map = [None] * self.size
# _get_pos, es el metodo con ... | 0.16848 | 0.629234 |
from Common.hive_connection import HiveConnection
import time
from Common.helper import format_two_point_time, sql_to_string
class Interpolation:
def __init__(self, config):
self.config = config
self.hc = HiveConnection()
def calculate_interpolation(self):
self.convert_cdr_to_array_fo... | Common/cdr_interpolation.py | from Common.hive_connection import HiveConnection
import time
from Common.helper import format_two_point_time, sql_to_string
class Interpolation:
def __init__(self, config):
self.config = config
self.hc = HiveConnection()
def calculate_interpolation(self):
self.convert_cdr_to_array_fo... | 0.440108 | 0.12603 |
from PyQt5.QtCore import QObject, pyqtSignal
from deriva.core import format_exception
from deriva.transfer import DerivaUpload
from deriva.qt import async_execute, Task
class UploadTask(QObject):
status_update_signal = pyqtSignal(bool, str, str, object)
progress_update_signal = pyqtSignal(int, int)
def _... | Lib/site-packages/deriva/qt/upload_gui/impl/upload_tasks.py | from PyQt5.QtCore import QObject, pyqtSignal
from deriva.core import format_exception
from deriva.transfer import DerivaUpload
from deriva.qt import async_execute, Task
class UploadTask(QObject):
status_update_signal = pyqtSignal(bool, str, str, object)
progress_update_signal = pyqtSignal(int, int)
def _... | 0.677474 | 0.266975 |
import json
import io
import sqlalchemy as sa
from sqlalchemy.inspection import inspect
import pandas as pd
from datetime import datetime
from collections import OrderedDict
from pyramid.traversal import find_root
from pyramid.response import Response
from zope.interface import implementer
from . import Base
from ..c... | Back/ecoreleve_server/core/base_resource.py | import json
import io
import sqlalchemy as sa
from sqlalchemy.inspection import inspect
import pandas as pd
from datetime import datetime
from collections import OrderedDict
from pyramid.traversal import find_root
from pyramid.response import Response
from zope.interface import implementer
from . import Base
from ..c... | 0.564098 | 0.097864 |
import random
import inspect
import urlparse
import traceback
from collections import Iterable
from pkgutil import iter_modules
import gevent
from gevent import Greenlet
from crawler.http import Request, Response
from crawler.queue import Empty
class Spider(Greenlet):
name = None
allowed_domains = []
st... | crawler/spider.py | import random
import inspect
import urlparse
import traceback
from collections import Iterable
from pkgutil import iter_modules
import gevent
from gevent import Greenlet
from crawler.http import Request, Response
from crawler.queue import Empty
class Spider(Greenlet):
name = None
allowed_domains = []
st... | 0.255437 | 0.053651 |
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn import ModeKeys
from rgat.datasets import rdf
def sp2tfsp(x):
coo = x.tocoo()
indices = np.mat([coo.row, coo.col]).transpose()
return tf.SparseTensor(indices, coo.data, coo.shape)
def get_input_fn(
mode,
dataset_n... | examples/rdf/inputs.py | import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn import ModeKeys
from rgat.datasets import rdf
def sp2tfsp(x):
coo = x.tocoo()
indices = np.mat([coo.row, coo.col]).transpose()
return tf.SparseTensor(indices, coo.data, coo.shape)
def get_input_fn(
mode,
dataset_n... | 0.876951 | 0.489931 |
import os, itertools
from data_read.imarisfiles import ImarisFiles
from config import system
import argparse
import numpy as np
import urllib
import zipfile
import logging
import pandas as pd
import glob
logging.getLogger(__name__)
def shift_list(seq, n):
n = n % len(seq)
return seq if n == 0 else seq[n:] ... | MiNTiF_Utils/utils/common_utils.py | import os, itertools
from data_read.imarisfiles import ImarisFiles
from config import system
import argparse
import numpy as np
import urllib
import zipfile
import logging
import pandas as pd
import glob
logging.getLogger(__name__)
def shift_list(seq, n):
n = n % len(seq)
return seq if n == 0 else seq[n:] ... | 0.318273 | 0.175009 |
from django import forms
from ummeli.opportunities.models import *
from ummeli.vlive.forms import PMLModelForm, PMLForm
class StatusUpdateForm(PMLForm):
title = forms.CharField(label='Status', required=True, max_length=160)
class JobEditForm(PMLModelForm):
province = forms.ModelChoiceField(empty_label=None,... | ummeli/vlive/community/forms.py | from django import forms
from ummeli.opportunities.models import *
from ummeli.vlive.forms import PMLModelForm, PMLForm
class StatusUpdateForm(PMLForm):
title = forms.CharField(label='Status', required=True, max_length=160)
class JobEditForm(PMLModelForm):
province = forms.ModelChoiceField(empty_label=None,... | 0.485112 | 0.090816 |
from alembic import op, context
import sqlalchemy as sa
from rucio.db.sqla.constants import DIDType
from rucio.db.sqla.types import GUID
# revision identifiers, used by Alembic.
revision = '3ad36e2268b0'
down_revision = '42db2617c364'
def upgrade():
if context.get_context().dialect.name != 'sqlite':
op.... | lib/rucio/db/sqla/migrate_repo/versions/3ad36e2268b0_create_collection_replicas_updates_table.py | from alembic import op, context
import sqlalchemy as sa
from rucio.db.sqla.constants import DIDType
from rucio.db.sqla.types import GUID
# revision identifiers, used by Alembic.
revision = '3ad36e2268b0'
down_revision = '42db2617c364'
def upgrade():
if context.get_context().dialect.name != 'sqlite':
op.... | 0.303525 | 0.076788 |
import torch
import torch.nn as nn
from ove.utils.modeling import Sequential
from ..networks import (
FilterInterpolationModule, DepthFlowProjectionModule,
MultipleBasicBlock, S2DF, PWCDCNet, HourGlass
)
from ..utils import Stack
class DAIN_slowmotion(nn.Module):
def __init__(
self,
... | ove/algorithm/dain/models/DAIN_slowmotion.py | import torch
import torch.nn as nn
from ove.utils.modeling import Sequential
from ..networks import (
FilterInterpolationModule, DepthFlowProjectionModule,
MultipleBasicBlock, S2DF, PWCDCNet, HourGlass
)
from ..utils import Stack
class DAIN_slowmotion(nn.Module):
def __init__(
self,
... | 0.813127 | 0.329823 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accura... | Avocado_price_prediction.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accura... | 0.557966 | 0.412116 |