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 typing import ByteString, Union
from dempy._protofiles import SampleListMessage
from dempy.acquisitions.image_sample import ImageSample
from dempy.acquisitions.timeseries_sample import TimeseriesSample
from dempy.acquisitions.video_sample import VideoSample
class SampleList(list):
"""Wrapper list class with... | dempy/acquisitions/_utils.py | from typing import ByteString, Union
from dempy._protofiles import SampleListMessage
from dempy.acquisitions.image_sample import ImageSample
from dempy.acquisitions.timeseries_sample import TimeseriesSample
from dempy.acquisitions.video_sample import VideoSample
class SampleList(list):
"""Wrapper list class with... | 0.932553 | 0.341253 |
import torch
import torchvision
import torch.nn as nn
class DoubleConvBlock(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size=3):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, padding='valid'),
... | project/models/unet.py | import torch
import torchvision
import torch.nn as nn
class DoubleConvBlock(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size=3):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, padding='valid'),
... | 0.961642 | 0.472014 |
import sys
import requests
from enum import Enum, auto, unique
from time import sleep
from uuid import uuid4
import re
@unique
class OPCODE(Enum):
def _generate_next_value_(name, start, count, last_values):
return name
def __str__(self):
return self.name
OP_PUSH = auto()
OP_POP = au... | sploits/sputnik_v8/memory_leak.py |
import sys
import requests
from enum import Enum, auto, unique
from time import sleep
from uuid import uuid4
import re
@unique
class OPCODE(Enum):
def _generate_next_value_(name, start, count, last_values):
return name
def __str__(self):
return self.name
OP_PUSH = auto()
OP_POP = au... | 0.299003 | 0.084947 |
from abc import abstractmethod
import torch
class TensorTree:
"""
Generalised version of tensor. As like as tensor, it represents an object of some data type,
but also stores information about it's structure. Every layer of tree stores tensor, which
values represent one layer of data structure and li... | src/main/python/runtime/trees/tensor_tree.py | from abc import abstractmethod
import torch
class TensorTree:
"""
Generalised version of tensor. As like as tensor, it represents an object of some data type,
but also stores information about it's structure. Every layer of tree stores tensor, which
values represent one layer of data structure and li... | 0.898773 | 0.441793 |
__all__ = ['Ring', 'CommutativeRing']
from ..basealgebra import Algebra
from .interface import RingInterface
from ..core import init_module, classes
init_module.import_heads()
init_module.import_numbers()
@init_module
def _init(m):
from ..arithmetic import mpq
Ring.coefftypes = (int, long, mpq)
class Ring(A... | sympycore/ring/algebra.py | __all__ = ['Ring', 'CommutativeRing']
from ..basealgebra import Algebra
from .interface import RingInterface
from ..core import init_module, classes
init_module.import_heads()
init_module.import_numbers()
@init_module
def _init(m):
from ..arithmetic import mpq
Ring.coefftypes = (int, long, mpq)
class Ring(A... | 0.681197 | 0.107437 |
import tile_generators
__author__ = "<NAME> and <NAME>"
__copyright__ = "Copyright 2017, The University of Queensland"
__license__ = "MIT"
__version__ = "1.1.2"
import model
import game_regular
from modules.weighted_selector import WeightedSelector
class LevelTile(model.AbstractTile):
"""Tile whose value & type... | game_make13.py | import tile_generators
__author__ = "<NAME> and <NAME>"
__copyright__ = "Copyright 2017, The University of Queensland"
__license__ = "MIT"
__version__ = "1.1.2"
import model
import game_regular
from modules.weighted_selector import WeightedSelector
class LevelTile(model.AbstractTile):
"""Tile whose value & type... | 0.836788 | 0.339034 |
import os
import socket
import venusian
from botocore.exceptions import ClientError
from flowy.swf.client import SWFClient, IDENTITY_SIZE
from flowy.swf.decision import SWFActivityDecision
from flowy.swf.decision import SWFWorkflowDecision
from flowy.swf.history import SWFExecutionHistory
from flowy.utils import logg... | flowy/swf/worker.py | import os
import socket
import venusian
from botocore.exceptions import ClientError
from flowy.swf.client import SWFClient, IDENTITY_SIZE
from flowy.swf.decision import SWFActivityDecision
from flowy.swf.decision import SWFWorkflowDecision
from flowy.swf.history import SWFExecutionHistory
from flowy.utils import logg... | 0.621656 | 0.103386 |
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.core.mail import message
from django.core.paginator import Paginator
from django.shortcuts import render
from django.urls import reverse_lazy
from djang... | src/trains/views.py | from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.core.mail import message
from django.core.paginator import Paginator
from django.shortcuts import render
from django.urls import reverse_lazy
from djang... | 0.40439 | 0.084606 |
import base64
from decimal import Decimal
import gettext
import hashlib
import os.path
import flask
import werkzeug.routing
import werkzeug.utils
from api import api
from player import player
from root import root
from sql import db_connect, db_init, get_db, put_db
class DefaultConfig:
DATABASE = "postgresql://... | trends.py |
import base64
from decimal import Decimal
import gettext
import hashlib
import os.path
import flask
import werkzeug.routing
import werkzeug.utils
from api import api
from player import player
from root import root
from sql import db_connect, db_init, get_db, put_db
class DefaultConfig:
DATABASE = "postgresql://... | 0.462473 | 0.06767 |
class ListNode:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
def __repr__(self):
return repr(self.data)
class CircularDoublyLinkedList:
def __init__(self, list):
# Keep track of all the nodes to save look-u... | 2020/day23-2.py | class ListNode:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
def __repr__(self):
return repr(self.data)
class CircularDoublyLinkedList:
def __init__(self, list):
# Keep track of all the nodes to save look-u... | 0.690559 | 0.351395 |
import pickle
import plotly.express as px
import numpy as np
import gspread_dataframe as gd
import pandas as pd
from scipy.spatial.distance import pdist, squareform
def get_raw_data(context):
_query = '''
SELECT
*
FROM
`moz-fx-data-shared-prod.regrets_reporter_analysis.yt_a... | semanticdist/utils.py | import pickle
import plotly.express as px
import numpy as np
import gspread_dataframe as gd
import pandas as pd
from scipy.spatial.distance import pdist, squareform
def get_raw_data(context):
_query = '''
SELECT
*
FROM
`moz-fx-data-shared-prod.regrets_reporter_analysis.yt_a... | 0.363534 | 0.320476 |
from rdflib import Graph, URIRef, Namespace, Literal
from rdflib.namespace import FOAF, SKOS, DCTERMS
import requests
import json
links = ['http://onomy.org/published/73/skos',
'http://onomy.org/published/74/skos',
'https://onomy.org/published/83/skos',
'http://onomy.org/published/... | pyfusekiutil/convert_rdf_json.py | from rdflib import Graph, URIRef, Namespace, Literal
from rdflib.namespace import FOAF, SKOS, DCTERMS
import requests
import json
links = ['http://onomy.org/published/73/skos',
'http://onomy.org/published/74/skos',
'https://onomy.org/published/83/skos',
'http://onomy.org/published/... | 0.386879 | 0.201656 |
import configparser
from utils import Crawler as CoreCrawler
class Crawler(CoreCrawler):
abbr = 'LA'
def _get_remote_filename(self, local_filename):
if local_filename.startswith('City of '):
directory = 'General Purpose'
name = local_filename.replace('City of ', '')
el... | get_LA.py | import configparser
from utils import Crawler as CoreCrawler
class Crawler(CoreCrawler):
abbr = 'LA'
def _get_remote_filename(self, local_filename):
if local_filename.startswith('City of '):
directory = 'General Purpose'
name = local_filename.replace('City of ', '')
el... | 0.233532 | 0.053552 |
import sys
from functools import reduce
from typing import Dict, Iterable, List, MutableMapping, Tuple
class Direction:
NORTH: str = "^"
SOUTH: str = "v"
EAST: str = ">"
WEST: str = "<"
def present_to_house(
direction: str,
cur_loc: Tuple[int, int],
visited_house_coordinates: MutableMapp... | aoc_2015/day_3/python/day3_puzzle.py | import sys
from functools import reduce
from typing import Dict, Iterable, List, MutableMapping, Tuple
class Direction:
NORTH: str = "^"
SOUTH: str = "v"
EAST: str = ">"
WEST: str = "<"
def present_to_house(
direction: str,
cur_loc: Tuple[int, int],
visited_house_coordinates: MutableMapp... | 0.534127 | 0.368463 |
import unittest
from binx.utils import bfs_shortest_path, ObjUtils, RecordUtils, DataFrameDtypeConversion
import pandas as pd
from pandas.testing import assert_frame_equal
import numpy as np
from marshmallow import fields
from datetime import datetime, date
class TestUtils(unittest.TestCase):
def setUp(self):
... | tests/test_utils.py | import unittest
from binx.utils import bfs_shortest_path, ObjUtils, RecordUtils, DataFrameDtypeConversion
import pandas as pd
from pandas.testing import assert_frame_equal
import numpy as np
from marshmallow import fields
from datetime import datetime, date
class TestUtils(unittest.TestCase):
def setUp(self):
... | 0.435661 | 0.644854 |
from multiprocessing import context
from django.shortcuts import render,redirect
from django.contrib.auth import login, authenticate,logout
from django.contrib.auth.models import User
from .models import Profile
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms im... | users/views.py | from multiprocessing import context
from django.shortcuts import render,redirect
from django.contrib.auth import login, authenticate,logout
from django.contrib.auth.models import User
from .models import Profile
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms im... | 0.334481 | 0.059183 |
import os
import sys
import enum
import textwrap
from cryptography.fernet import Fernet
import environ
from environ._environ_config import _env_to_bool
def split_by_comma(value):
return tuple(e.strip() for e in value.split(","))
@environ.config(prefix="")
class NoeConfig:
debug = environ.bool_var(
d... | code/backend/project_noe/config.py | import os
import sys
import enum
import textwrap
from cryptography.fernet import Fernet
import environ
from environ._environ_config import _env_to_bool
def split_by_comma(value):
return tuple(e.strip() for e in value.split(","))
@environ.config(prefix="")
class NoeConfig:
debug = environ.bool_var(
d... | 0.322206 | 0.077588 |
import six
import asyncio
import struct
import json
from autobahn.asyncio.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
class TickerClientProtocol(WebSocketClientProtocol):
""" Kite ticker autobahn WebSocket base protocol """
def onConnect(self, response):
"""
Called ... | async_ticker.py | import six
import asyncio
import struct
import json
from autobahn.asyncio.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
class TickerClientProtocol(WebSocketClientProtocol):
""" Kite ticker autobahn WebSocket base protocol """
def onConnect(self, response):
"""
Called ... | 0.59749 | 0.154887 |
import allocate
# Function to decode parsed instruction into it's binary equivalents
def decoder(field1, field2, field3, labels):
binString = ""
if field1.isdigit() and field2 == "" and field3 == "":
binString = toBinary(field1)
elif (field2.isalnum() and field3.isalpha()) or (field1.isalpha() and field... | Project 6/assembler/Decoder.py | import allocate
# Function to decode parsed instruction into it's binary equivalents
def decoder(field1, field2, field3, labels):
binString = ""
if field1.isdigit() and field2 == "" and field3 == "":
binString = toBinary(field1)
elif (field2.isalnum() and field3.isalpha()) or (field1.isalpha() and field... | 0.270191 | 0.323621 |
import json
import os
import unittest
from unittest import mock
from django import test
from django.conf import settings
from django.urls import reverse
import webtest
from config import wsgi
class TestBasicViews(test.TestCase):
def test_code_of_conduct(self):
response = self.client.get(reverse("code-of... | pythonsd/tests/__init__.py | import json
import os
import unittest
from unittest import mock
from django import test
from django.conf import settings
from django.urls import reverse
import webtest
from config import wsgi
class TestBasicViews(test.TestCase):
def test_code_of_conduct(self):
response = self.client.get(reverse("code-of... | 0.578091 | 0.305568 |
from service.models import RoutedNotification, Account
import os
from octopus.lib import clcsv
from copy import deepcopy
from datetime import datetime
from octopus.core import app
def delivery_report(from_date, to_date, reportfile):
"""
Generate the monthly report from from_date to to_date. It is assumed that... | service/reports.py | from service.models import RoutedNotification, Account
import os
from octopus.lib import clcsv
from copy import deepcopy
from datetime import datetime
from octopus.core import app
def delivery_report(from_date, to_date, reportfile):
"""
Generate the monthly report from from_date to to_date. It is assumed that... | 0.353651 | 0.364947 |
from ROOT import *
gROOT.SetBatch()
gROOT.LoadMacro( "AtlasStyle.C" )
gROOT.LoadMacro( "AtlasLabels.C" )
SetAtlasStyle()
#====================================================
# FUNCTION TO MAKE CANVAS
#====================================================
def MakeCanvas( split = 0.25 ):
c = TCanvas( "DataPredic... | scripts/python/data analysis/impact parameters/compare_plots.py | from ROOT import *
gROOT.SetBatch()
gROOT.LoadMacro( "AtlasStyle.C" )
gROOT.LoadMacro( "AtlasLabels.C" )
SetAtlasStyle()
#====================================================
# FUNCTION TO MAKE CANVAS
#====================================================
def MakeCanvas( split = 0.25 ):
c = TCanvas( "DataPredic... | 0.413359 | 0.160496 |
# pyright: reportGeneralTypeIssues=false
# pylint: disable=C0103,C0301,E0401,R0912,R0913,R0914,R0915
from math import log, pow, sqrt # pylint: disable=W0622
from typing import Union
import numpy
import xarray
from numba import guvectorize, njit
from numba.core.types import float64, int16, int32, uint8
@njit
def ws2... | seasmon_xr/ops/whit.py | # pyright: reportGeneralTypeIssues=false
# pylint: disable=C0103,C0301,E0401,R0912,R0913,R0914,R0915
from math import log, pow, sqrt # pylint: disable=W0622
from typing import Union
import numpy
import xarray
from numba import guvectorize, njit
from numba.core.types import float64, int16, int32, uint8
@njit
def ws2... | 0.741768 | 0.474814 |
from PIL import Image
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
"""
prcessImage - colors the edges of the image and saves it to the 'result' folder
@ARGS
path (utf string) - the path of the original image [ default - path to sample image ]
Mu (int) -... | main.py | from PIL import Image
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
"""
prcessImage - colors the edges of the image and saves it to the 'result' folder
@ARGS
path (utf string) - the path of the original image [ default - path to sample image ]
Mu (int) -... | 0.313 | 0.458106 |
from uuid import UUID
class Identifier:
def __init__(self, value: UUID) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
if isinstance(other, Identifier):
if isinstance(other, type(self)) or isinstance(self, type(other)):
if isinstance(other.val... | src/fbsrankings/common/identifier.py | from uuid import UUID
class Identifier:
def __init__(self, value: UUID) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
if isinstance(other, Identifier):
if isinstance(other, type(self)) or isinstance(self, type(other)):
if isinstance(other.val... | 0.639511 | 0.116161 |
import argparse
import copy
import glob
import json
import os
from .core import GTAB
dir_path = os.path.dirname(os.path.abspath(__file__))
# --- UTILITY METHODS ---
class GroupedAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
group, dest = self.dest.split('.'... | gtab/command_line.py | import argparse
import copy
import glob
import json
import os
from .core import GTAB
dir_path = os.path.dirname(os.path.abspath(__file__))
# --- UTILITY METHODS ---
class GroupedAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
group, dest = self.dest.split('.'... | 0.327883 | 0.091342 |
import npd
import utilities
import csv
def format_data(input_path: str, output_directory: str, entries: dict):
csv_data = {}
for key in entries:
csv_data[key] = []
with open(input_path, "r") as file:
line_total = len(file.readlines())
with open(input_path, "r") as file:
for ... | Python/format_npd.py | import npd
import utilities
import csv
def format_data(input_path: str, output_directory: str, entries: dict):
csv_data = {}
for key in entries:
csv_data[key] = []
with open(input_path, "r") as file:
line_total = len(file.readlines())
with open(input_path, "r") as file:
for ... | 0.407687 | 0.277069 |
import os
import time
from cryptojwt.jws import factory
from oidcmsg.key_jar import KeyJar
from oidcmsg.oidc import RegistrationRequest
from fedoidcmsg.signing_service import InternalSigningService
from fedoidcmsg.signing_service import WebSigningServiceClient
from fedoidcmsg.signing_service import make_internal_sign... | tests/test_05_signing_service.py | import os
import time
from cryptojwt.jws import factory
from oidcmsg.key_jar import KeyJar
from oidcmsg.oidc import RegistrationRequest
from fedoidcmsg.signing_service import InternalSigningService
from fedoidcmsg.signing_service import WebSigningServiceClient
from fedoidcmsg.signing_service import make_internal_sign... | 0.448909 | 0.322766 |
import pytest
import random
import json
import os
from assets import resource
def test_send_no_thread():
test_message = str(random.getrandbits(128))
code, message = resource.send("https://httpbin.org/post", test_message, False)
assert code == 200
assert test_message in message
def test_send_thread()... | test_resource.py | import pytest
import random
import json
import os
from assets import resource
def test_send_no_thread():
test_message = str(random.getrandbits(128))
code, message = resource.send("https://httpbin.org/post", test_message, False)
assert code == 200
assert test_message in message
def test_send_thread()... | 0.345547 | 0.301908 |
# (c)2021 .direwolf <<EMAIL>>
# Licensed under the MIT License.
from typing import Callable, Iterable, List, Literal
from arcfutil.aff.note.notegroup import TimingGroup
from ..note import Arc
from ..note import NoteGroup
from ..note import SceneControl
from ..note import Timing
from random import randint
from ...exce... | src/arcfutil/aff/generator/arc_sample.py |
# (c)2021 .direwolf <<EMAIL>>
# Licensed under the MIT License.
from typing import Callable, Iterable, List, Literal
from arcfutil.aff.note.notegroup import TimingGroup
from ..note import Arc
from ..note import NoteGroup
from ..note import SceneControl
from ..note import Timing
from random import randint
from ...exce... | 0.71423 | 0.341335 |
import wx
from kurier.interfaces import IStateRestorable
from kurier.widgets.list_ctrl import EditableListCtrl
class RequestHeadersTab(IStateRestorable, wx.Panel):
USED_COLUMNS = ["Header name", "Value"]
UTILITY_ROW_TEXT = "Click here for adding a new user header..."
def __init__(self, *args, **kwargs):... | kurier/widgets/request/headers.py | import wx
from kurier.interfaces import IStateRestorable
from kurier.widgets.list_ctrl import EditableListCtrl
class RequestHeadersTab(IStateRestorable, wx.Panel):
USED_COLUMNS = ["Header name", "Value"]
UTILITY_ROW_TEXT = "Click here for adding a new user header..."
def __init__(self, *args, **kwargs):... | 0.289271 | 0.079246 |
from __future__ import absolute_import, unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Count, F, Q
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_pr... | shopit/models/modifier.py | from __future__ import absolute_import, unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Count, F, Q
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_pr... | 0.783575 | 0.143698 |
import pyfastaq
from varifier import edit_distance
class Probe:
def __init__(self, seq, allele_start, allele_end):
self.seq = seq
self.allele_start = allele_start
self.allele_end = allele_end
def __str__(self):
return f"{self.seq} {self.allele_start} {self.allele_end}"
d... | varifier/probe.py | import pyfastaq
from varifier import edit_distance
class Probe:
def __init__(self, seq, allele_start, allele_end):
self.seq = seq
self.allele_start = allele_start
self.allele_end = allele_end
def __str__(self):
return f"{self.seq} {self.allele_start} {self.allele_end}"
d... | 0.695855 | 0.267199 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Base(object):
"""Abstract base class for TF RL environments.
The `current_time_step()` method returns current `time_step`, resetting the
envi... | tf_agents/environments/tf_environment.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Base(object):
"""Abstract base class for TF RL environments.
The `current_time_step()` method returns current `time_step`, resetting the
envi... | 0.946448 | 0.572842 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
import unittest
import tempfile
from typing import Type, Tuple
import h5py
import numpy as np
from sidpy import Dataset, Dimension
sys.path.append("../pyNSID/")
from pyNSID.io.hdf_io impo... | tests/io/test_nsi_reader.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
import unittest
import tempfile
from typing import Type, Tuple
import h5py
import numpy as np
from sidpy import Dataset, Dimension
sys.path.append("../pyNSID/")
from pyNSID.io.hdf_io impo... | 0.541894 | 0.299726 |
import os
import sys
import tempfile
from test.pytest_execute import InProcessExecution
from project_summarizer.__main__ import main
from project_summarizer.main import ProjectSummarizer
JUNIT_COMMAND_LINE_FLAG = "--junit"
COBERTURA_COMMAND_LINE_FLAG = "--cobertura"
PUBLISH_COMMAND_LINE_FLAG = "--publish"
ONLY_CHANG... | test/test_scenarios.py | import os
import sys
import tempfile
from test.pytest_execute import InProcessExecution
from project_summarizer.__main__ import main
from project_summarizer.main import ProjectSummarizer
JUNIT_COMMAND_LINE_FLAG = "--junit"
COBERTURA_COMMAND_LINE_FLAG = "--cobertura"
PUBLISH_COMMAND_LINE_FLAG = "--publish"
ONLY_CHANG... | 0.365117 | 0.113432 |
import asyncio
import json
from typing import Any
from typing import Mapping
import requests
from telliot.datafeed.data_feed import DataFeed
from telliot.reporter.base import Reporter
from telliot.submitter.base import Submitter
from telliot.utils.abi import tellor_playground_abi
from web3 import Web3
# T... | src/telliot/reporter/simple_interval.py | import asyncio
import json
from typing import Any
from typing import Mapping
import requests
from telliot.datafeed.data_feed import DataFeed
from telliot.reporter.base import Reporter
from telliot.submitter.base import Submitter
from telliot.utils.abi import tellor_playground_abi
from web3 import Web3
# T... | 0.522933 | 0.213152 |
import logging
import sys
import pandas as pd
import glob
import os
import atools
def main():
if (not len(sys.argv) == 4):
print("""
Usage: sort_structures.py DB_file output_file file_type
DB_file (str) - file with initial list of REFCODEs
output_file (str) - file to output results of ... | sort_structures.py | import logging
import sys
import pandas as pd
import glob
import os
import atools
def main():
if (not len(sys.argv) == 4):
print("""
Usage: sort_structures.py DB_file output_file file_type
DB_file (str) - file with initial list of REFCODEs
output_file (str) - file to output results of ... | 0.119987 | 0.156781 |
from geetools import batch
from ipywidgets import *
class toAsset(VBox):
def __init__(self, **kwargs):
super(toAsset, self).__init__(**kwargs)
layout = Layout(width='500px')
self.bapwidget = kwargs.get('bapwidget')
self.root = kwargs.get('root', '')
self.scale = Text(descri... | geecomposite/widgets/export.py | from geetools import batch
from ipywidgets import *
class toAsset(VBox):
def __init__(self, **kwargs):
super(toAsset, self).__init__(**kwargs)
layout = Layout(width='500px')
self.bapwidget = kwargs.get('bapwidget')
self.root = kwargs.get('root', '')
self.scale = Text(descri... | 0.755817 | 0.167797 |
from PIL import Image, ImageFilter
from colormath.color_objects import LabColor, sRGBColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
import json, operator
# close enough for now
lab_def_colors = {
"red": { 'l': 5140.11747498726, 'a': 5854.540388686413, '... | color.py | from PIL import Image, ImageFilter
from colormath.color_objects import LabColor, sRGBColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
import json, operator
# close enough for now
lab_def_colors = {
"red": { 'l': 5140.11747498726, 'a': 5854.540388686413, '... | 0.372277 | 0.354573 |
from datetime import datetime
import pytest
import pytz
import textwrap
import app
SCHEDULE_LINK = 'https://camph.net/schedule/'
class TestEvent:
def test_from_json(self):
tz = pytz.timezone("Asia/Tokyo")
d = {
"start": "2015-11-02T17:00:00+09:00",
"end": "2015-11-02T20:... | tests/test_app.py | from datetime import datetime
import pytest
import pytz
import textwrap
import app
SCHEDULE_LINK = 'https://camph.net/schedule/'
class TestEvent:
def test_from_json(self):
tz = pytz.timezone("Asia/Tokyo")
d = {
"start": "2015-11-02T17:00:00+09:00",
"end": "2015-11-02T20:... | 0.33231 | 0.5526 |
import setup
import scapy.all as scapy
import subprocess
import re
import time
def greet():
subprocess.call(["clear"])
print("ARP Spoofer 0.01 [MITM] by Ravehorn\n")
def ifconfig():
print("Running ifconfig:\n")
subprocess.call(["ifconfig"])
interface = input("Interface -> ")
print("\n")
... | arp_spoof.py | import setup
import scapy.all as scapy
import subprocess
import re
import time
def greet():
subprocess.call(["clear"])
print("ARP Spoofer 0.01 [MITM] by Ravehorn\n")
def ifconfig():
print("Running ifconfig:\n")
subprocess.call(["ifconfig"])
interface = input("Interface -> ")
print("\n")
... | 0.209389 | 0.093471 |
from tqdm import tqdm
import pandas as pd
import numpy as np
import os
os.chdir("/media/data/bderinbay/rvc_devkit/datasets/json_file/")
df_cats = pd.read_csv('categories.csv')
df_images = pd.read_csv('images.csv')
df_anno = pd.read_csv('annotations.csv')
sample_columns = ['image_id','bbox','category_id', 'category_... | scripts/dataset_sampler/json_sampler_v1_saved.py | from tqdm import tqdm
import pandas as pd
import numpy as np
import os
os.chdir("/media/data/bderinbay/rvc_devkit/datasets/json_file/")
df_cats = pd.read_csv('categories.csv')
df_images = pd.read_csv('images.csv')
df_anno = pd.read_csv('annotations.csv')
sample_columns = ['image_id','bbox','category_id', 'category_... | 0.174551 | 0.157008 |
import numpy as np
class BaseGenetics(object):
def __init__(self, e=None):
self.estimator = None
self.expectations = e # vector of math expectations for each component
def set_estimator(self, f):
def g(*args, **kwargs):
return f(*args, **kwargs)
self.estimat... | synthesis_repo/genetic_opt.py | import numpy as np
class BaseGenetics(object):
def __init__(self, e=None):
self.estimator = None
self.expectations = e # vector of math expectations for each component
def set_estimator(self, f):
def g(*args, **kwargs):
return f(*args, **kwargs)
self.estimat... | 0.604516 | 0.599778 |
def xyz2ll(x,y,z):
i_r = 1/numpy.sqrt(x*x + y*y + z*z)
sinlat = z*i_r
recip_coslat = 1/numpy.sqrt(1 - sinlat**2)
sinlon = (y*i_r)*recip_coslat
coslon = (x*i_r)*recip_coslat
rad2deg = 180/numpy.pi
lat = numpy.arcsin(sinlat)*rad2deg
sgn = numpy.maximum(numpy.sign(coslon),0)
lon0 = nump... | figure-scripts/some-projections.py | def xyz2ll(x,y,z):
i_r = 1/numpy.sqrt(x*x + y*y + z*z)
sinlat = z*i_r
recip_coslat = 1/numpy.sqrt(1 - sinlat**2)
sinlon = (y*i_r)*recip_coslat
coslon = (x*i_r)*recip_coslat
rad2deg = 180/numpy.pi
lat = numpy.arcsin(sinlat)*rad2deg
sgn = numpy.maximum(numpy.sign(coslon),0)
lon0 = nump... | 0.588534 | 0.646628 |
from cached_property import cached_property
from onegov.core.elements import Link
from onegov.wtfs import _
from onegov.wtfs.layouts.default import DefaultLayout
class ReportLayout(DefaultLayout):
@cached_property
def title(self):
return _("Report")
@cached_property
def breadcrumbs(self):
... | src/onegov/wtfs/layouts/report.py | from cached_property import cached_property
from onegov.core.elements import Link
from onegov.wtfs import _
from onegov.wtfs.layouts.default import DefaultLayout
class ReportLayout(DefaultLayout):
@cached_property
def title(self):
return _("Report")
@cached_property
def breadcrumbs(self):
... | 0.778607 | 0.095898 |
import operator
from xml.etree import ElementTree as ET
import cStringIO as StringIO
import json
from twisted.trial import unittest
from twisted.internet import defer, tcp
from twisted.web import resource, server
from twisted.web.test import requesthelper
from reqpi.robot import hash as rrhash
from zope.interface i... | reqpi/test/test_robot/test_hash.py | import operator
from xml.etree import ElementTree as ET
import cStringIO as StringIO
import json
from twisted.trial import unittest
from twisted.internet import defer, tcp
from twisted.web import resource, server
from twisted.web.test import requesthelper
from reqpi.robot import hash as rrhash
from zope.interface i... | 0.5083 | 0.186576 |
from enum import Enum
from uuid import UUID
from pydantic.types import constr, conint
from app import create_api_router, VoteDefinition, VoteAggregation
def most_voted(mongo_votes):
values = dict()
for mongo_vote in mongo_votes:
if mongo_vote["value"] in values:
values[mongo_vote["value"]... | app/routers/climbs.py | from enum import Enum
from uuid import UUID
from pydantic.types import constr, conint
from app import create_api_router, VoteDefinition, VoteAggregation
def most_voted(mongo_votes):
values = dict()
for mongo_vote in mongo_votes:
if mongo_vote["value"] in values:
values[mongo_vote["value"]... | 0.390011 | 0.163179 |
# Admin script for managing vent
import time
import socket
import requests
import logging
from multiprocessing import Value
import board
import digitalio
from adafruit_motorkit import MotorKit
import rpi2c
from actuator import peep
from sensor import sensor
from sensor.sensor_d6f import FlowSensorD6F
from sensor.se... | admin.py |
# Admin script for managing vent
import time
import socket
import requests
import logging
from multiprocessing import Value
import board
import digitalio
from adafruit_motorkit import MotorKit
import rpi2c
from actuator import peep
from sensor import sensor
from sensor.sensor_d6f import FlowSensorD6F
from sensor.se... | 0.225331 | 0.211417 |
import datetime
import json
from math import ceil
from dev01_22_19.data.characters.base import *
from roengine.game.recording import RecordingPlayer
class CustomPlayer(RecordingPlayer):
def apply_packet(self, packet, actual_time, expected_time):
bullets._bullets = pygame.sprite.Group(*[DummyBullet(i, sel... | dev01_22_19/replay_player.py | import datetime
import json
from math import ceil
from dev01_22_19.data.characters.base import *
from roengine.game.recording import RecordingPlayer
class CustomPlayer(RecordingPlayer):
def apply_packet(self, packet, actual_time, expected_time):
bullets._bullets = pygame.sprite.Group(*[DummyBullet(i, sel... | 0.25174 | 0.201754 |
import time
import pandas as pd
from model.utils import *
def dhp(line, h, d):
recall = int(line[0])
interval = int(line[1])
if recall == 1:
if interval == 0:
h = cal_start_halflife(d)
else:
p_recall = np.exp2(- interval / h)
h = cal_recall_halflife(d, h... | model/dhp.py | import time
import pandas as pd
from model.utils import *
def dhp(line, h, d):
recall = int(line[0])
interval = int(line[1])
if recall == 1:
if interval == 0:
h = cal_start_halflife(d)
else:
p_recall = np.exp2(- interval / h)
h = cal_recall_halflife(d, h... | 0.296145 | 0.240273 |
import logging
import platform
import sched, threading
import subprocess
from django.http import HttpResponseForbidden
from django.http.request import QueryDict
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from utils import Status
from utils.typecheck import ensure_typ... | frontend/api.py | import logging
import platform
import sched, threading
import subprocess
from django.http import HttpResponseForbidden
from django.http.request import QueryDict
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from utils import Status
from utils.typecheck import ensure_typ... | 0.617859 | 0.119923 |
import os
import sys
import random
import socket
import select
import datetime
import threading
lock = threading.RLock(); os.system('cls' if os.name == 'nt' else 'clear')
def real_path(file_name):
return os.path.dirname(os.path.abspath(__file__)) + file_name
def filter_array(array):
for i in ra... | app.py | import os
import sys
import random
import socket
import select
import datetime
import threading
lock = threading.RLock(); os.system('cls' if os.name == 'nt' else 'clear')
def real_path(file_name):
return os.path.dirname(os.path.abspath(__file__)) + file_name
def filter_array(array):
for i in ra... | 0.103635 | 0.089733 |
import timeboard as tb
import datetime
import pytest
import pandas as pd
class TestVersion(object):
def test_version(self):
version = tb.read_from('VERSION.txt')
assert version == tb.__version__
class TestTBConstructor(object):
def test_tb_constructor_trivial(self):
clnd = tb.Timeboa... | timeboard/tests/test_timeboard.py | import timeboard as tb
import datetime
import pytest
import pandas as pd
class TestVersion(object):
def test_version(self):
version = tb.read_from('VERSION.txt')
assert version == tb.__version__
class TestTBConstructor(object):
def test_tb_constructor_trivial(self):
clnd = tb.Timeboa... | 0.622459 | 0.616157 |
import pygame
class Controller:
def __init__(self, number):
self.number = number
self.joystick = None
if number <= pygame.joystick.get_count()-1:
self.joystick = pygame.joystick.Joystick(number)
self.joystick.init()
self.name = self.joystick.get_name()
... | gamma/controller.py | import pygame
class Controller:
def __init__(self, number):
self.number = number
self.joystick = None
if number <= pygame.joystick.get_count()-1:
self.joystick = pygame.joystick.Joystick(number)
self.joystick.init()
self.name = self.joystick.get_name()
... | 0.419767 | 0.091382 |
from typing import Optional
import config
import pandas as pd
import plotly.express as px
from pandas import DataFrame
from plotly.graph_objs import Figure
__all__ = [
"plot_auc_dist",
"plot_auc_scatter",
"plot_pr_curve_per_organism",
"plot_pr_scatter",
"plot_score_boxplot",
]
XRANGE = [-0.05, 1.... | iseq_prof_analysis/baseline/plot.py | from typing import Optional
import config
import pandas as pd
import plotly.express as px
from pandas import DataFrame
from plotly.graph_objs import Figure
__all__ = [
"plot_auc_dist",
"plot_auc_scatter",
"plot_pr_curve_per_organism",
"plot_pr_scatter",
"plot_score_boxplot",
]
XRANGE = [-0.05, 1.... | 0.947332 | 0.3694 |
import os
from pathlib import Path
import shutil
"""------[ Class ]---------"""
class UtilsFichier():
def __init__(self, repertoire='', fichier=''):
self.c_fic = fichier
self.c_dir = repertoire
def isCheminExiste(self, c_dir="") -> bool:
"""Test si le répertoire existe."""
... | UtilsDR/utils.py |
import os
from pathlib import Path
import shutil
"""------[ Class ]---------"""
class UtilsFichier():
def __init__(self, repertoire='', fichier=''):
self.c_fic = fichier
self.c_dir = repertoire
def isCheminExiste(self, c_dir="") -> bool:
"""Test si le répertoire existe."""
... | 0.310172 | 0.274991 |
import os
import subprocess
networks = {}
class Network(object):
def __init__(self, key, networkName):
self.key = key
self.networkName = networkName
self.connectedContainer = {}
self.netemInitialized = {}
def isNetemInitialized(self, container):
return self.netemInitia... | docker-network-simulator/actions/networkActions.py | import os
import subprocess
networks = {}
class Network(object):
def __init__(self, key, networkName):
self.key = key
self.networkName = networkName
self.connectedContainer = {}
self.netemInitialized = {}
def isNetemInitialized(self, container):
return self.netemInitia... | 0.243373 | 0.122576 |
# The network address to bind the server socket to
# Use "localhost" to restrict access from the local machine.
SERVER_ADDRESS = ""
# The TCP port to listen to
SERVER_PORT = 9099
# The base path for the API. Do not forget the trailing "/"!
# This the path that the front-end web server will redirect request to this ... | hcds_config.py |
# The network address to bind the server socket to
# Use "localhost" to restrict access from the local machine.
SERVER_ADDRESS = ""
# The TCP port to listen to
SERVER_PORT = 9099
# The base path for the API. Do not forget the trailing "/"!
# This the path that the front-end web server will redirect request to this ... | 0.722135 | 0.547525 |
from pathlib import Path
import cloudinary
import cloudinary.uploader
import cloudinary.api
from dotenv import load_dotenv
import dj_database_url
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
import os
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'sub... | UltronCRM/settings.py | from pathlib import Path
import cloudinary
import cloudinary.uploader
import cloudinary.api
from dotenv import load_dotenv
import dj_database_url
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
import os
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'sub... | 0.470737 | 0.062847 |
import os
import sys
sys.path.append(os.getcwd())
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from src.DataReader import *
from src.Visualiser import *
from src.Trader import *
from test.MCS import *
reader = DataReader("./resources/DAT_XLSX_USDZAR_M1_2019.csv")
# reader = DataReader("./re... | main.py | import os
import sys
sys.path.append(os.getcwd())
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from src.DataReader import *
from src.Visualiser import *
from src.Trader import *
from test.MCS import *
reader = DataReader("./resources/DAT_XLSX_USDZAR_M1_2019.csv")
# reader = DataReader("./re... | 0.476336 | 0.201813 |
from __future__ import annotations
import asyncio
import functools
import socket
import typing
def log_exceptions(msg="unhandled exception in {__func__}"):
"""
decorator that will catch all exceptions in methods and coroutine methods
and log them with self.log
msg will be formatted with __func__ as ... | src/someip/utils.py | from __future__ import annotations
import asyncio
import functools
import socket
import typing
def log_exceptions(msg="unhandled exception in {__func__}"):
"""
decorator that will catch all exceptions in methods and coroutine methods
and log them with self.log
msg will be formatted with __func__ as ... | 0.639624 | 0.088505 |
import logging
import random
import string
import sys
import unittest
from time import time, sleep
import apiritif
import os
import re
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains ... | tests/resources/selenium/generated_from_requests_remote.py |
import logging
import random
import string
import sys
import unittest
from time import time, sleep
import apiritif
import os
import re
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains ... | 0.170473 | 0.054853 |
# Number Of Worms, Length Of HP Each Worm Needs To Create, Length Of Each Worm and Diameter Of Each Worm
import math
# Possible Constants Related To Worms
MinLOHP = # ly
# MinLOHP means Minimum Length Of Hyperspace Pathway.
MaxLOHP = # ly
# MaxLOHP means Maximum Length Of HP.
MSDBITOHP = 0.0001369863 # ly
# MSDBITO... | number_of_worms,_length_of_HP_each_worm_needs_to_create,_length_of_each_worm_and_diameter_of_each_worm.py |
# Number Of Worms, Length Of HP Each Worm Needs To Create, Length Of Each Worm and Diameter Of Each Worm
import math
# Possible Constants Related To Worms
MinLOHP = # ly
# MinLOHP means Minimum Length Of Hyperspace Pathway.
MaxLOHP = # ly
# MaxLOHP means Maximum Length Of HP.
MSDBITOHP = 0.0001369863 # ly
# MSDBITO... | 0.435902 | 0.519278 |
import argparse
import numpy as np
import os
import sys
import random
import torch
from replaybuffer import ReplayBuffer
from network import LinearNetwork, ConvNetwork
class Agent(object):
"""Agent is defined here
"""
def __init__(self, args):
self.is_training = not args.eval
... | agent.py | import argparse
import numpy as np
import os
import sys
import random
import torch
from replaybuffer import ReplayBuffer
from network import LinearNetwork, ConvNetwork
class Agent(object):
"""Agent is defined here
"""
def __init__(self, args):
self.is_training = not args.eval
... | 0.444083 | 0.20834 |
import numpy as np
epsilon = 10e-10
kmax = 10000
def identity_minus(A, nr):
X = A * -1
for i in range(len(X)):
X[i, i] = nr + X[i, i]
return X
def identity_plus(A, nr):
for i in range(len(A)):
A[i, i] = A[i, i] + nr
return A
def get_solution_norm(A):
max_sum_line = 0
f... | hw5/main.py | import numpy as np
epsilon = 10e-10
kmax = 10000
def identity_minus(A, nr):
X = A * -1
for i in range(len(X)):
X[i, i] = nr + X[i, i]
return X
def identity_plus(A, nr):
for i in range(len(A)):
A[i, i] = A[i, i] + nr
return A
def get_solution_norm(A):
max_sum_line = 0
f... | 0.285671 | 0.411702 |
import argparse
def parse_args(args):
""" Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')
subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')
subparsers.required =... | yolk/parser.py | import argparse
def parse_args(args):
""" Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')
subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')
subparsers.required =... | 0.630912 | 0.239505 |
from flask import request
from flask_jwt_extended import get_jwt_identity, jwt_required
from flask_restful import Resource
from ...models import Collaboration
from ...schemas import CollaborationSchema
from .responses import respond
class CollaborationListResource(Resource):
@jwt_required
def get(self):
... | api/resources/v1/collaborations.py | from flask import request
from flask_jwt_extended import get_jwt_identity, jwt_required
from flask_restful import Resource
from ...models import Collaboration
from ...schemas import CollaborationSchema
from .responses import respond
class CollaborationListResource(Resource):
@jwt_required
def get(self):
... | 0.50708 | 0.159839 |
import os
import argparse
import xmltodict
import json
import requests
from concurrent.futures import ThreadPoolExecutor
MAX_WORKERS = 10
ENDPOINT = 'https://explorecourses.stanford.edu/'
DEPARMENTS_ENDPOINT = ENDPOINT + '?view=xml-20140630'
COURSE_ENDPOINT = (ENDPOINT + 'search?view=xml-20140630&academicYear='
... | scraper/fetch.py | import os
import argparse
import xmltodict
import json
import requests
from concurrent.futures import ThreadPoolExecutor
MAX_WORKERS = 10
ENDPOINT = 'https://explorecourses.stanford.edu/'
DEPARMENTS_ENDPOINT = ENDPOINT + '?view=xml-20140630'
COURSE_ENDPOINT = (ENDPOINT + 'search?view=xml-20140630&academicYear='
... | 0.263126 | 0.082438 |
import tensorflow as tf
from official.transformer.model import attention_layer, ffn_layer, transformer, model_utils, model_params
from tensor2tensor.models.research import universal_transformer, universal_transformer_util
from tensor2tensor.models import transformer as t2t_transformer
def create(params, transformer_p... | model/transformers.py | import tensorflow as tf
from official.transformer.model import attention_layer, ffn_layer, transformer, model_utils, model_params
from tensor2tensor.models.research import universal_transformer, universal_transformer_util
from tensor2tensor.models import transformer as t2t_transformer
def create(params, transformer_p... | 0.949517 | 0.311401 |
from settings import *
from athera.api import groups
import unittest
import uuid
from requests import codes
import os
class GroupsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.token = os.getenv("ATHERA_API_TEST_TOKEN")
if not cls.token:
raise ValueError("ATHERA_API... | test/api/test_groups.py | from settings import *
from athera.api import groups
import unittest
import uuid
from requests import codes
import os
class GroupsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.token = os.getenv("ATHERA_API_TEST_TOKEN")
if not cls.token:
raise ValueError("ATHERA_API... | 0.651355 | 0.35421 |
from flask import flash, redirect, session, url_for, current_app, Markup
from flask_user import current_user
from flask_login import login_user
from app.oauth.orcid_flask_dance import make_orcid_blueprint
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_dance.consumer.storage.sqla import SQLAlc... | app/oauth/orcid_blueprint.py | from flask import flash, redirect, session, url_for, current_app, Markup
from flask_user import current_user
from flask_login import login_user
from app.oauth.orcid_flask_dance import make_orcid_blueprint
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_dance.consumer.storage.sqla import SQLAlc... | 0.399343 | 0.095349 |
import os
from squirrel.shared.squirrelerror import SquirrelError
from bvzlocalization import LocalizedResource
class KeyValuePairs(object):
"""
A class to manage a specific metadata (key=value pairs) file within an asset.
"""
# -----------------------------------------------------------------------... | src/squirrel/asset/keyvaluepairs.py | import os
from squirrel.shared.squirrelerror import SquirrelError
from bvzlocalization import LocalizedResource
class KeyValuePairs(object):
"""
A class to manage a specific metadata (key=value pairs) file within an asset.
"""
# -----------------------------------------------------------------------... | 0.63023 | 0.269314 |
import h5py
import numpy as np
from multiprocess import cpu_count, Pool
from concurrent.futures import ThreadPoolExecutor
import os
from functools import partial
from tqdm import tqdm
from .features import Feature
from .crud import _add, _load, H5_NONE, SRC_KEY, apply_and_store
from .utils import flatten_dict
__all... | h5mapper/create.py | import h5py
import numpy as np
from multiprocess import cpu_count, Pool
from concurrent.futures import ThreadPoolExecutor
import os
from functools import partial
from tqdm import tqdm
from .features import Feature
from .crud import _add, _load, H5_NONE, SRC_KEY, apply_and_store
from .utils import flatten_dict
__all... | 0.357343 | 0.184768 |
import sys
import time
class ProgressBar:
def __init__(self, bar_length, total_steps, unit, lines_subplot):
self.bar_length = bar_length
self.total_steps = total_steps
self.unit = unit
self.lines_subplot = lines_subplot
def _up(self, step=1):
# My term... | se_tools/benchmark_scripts/_progress_bar.py |
import sys
import time
class ProgressBar:
def __init__(self, bar_length, total_steps, unit, lines_subplot):
self.bar_length = bar_length
self.total_steps = total_steps
self.unit = unit
self.lines_subplot = lines_subplot
def _up(self, step=1):
# My term... | 0.279042 | 0.198569 |
# https://github.com/regilero/check_burp_backup_age
# check_burp_backup_age: Local check, Check freshness of last backup for
# a given host name.
import sys
import os
import argparse
import time
import datetime
class CheckBurp(object):
def __init__(self):
self._program = "check_burp_backup_age"
... | localsettings_monitoring/files/check_burp_backup_age.py |
# https://github.com/regilero/check_burp_backup_age
# check_burp_backup_age: Local check, Check freshness of last backup for
# a given host name.
import sys
import os
import argparse
import time
import datetime
class CheckBurp(object):
def __init__(self):
self._program = "check_burp_backup_age"
... | 0.326271 | 0.21214 |
import random
import timeit
import random
# sort the given list
# first of all create test samples
test0 = {'input_list': [0, 2, 3, -5, 23, -42],
'output_list': [-42, -5, 0, 2, 3, 23]}
test1 = {'input_list': [3, 5, 6, 8, 9, 10, 99],
'output_list': [3, 5, 6, 8, 9, 10, 99]}
test2 = {'input_list': [99, 1... | bubble_sort/bubble_sort_exercise.py | import random
import timeit
import random
# sort the given list
# first of all create test samples
test0 = {'input_list': [0, 2, 3, -5, 23, -42],
'output_list': [-42, -5, 0, 2, 3, 23]}
test1 = {'input_list': [3, 5, 6, 8, 9, 10, 99],
'output_list': [3, 5, 6, 8, 9, 10, 99]}
test2 = {'input_list': [99, 1... | 0.118449 | 0.392279 |
import os
import os.path
from StrengthTest import StrengthTest
settings = 'settings.txt'
def prompt(again=None):
yesno = " [Yes/No] "
ask = ""
if again == None:
ask = "Would you like to run the test now?" + yesno
else:
ask = "Would you like to run the test again?" + yesno... | StrengthTestApp.py |
import os
import os.path
from StrengthTest import StrengthTest
settings = 'settings.txt'
def prompt(again=None):
yesno = " [Yes/No] "
ask = ""
if again == None:
ask = "Would you like to run the test now?" + yesno
else:
ask = "Would you like to run the test again?" + yesno... | 0.069704 | 0.069668 |
import copy
import mock
import os
import sys
import tempfile
from contextlib import contextmanager
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from mock import call
from magnumclient import exceptions
from magnumclient.osc.v1 import clusters as osc_clusters
from magnumclien... | magnumclient/tests/osc/unit/v1/test_clusters.py |
import copy
import mock
import os
import sys
import tempfile
from contextlib import contextmanager
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from mock import call
from magnumclient import exceptions
from magnumclient.osc.v1 import clusters as osc_clusters
from magnumclien... | 0.520253 | 0.257255 |
import pandas as pd
from datamonster_api import DataGroupColumn
def assert_object_matches_data_group(data_group, data_group_obj):
assert data_group_obj["_id"] == data_group.id
assert data_group_obj["name"] == data_group.name
assert len(data_group_obj["columns"]) == len(data_group.columns)
dg_col_name_... | datamonster_api/tests/lib/test_data_group.py | import pandas as pd
from datamonster_api import DataGroupColumn
def assert_object_matches_data_group(data_group, data_group_obj):
assert data_group_obj["_id"] == data_group.id
assert data_group_obj["name"] == data_group.name
assert len(data_group_obj["columns"]) == len(data_group.columns)
dg_col_name_... | 0.655667 | 0.729869 |
import thread, redis
from kafka import SimpleProducer, KafkaClient
from flask import Flask, session
from flask.ext.session import Session
from query_subscriber import QuerySubscriber
from views import attach_views
from datetime import datetime
def highlight(word):
return("<span style=\"background-color: #FFFF00\">... | src/frontend/app/straw_app.py | import thread, redis
from kafka import SimpleProducer, KafkaClient
from flask import Flask, session
from flask.ext.session import Session
from query_subscriber import QuerySubscriber
from views import attach_views
from datetime import datetime
def highlight(word):
return("<span style=\"background-color: #FFFF00\">... | 0.321141 | 0.097176 |
import os
import numpy as np
import tensorflow as tf
from datetime import datetime
from skimage import img_as_int, io
from unet.unet_components import weight_init, bias_init, conv2d, max_pool, deconv2d, crop_and_copy
from unet.loss import dice_loss
from unet.metrics import mean_iou
from utils import get_imgs_masks, get... | unet/unet_model.py | import os
import numpy as np
import tensorflow as tf
from datetime import datetime
from skimage import img_as_int, io
from unet.unet_components import weight_init, bias_init, conv2d, max_pool, deconv2d, crop_and_copy
from unet.loss import dice_loss
from unet.metrics import mean_iou
from utils import get_imgs_masks, get... | 0.746693 | 0.545528 |
from mock import patch
from ....testcases import DustyTestCase
from dusty.compiler.port_spec import (_docker_compose_port_spec, _nginx_port_spec,
_hosts_file_port_spec, get_port_spec_document,
ReusedHostFullAddress, ReusedStreamHostPort)
clas... | tests/unit/compiler/port_spec/init_test.py | from mock import patch
from ....testcases import DustyTestCase
from dusty.compiler.port_spec import (_docker_compose_port_spec, _nginx_port_spec,
_hosts_file_port_spec, get_port_spec_document,
ReusedHostFullAddress, ReusedStreamHostPort)
clas... | 0.47658 | 0.149656 |
from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse
from boto1.models import Image, Hit
from optparse import make_option
import urlparse
import boto
import boto.mturk
import boto.mturk.connection
_mturk_connexion = None
def get_connection():
global _mturk... | boto1/management/commands/create_hits.py | from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse
from boto1.models import Image, Hit
from optparse import make_option
import urlparse
import boto
import boto.mturk
import boto.mturk.connection
_mturk_connexion = None
def get_connection():
global _mturk... | 0.298389 | 0.064036 |
import lightgbm as lgb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#--------------------------------
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin'
#--------------------------------
#parameters
is_regression = True
plotTree = False
... | python/LightGBM/LightGBM.py | import lightgbm as lgb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#--------------------------------
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin'
#--------------------------------
#parameters
is_regression = True
plotTree = False
... | 0.129871 | 0.222215 |
import numpy as np
import os
import argparse
from scipy.spatial.distance import pdist, squareform
def cos_sim(vector_a, vector_b):
"""
Cos Similarity
:param vector_a: vector a
:param vector_b: vector b
:return: sim
"""
return np.inner(vector_a, vector_b) / (np.linalg.norm(vector_a)*np.lina... | tools/layer_select.py | import numpy as np
import os
import argparse
from scipy.spatial.distance import pdist, squareform
def cos_sim(vector_a, vector_b):
"""
Cos Similarity
:param vector_a: vector a
:param vector_b: vector b
:return: sim
"""
return np.inner(vector_a, vector_b) / (np.linalg.norm(vector_a)*np.lina... | 0.486575 | 0.53437 |
try:
import RPi.GPIO as gpio
except ImportError:
import components.gpio as gpio
class Engine:
"""
Base class for all engines.
Provides basic functionality like forwards, backwards and stop.
"""
# Possible engine states
state = {
"FORWARD": (gpio.HIGH, gpio.LOW, gpio.HIGH),
... | components/engine.py | try:
import RPi.GPIO as gpio
except ImportError:
import components.gpio as gpio
class Engine:
"""
Base class for all engines.
Provides basic functionality like forwards, backwards and stop.
"""
# Possible engine states
state = {
"FORWARD": (gpio.HIGH, gpio.LOW, gpio.HIGH),
... | 0.698227 | 0.496277 |
import datetime
import re
import dateparser
import scrapy
from gazette.items import Gazette
from gazette.spiders.base import BaseGazetteSpider
class SpSaoGoncaloDoAmarante(BaseGazetteSpider):
"""
<NAME> has a primary url with
recent gazettes (https://saogoncalo.rn.gov.br/diario-oficial/)
and another... | data_collection/gazette/spiders/rn_sao_goncalo_do_amarante.py | import datetime
import re
import dateparser
import scrapy
from gazette.items import Gazette
from gazette.spiders.base import BaseGazetteSpider
class SpSaoGoncaloDoAmarante(BaseGazetteSpider):
"""
<NAME> has a primary url with
recent gazettes (https://saogoncalo.rn.gov.br/diario-oficial/)
and another... | 0.537527 | 0.328987 |
from collections import OrderedDict
import numpy as np
from .. import Chem, chemutils
from ..vocabulary import AtomTuple
try:
from ..genric_extensions import molecule_representation as mr_native
except ImportError:
from . import _implementation_python as mr_native
from ._implementation_python import atom_fe... | code/genric/molecule_representation/_representation.py |
from collections import OrderedDict
import numpy as np
from .. import Chem, chemutils
from ..vocabulary import AtomTuple
try:
from ..genric_extensions import molecule_representation as mr_native
except ImportError:
from . import _implementation_python as mr_native
from ._implementation_python import atom_fe... | 0.874493 | 0.582254 |
from lazyflow.operators import OpArrayPiper
"""
Operator classes usually start with "Op". We want to get started
quickly, so we just inherit from OpArrayPiper because the operator is
(at least to some extent) similar.
"""
class OpThreshold(OpArrayPiper):
# it is always good to give operators a name
name = "Op... | exercises/03/my_first_operator.py | from lazyflow.operators import OpArrayPiper
"""
Operator classes usually start with "Op". We want to get started
quickly, so we just inherit from OpArrayPiper because the operator is
(at least to some extent) similar.
"""
class OpThreshold(OpArrayPiper):
# it is always good to give operators a name
name = "Op... | 0.761095 | 0.754712 |
import numpy as np
import math
import pandas as pd
import pickle as pkl
import torch
import torch.utils.data as utils
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import LSTM, GRU, ConstantPad1d
from tqdm import tqdm
from attention_models import Attention
from pdb import set_trace as... | code/lib/rnn_models.py | import numpy as np
import math
import pandas as pd
import pickle as pkl
import torch
import torch.utils.data as utils
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import LSTM, GRU, ConstantPad1d
from tqdm import tqdm
from attention_models import Attention
from pdb import set_trace as... | 0.821403 | 0.271443 |
from __future__ import division, print_function, absolute_import
import re
import glob
import os.path as osp
import warnings
from ..dataset import ImageDataset
class MSMT17_NEW(ImageDataset):
"""MSMT17.
Reference:
Wei et al. Person Transfer GAN to Bridge Domain Gap for Person Re-Identification. CVPR... | torchreid/data/datasets/image/msmt17_new.py | from __future__ import division, print_function, absolute_import
import re
import glob
import os.path as osp
import warnings
from ..dataset import ImageDataset
class MSMT17_NEW(ImageDataset):
"""MSMT17.
Reference:
Wei et al. Person Transfer GAN to Bridge Domain Gap for Person Re-Identification. CVPR... | 0.531453 | 0.21463 |
import discord
from redbot.core import Config, commands
from redbot.core.bot import Red
BaseCog = getattr(commands, "Cog", object)
class Loot(BaseCog):
default_guild_settings = {}
def __init__(self, bot: Red):
self.bot = bot
self._loot = Config.get_conf(self, 9741981201)
self._loot... | loot/loot.py | import discord
from redbot.core import Config, commands
from redbot.core.bot import Red
BaseCog = getattr(commands, "Cog", object)
class Loot(BaseCog):
default_guild_settings = {}
def __init__(self, bot: Red):
self.bot = bot
self._loot = Config.get_conf(self, 9741981201)
self._loot... | 0.364099 | 0.145267 |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import argparse
import glob
import numpy as np
import os
import sys
import subprocess
import pdb
from apogee.plan import mkslurm
if __name__ == '__main__' :
parser... | bin/mkaspcap.py |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import argparse
import glob
import numpy as np
import os
import sys
import subprocess
import pdb
from apogee.plan import mkslurm
if __name__ == '__main__' :
parser... | 0.310799 | 0.049681 |
"""ETOS API suite validator module."""
import logging
from uuid import UUID
from typing import Union, List
from pydantic import BaseModel, validator, ValidationError, constr, conlist
import requests
class Environment(BaseModel):
"""ETOS suite definion 'ENVIRONMENT' constraint."""
key: str
value: dict
c... | src/etos_api/library/validator.py | """ETOS API suite validator module."""
import logging
from uuid import UUID
from typing import Union, List
from pydantic import BaseModel, validator, ValidationError, constr, conlist
import requests
class Environment(BaseModel):
"""ETOS suite definion 'ENVIRONMENT' constraint."""
key: str
value: dict
c... | 0.925048 | 0.310917 |
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
class AbstractBaseEventNotifier(object):
""" Abstract base EventNotifier that allows receiving notifications for
different events with default implementations.
See :class:`hystrix.strategy.plugins.Plugin` or the Hyst... | hystrix/strategy/eventnotifier/event_notifier.py | from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
class AbstractBaseEventNotifier(object):
""" Abstract base EventNotifier that allows receiving notifications for
different events with default implementations.
See :class:`hystrix.strategy.plugins.Plugin` or the Hyst... | 0.897819 | 0.161585 |
import kivy
kivy.require('1.11.1')
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
from kivy.uix.tabbedpanel import TabbedPanelItem
from kivy.uix.treeview ... | tests/actual/test_widget_interaction.py | import kivy
kivy.require('1.11.1')
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
from kivy.uix.tabbedpanel import TabbedPanelItem
from kivy.uix.treeview ... | 0.321673 | 0.113629 |
from __future__ import print_function
from compas_rhino.forms import Form
try:
from System.Windows.Forms import Button
from System.Windows.Forms import DialogResult
from System.Windows.Forms import DataGridViewColumnSortMode
from System.Windows.Forms import FlowLayoutPanel
from System.Win... | src/compas_rhino/forms/_table.py | from __future__ import print_function
from compas_rhino.forms import Form
try:
from System.Windows.Forms import Button
from System.Windows.Forms import DialogResult
from System.Windows.Forms import DataGridViewColumnSortMode
from System.Windows.Forms import FlowLayoutPanel
from System.Win... | 0.303525 | 0.034036 |
"""CLI to apply rainforests calibration."""
from improver import cli
@cli.clizefy
@cli.with_output
def process(
forecast: cli.inputcube,
*features: cli.inputcube,
model_config: cli.inputjson,
error_percentiles_count: int = 19,
output_realizations_count: int = 100,
threads: int = 1,
):
"""... | improver/cli/apply_rainforests_calibration.py | """CLI to apply rainforests calibration."""
from improver import cli
@cli.clizefy
@cli.with_output
def process(
forecast: cli.inputcube,
*features: cli.inputcube,
model_config: cli.inputjson,
error_percentiles_count: int = 19,
output_realizations_count: int = 100,
threads: int = 1,
):
"""... | 0.956237 | 0.491456 |
import os
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from pylab import rcParams
from sklearn.cluster import dbscan
from tefingerprint.cluster import DBICAN, SDBICAN
# directory of this script
directory = os.path.dirname(os.path.abspath(__file__))
# figure 1: comparison of DBSCA... | docs/figure/figures.py | import os
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from pylab import rcParams
from sklearn.cluster import dbscan
from tefingerprint.cluster import DBICAN, SDBICAN
# directory of this script
directory = os.path.dirname(os.path.abspath(__file__))
# figure 1: comparison of DBSCA... | 0.397704 | 0.373647 |