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 argparse
import pdb
from builder import build
from util import DEFAULTS
if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser(description='Arguments for building a model that satisfies a set of geometry constraints')
# General arguments
parser.add_argument('--problem'... | src/builder_cli.py | import argparse
import pdb
from builder import build
from util import DEFAULTS
if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser(description='Arguments for building a model that satisfies a set of geometry constraints')
# General arguments
parser.add_argument('--problem'... | 0.609408 | 0.062933 |
from gym.envs.classic_control import MountainCarEnv
class MCEnv(MountainCarEnv):
def __init__(self, partitions=6):
super().__init__()
self.name = "MountainCar"
self.partitions = partitions
self.n_states = partitions * partitions
self.terminal_discrete_state = self.getD... | Environments/MountainCar/MCEnv.py | from gym.envs.classic_control import MountainCarEnv
class MCEnv(MountainCarEnv):
def __init__(self, partitions=6):
super().__init__()
self.name = "MountainCar"
self.partitions = partitions
self.n_states = partitions * partitions
self.terminal_discrete_state = self.getD... | 0.550849 | 0.381796 |
from trankit import Pipeline
from trankit.utils.tbinfo import tbname2max_input_length, lang2treebank, tbname2tokbatchsize
import torch
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer
from tqdm import tqdm
class eNLPDataset(Dataset):
def __init__(self, config, docs, max_inpu... | enlpkit/enlpkit.py | from trankit import Pipeline
from trankit.utils.tbinfo import tbname2max_input_length, lang2treebank, tbname2tokbatchsize
import torch
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer
from tqdm import tqdm
class eNLPDataset(Dataset):
def __init__(self, config, docs, max_inpu... | 0.723114 | 0.268468 |
import asyncio
import re
from datetime import datetime
from collections.abc import Mapping
import discord
from discord.embeds import EmptyEmbed
from . import common
def recursive_update(old_dict, update_dict):
"""
Update one embed dictionary with another, similar to dict.update(),
But recursively update... | pgbot/embed_utils.py | import asyncio
import re
from datetime import datetime
from collections.abc import Mapping
import discord
from discord.embeds import EmptyEmbed
from . import common
def recursive_update(old_dict, update_dict):
"""
Update one embed dictionary with another, similar to dict.update(),
But recursively update... | 0.669529 | 0.226548 |
import collections
import datetime
import logging
import threading
import time
import sia_client as sc
logger = logging.getLogger(__name__)
# Sia must average at least 3 Mbps upload speed in the past hour window.
TIME_WINDOW_MINUTES = 60
MINIMUM_PROGRESS_THRESHOLD = 1350000000 # ~1.26 GiB
_CHECK_FREQUENCY_IN_SECON... | sia_load_tester/progress.py | import collections
import datetime
import logging
import threading
import time
import sia_client as sc
logger = logging.getLogger(__name__)
# Sia must average at least 3 Mbps upload speed in the past hour window.
TIME_WINDOW_MINUTES = 60
MINIMUM_PROGRESS_THRESHOLD = 1350000000 # ~1.26 GiB
_CHECK_FREQUENCY_IN_SECON... | 0.723602 | 0.134378 |
__all__ = ["routes"]
import logging
import secrets
from typing import Any, MutableMapping, Optional, Union
from aiohttp import ClientSession, web
from . import api
logger = logging.getLogger("aiohttp_spotify")
try:
import aiohttp_session
from aiohttp_session import Session
except ImportError:
logger.wa... | src/aiohttp_spotify/views.py | __all__ = ["routes"]
import logging
import secrets
from typing import Any, MutableMapping, Optional, Union
from aiohttp import ClientSession, web
from . import api
logger = logging.getLogger("aiohttp_spotify")
try:
import aiohttp_session
from aiohttp_session import Session
except ImportError:
logger.wa... | 0.819207 | 0.088426 |
import os
import json
import h5py
import numpy as np
import torch
from pathlib import Path
from sacred import Experiment
from sacred.utils import apply_backspaces_and_linefeeds
from sacred.observers import FileStorageObserver
from bnn_priors import exp_utils
# Makes CUDA faster
if torch.cuda.is_available():
torc... | src/bnn_priors/experiments/eval_bnn.py | import os
import json
import h5py
import numpy as np
import torch
from pathlib import Path
from sacred import Experiment
from sacred.utils import apply_backspaces_and_linefeeds
from sacred.observers import FileStorageObserver
from bnn_priors import exp_utils
# Makes CUDA faster
if torch.cuda.is_available():
torc... | 0.502441 | 0.321433 |
from .xlstable import *
import re
import datetime
import sys
from copy import copy
def maybe_sqlquoted(param):
"""Возвращает переданный параметр окруженный кавычками (если это необходимо в SQL)
"""
UUID_PATTERN = re.compile(r'^[{]?([\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12})[}]?$', re.IGNORECASE)
matched... | xlsreport/sqltabledata.py |
from .xlstable import *
import re
import datetime
import sys
from copy import copy
def maybe_sqlquoted(param):
"""Возвращает переданный параметр окруженный кавычками (если это необходимо в SQL)
"""
UUID_PATTERN = re.compile(r'^[{]?([\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12})[}]?$', re.IGNORECASE)
matched... | 0.218336 | 0.161254 |
from datetime import datetime
import discord
AOC_DAY_AND_STAR_TEMPLATE = "{rank: >4} | {name:25.25} | {completion_time: >10}"
class AoCDropdownView(discord.ui.View):
"""Interactive view to filter AoC stats by Day and Star."""
def __init__(self, original_author: discord.Member, day_and_star_data: dict[str: ... | bot/exts/events/advent_of_code/views/dayandstarview.py | from datetime import datetime
import discord
AOC_DAY_AND_STAR_TEMPLATE = "{rank: >4} | {name:25.25} | {completion_time: >10}"
class AoCDropdownView(discord.ui.View):
"""Interactive view to filter AoC stats by Day and Star."""
def __init__(self, original_author: discord.Member, day_and_star_data: dict[str: ... | 0.880566 | 0.47098 |
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
from tkinter import messagebox
from . import odatasfunctions as of
from . import patrickstools2
class StuffPage(ttk.Frame):
def __... | meister_tools/sonstiges.py | try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
from tkinter import messagebox
from . import odatasfunctions as of
from . import patrickstools2
class StuffPage(ttk.Frame):
def __... | 0.177169 | 0.069384 |
import json
import time
import graphics
DEBUG = True
class GShape:
"""
A parent class that represents a shape. It is named GShape for "Graphical shape"
since "shape" is such a generic word.
"""
def __init__(self, win: object, name: str, channel: int, x: int, y: int, color: str):
"""
... | GraphicsJson.py | import json
import time
import graphics
DEBUG = True
class GShape:
"""
A parent class that represents a shape. It is named GShape for "Graphical shape"
since "shape" is such a generic word.
"""
def __init__(self, win: object, name: str, channel: int, x: int, y: int, color: str):
"""
... | 0.891528 | 0.617109 |
import math
import numpy as np
import torch
from ..utils import common_functions as c_f
from .arcface_loss import ArcFaceLoss
class SubCenterArcFaceLoss(ArcFaceLoss):
"""
Implementation of https://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123560715.pdf
"""
def __init__(self, *args, margin=28... | src/pytorch_metric_learning/losses/subcenter_arcface_loss.py | import math
import numpy as np
import torch
from ..utils import common_functions as c_f
from .arcface_loss import ArcFaceLoss
class SubCenterArcFaceLoss(ArcFaceLoss):
"""
Implementation of https://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123560715.pdf
"""
def __init__(self, *args, margin=28... | 0.881296 | 0.252629 |
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import time
print()
print("Hello welcome to the Python Email Bot 1.0")
print("Loading...")
print()
time.sleep(3)
while True:
print()
... | EmailBot.py | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import time
print()
print("Hello welcome to the Python Email Bot 1.0")
print("Loading...")
print()
time.sleep(3)
while True:
print()
... | 0.114653 | 0.067087 |
import torch
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import sys
from os.path import join as pjoin
import scanpy as sc
import anndata
import matplotlib.patches as patches
import matplotlib
font = {"size": 30}
matplotlib.rc("font", **font)
matplotlib.rcParams["text.... | experiments/expression/slideseq/compute_landmark_distances.py | import torch
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import sys
from os.path import join as pjoin
import scanpy as sc
import anndata
import matplotlib.patches as patches
import matplotlib
font = {"size": 30}
matplotlib.rc("font", **font)
matplotlib.rcParams["text.... | 0.432782 | 0.45847 |
import sys,os
sys.path.insert(0,'..')
""" Learned ADMM Plus
Reference : Learned Primal-Dual Reconstruction (<NAME>,<NAME>)
https://github.com/adler-j/learned_primal_dual
Run this script to evauluate parameters trained in learned_admm_plus.py.
"""
import adler
adler.util.gpu.setup_one_gpu()
from adler.odl.phanto... | Lib/learned/evaluate_learned_admm_plus.py | import sys,os
sys.path.insert(0,'..')
""" Learned ADMM Plus
Reference : Learned Primal-Dual Reconstruction (<NAME>,<NAME>)
https://github.com/adler-j/learned_primal_dual
Run this script to evauluate parameters trained in learned_admm_plus.py.
"""
import adler
adler.util.gpu.setup_one_gpu()
from adler.odl.phanto... | 0.429429 | 0.479382 |
from typing import Callable, List, Optional
from pykube import HTTPClient
from pytest_helm_charts.giantswarm_app_platform.custom_resources import CatalogCR
CatalogFactoryFunc = Callable[[str, str, Optional[str]], CatalogCR]
def get_catalog_obj(catalog_name: str, catalog_namespace: str, catalog_uri: str, kube_clien... | pytest_helm_charts/giantswarm_app_platform/catalog.py | from typing import Callable, List, Optional
from pykube import HTTPClient
from pytest_helm_charts.giantswarm_app_platform.custom_resources import CatalogCR
CatalogFactoryFunc = Callable[[str, str, Optional[str]], CatalogCR]
def get_catalog_obj(catalog_name: str, catalog_namespace: str, catalog_uri: str, kube_clien... | 0.833155 | 0.422683 |
import numpy as np
from scipy.linalg import toeplitz
from .Templates import Estimator_mimo, Descriptor
from training_CNN_mimo import pilot_matrix
class DiscreteMMSE(Estimator_mimo, Descriptor):
_object_counter = 1
def __init__(self, channel, snr, n_antennas_BS, n_antennas_MS, n_samples, n_pilots, name=None):
... | estimators/DiscreteMMSE_mimo.py | import numpy as np
from scipy.linalg import toeplitz
from .Templates import Estimator_mimo, Descriptor
from training_CNN_mimo import pilot_matrix
class DiscreteMMSE(Estimator_mimo, Descriptor):
_object_counter = 1
def __init__(self, channel, snr, n_antennas_BS, n_antennas_MS, n_samples, n_pilots, name=None):
... | 0.727492 | 0.416144 |
from __future__ import absolute_import, division, print_function, with_statement
import os
import inspect
import tornado.web
import tornado.httpserver
import tornado.httputil
import tornado.ioloop
from tornado import gen
from tornado import iostream
from tornado.web import HTTPError
from tornado.concurrent import is_... | rw/httpbase.py | from __future__ import absolute_import, division, print_function, with_statement
import os
import inspect
import tornado.web
import tornado.httpserver
import tornado.httputil
import tornado.ioloop
from tornado import gen
from tornado import iostream
from tornado.web import HTTPError
from tornado.concurrent import is_... | 0.616128 | 0.056679 |
import pandas as pd
import numpy as np
import re
import time
def find_num(major_el_name):
"""
Find the number of cations and the number of oxygen atoms of the principal element in the listing
:param major_el_name: Listing of principal elements
:return: Number of cations and number of oxygen atoms
... | english/calculator_for_rock/pyroxene/calculator.py |
import pandas as pd
import numpy as np
import re
import time
def find_num(major_el_name):
"""
Find the number of cations and the number of oxygen atoms of the principal element in the listing
:param major_el_name: Listing of principal elements
:return: Number of cations and number of oxygen atoms
... | 0.475849 | 0.552238 |
import logging
from typing import Union, Optional, List
from gullveig import bootstrap_default_logger
# Configure default logging
def _configure_default_server_logger():
logger = logging.getLogger('gullveig-server')
bootstrap_default_logger(logger)
_configure_default_server_logger()
class AnalyticsSource... | gullveig/server/__init__.py | import logging
from typing import Union, Optional, List
from gullveig import bootstrap_default_logger
# Configure default logging
def _configure_default_server_logger():
logger = logging.getLogger('gullveig-server')
bootstrap_default_logger(logger)
_configure_default_server_logger()
class AnalyticsSource... | 0.883154 | 0.262202 |
import enum
import numpy as np
import random
import matplotlib.pyplot as plt
# 1. Create and algorithm for random walk with equal probability of length 100
# 2. Run your RW algorithm 10x and calculate the statistical features:
# time average, ensemble average, variance and standard deviation.
# Plot a histogram... | random_walk.py | import enum
import numpy as np
import random
import matplotlib.pyplot as plt
# 1. Create and algorithm for random walk with equal probability of length 100
# 2. Run your RW algorithm 10x and calculate the statistical features:
# time average, ensemble average, variance and standard deviation.
# Plot a histogram... | 0.593138 | 0.7063 |
from typing import Any, Dict, Optional, Sequence
import numpy as np
import sklearn.metrics
import tensorflow as tf
import tensorflow_hub as hub
PADDING_VALUE = 0
def state_is_tuple(cell_type):
return cell_type == 'lstm'
def create_mask(inputs: tf.Tensor,
masking_prob: Dict[Any, float],
... | experimental/language_structure/vrnn/utils.py | from typing import Any, Dict, Optional, Sequence
import numpy as np
import sklearn.metrics
import tensorflow as tf
import tensorflow_hub as hub
PADDING_VALUE = 0
def state_is_tuple(cell_type):
return cell_type == 'lstm'
def create_mask(inputs: tf.Tensor,
masking_prob: Dict[Any, float],
... | 0.970521 | 0.548674 |
import numpy as np
from random import randrange
def average_above_zero(table):
"""
make average from a table of non-null positiv value
Arg:
table : a list of numeric values
return:
he computed average
raise :
check if there is no positive value in table
"""
if not(... | assignments/Session1/S1_algotools.py |
import numpy as np
from random import randrange
def average_above_zero(table):
"""
make average from a table of non-null positiv value
Arg:
table : a list of numeric values
return:
he computed average
raise :
check if there is no positive value in table
"""
if not(... | 0.40439 | 0.549701 |
DOCUMENTATION = '''
---
module: ec2_asg_target_groups
short_description: Configure target groups on an existing auto scaling group
description:
- Configure the specified target groups to be attached to an auto scaling group
- The auto scaling group must already exist (use the ec2_asg module)
version_added: "2.4"
... | library/ec2_asg_target_groups.py |
DOCUMENTATION = '''
---
module: ec2_asg_target_groups
short_description: Configure target groups on an existing auto scaling group
description:
- Configure the specified target groups to be attached to an auto scaling group
- The auto scaling group must already exist (use the ec2_asg module)
version_added: "2.4"
... | 0.643329 | 0.257053 |
from typing import Iterable, Optional
import aiohttp
from aiomoex import client, request_helpers
from aiomoex.request_helpers import DEFAULT_BOARD, DEFAULT_ENGINE, DEFAULT_MARKET, SECURITIES
async def get_board_dates(
session: aiohttp.ClientSession,
board: str = DEFAULT_BOARD,
market: str = DEFAULT_MARK... | aiomoex/history.py | from typing import Iterable, Optional
import aiohttp
from aiomoex import client, request_helpers
from aiomoex.request_helpers import DEFAULT_BOARD, DEFAULT_ENGINE, DEFAULT_MARKET, SECURITIES
async def get_board_dates(
session: aiohttp.ClientSession,
board: str = DEFAULT_BOARD,
market: str = DEFAULT_MARK... | 0.692746 | 0.350894 |
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from lusid_drive.api_client import ApiClient
from lusid_drive.exceptions import (
ApiTypeError,
ApiValueError
)
class FoldersApi(object):
"""NOTE: This class is auto generated by Open... | sdk/lusid_drive/api/folders_api.py | from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from lusid_drive.api_client import ApiClient
from lusid_drive.exceptions import (
ApiTypeError,
ApiValueError
)
class FoldersApi(object):
"""NOTE: This class is auto generated by Open... | 0.754825 | 0.077973 |
import re, os, sys, shutil
from pathlib import Path
import pandas as pd
import numpy as np
def split_wnd(df):
unsplit = df['wnd'].str.split(',')
wnd_metrics = pd.DataFrame.from_dict(
dict(zip(df.index, unsplit)),
orient='index',
columns=[
'wnd_direction', # The angle, m... | parsing.py | import re, os, sys, shutil
from pathlib import Path
import pandas as pd
import numpy as np
def split_wnd(df):
unsplit = df['wnd'].str.split(',')
wnd_metrics = pd.DataFrame.from_dict(
dict(zip(df.index, unsplit)),
orient='index',
columns=[
'wnd_direction', # The angle, m... | 0.369201 | 0.520862 |
import numpy as np
from transonic import boost, Array, Type
A = Array[Type(np.float64, np.complex128), "3d"]
Af = "float[:,:,:]"
A = Af # issue fused type with Cython
def proj(vx: A, vy: A, vz: A, kx: Af, ky: Af, kz: Af, inv_k_square_nozero: Af):
tmp = (kx * vx + ky * vy + kz * vz) * inv_k_square_nozero
vx ... | doc/examples/bench_proj_perp/bench.py | import numpy as np
from transonic import boost, Array, Type
A = Array[Type(np.float64, np.complex128), "3d"]
Af = "float[:,:,:]"
A = Af # issue fused type with Cython
def proj(vx: A, vy: A, vz: A, kx: Af, ky: Af, kz: Af, inv_k_square_nozero: Af):
tmp = (kx * vx + ky * vy + kz * vz) * inv_k_square_nozero
vx ... | 0.373076 | 0.314919 |
# pylint: disable=wildcard-import
import logging
import signal
from time import time, sleep
from threading import Thread, Event
from yaml import load, FullLoader
import typing as tp
import humanfriendly
import argparse
from pymeterreader.device_lib import BaseReader, Sample, strip, SmlReader, PlainReader, Bme280Reader
... | pymeterreader/meter_reader.py | # pylint: disable=wildcard-import
import logging
import signal
from time import time, sleep
from threading import Thread, Event
from yaml import load, FullLoader
import typing as tp
import humanfriendly
import argparse
from pymeterreader.device_lib import BaseReader, Sample, strip, SmlReader, PlainReader, Bme280Reader
... | 0.808105 | 0.288413 |
import requests
import json
from config import config
from api_client.url_helpers.internal_app_url import get_create_internal_app_from_blob_url, get_edit_assignment_url
from api_client.url_helpers.internal_app_url import get_retire_app_url, get_internal_app_assignment_url
from Logs.log_configuration import configure_l... | UEM-Samples/Utilities and Tools/Generic/App Upload/Mobile CICD Script/api_client/application_api.py | import requests
import json
from config import config
from api_client.url_helpers.internal_app_url import get_create_internal_app_from_blob_url, get_edit_assignment_url
from api_client.url_helpers.internal_app_url import get_retire_app_url, get_internal_app_assignment_url
from Logs.log_configuration import configure_l... | 0.575111 | 0.07538 |
# OAuth Module for Twitter
import time
import random
import string
import urllib, urllib2
import httplib
import urlparse
import hmac, hashlib
import cgi
import cStringIO
class oauth(object):
_randchars = string.ascii_letters + string.digits
def __init__(self, ckey, csecret, atoken = "", asecret = "",
... | twoauth/oauth.py |
# OAuth Module for Twitter
import time
import random
import string
import urllib, urllib2
import httplib
import urlparse
import hmac, hashlib
import cgi
import cStringIO
class oauth(object):
_randchars = string.ascii_letters + string.digits
def __init__(self, ckey, csecret, atoken = "", asecret = "",
... | 0.470737 | 0.079567 |
from flask import render_template, request, Response
from .message import Message
from .redirection import Redirection
class Page:
def __init__(self, config, api, needs_api, needed_permission, name, template, **static):
self.config = config
self.api = api
self.needs_api = needs_api
... | app/pages/page.py | from flask import render_template, request, Response
from .message import Message
from .redirection import Redirection
class Page:
def __init__(self, config, api, needs_api, needed_permission, name, template, **static):
self.config = config
self.api = api
self.needs_api = needs_api
... | 0.490236 | 0.062962 |
import mmap
import os
import re
def getFileNames():
#this method prints the filenames in a folder (including all subfolders)
#use "r" before filename to use normal string, or escape "\" with "\" or use "/"
for root, dirs, files in os.walk(r"C:\Users\H116099\Documents\archive\python\search TID"):
fo... | search text.py | import mmap
import os
import re
def getFileNames():
#this method prints the filenames in a folder (including all subfolders)
#use "r" before filename to use normal string, or escape "\" with "\" or use "/"
for root, dirs, files in os.walk(r"C:\Users\H116099\Documents\archive\python\search TID"):
fo... | 0.086425 | 0.096748 |
import yKit
import yStructure
import yParameter
import yPort
import types
import logging
class yNodeStructure(yStructure.yStructure):
def __init__(self):
super(yNodeStructure, self).__init__()
self.parameters = yParameter.yParamContainer()
self.input = []
self.output = []
... | yExplorer/src/modules/yNode.py |
import yKit
import yStructure
import yParameter
import yPort
import types
import logging
class yNodeStructure(yStructure.yStructure):
def __init__(self):
super(yNodeStructure, self).__init__()
self.parameters = yParameter.yParamContainer()
self.input = []
self.output = []
... | 0.40251 | 0.226249 |
import sys
import os
import re
import requests
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
include = os.path.relpath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, include)
import emoji as emoji_pkg
def get_text_from_url(url: str) -> str:... | utils/get_codes_from_unicode_emoji_data_files.py | import sys
import os
import re
import requests
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
include = os.path.relpath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, include)
import emoji as emoji_pkg
def get_text_from_url(url: str) -> str:... | 0.395251 | 0.171061 |
import unittest
import platform
from pyxmpp2.etree import ElementTree
import pyxmpp2.version
from pyxmpp2.iq import Iq
from pyxmpp2.jid import JID
from pyxmpp2.stanzaprocessor import StanzaProcessor
from pyxmpp2.settings import XMPPSettings
from pyxmpp2.stanzapayload import XMLPayload
from pyxmpp2.ext.version impor... | modules/pyxmpp2/test/ext_version.py |
import unittest
import platform
from pyxmpp2.etree import ElementTree
import pyxmpp2.version
from pyxmpp2.iq import Iq
from pyxmpp2.jid import JID
from pyxmpp2.stanzaprocessor import StanzaProcessor
from pyxmpp2.settings import XMPPSettings
from pyxmpp2.stanzapayload import XMLPayload
from pyxmpp2.ext.version impor... | 0.505859 | 0.327991 |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
import gc
tf.compat.v1.disable_eager_execution()
def normalize(x):
"""Utility function to normalize a tensor by its L2 norm"""
retu... | gradcamutils.py | import numpy as np
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
import gc
tf.compat.v1.disable_eager_execution()
def normalize(x):
"""Utility function to normalize a tensor by its L2 norm"""
retu... | 0.777553 | 0.581125 |
import re
import psycopg2.errors
from api.config import BotjagwarConfig
config = BotjagwarConfig()
def refine_ipa(data: str) -> str:
lines = data.split('\n')
for line in lines:
if '{{audio|' in line:
rgx = re.search('\\{\\{[Aa]udio\\|(.*)\\|(.*)\\|[A-Za-z]+', line)
if rgx is... | refine_additional_data.py | import re
import psycopg2.errors
from api.config import BotjagwarConfig
config = BotjagwarConfig()
def refine_ipa(data: str) -> str:
lines = data.split('\n')
for line in lines:
if '{{audio|' in line:
rgx = re.search('\\{\\{[Aa]udio\\|(.*)\\|(.*)\\|[A-Za-z]+', line)
if rgx is... | 0.190611 | 0.10316 |
import subprocess
import pytest
from wewcompiler.backend.rustvm import compile_and_pack, assemble_instructions
from tests.helpers import for_feature
def run_code_on_vm(location: int, value: int, size: int, program: str, binary_location: str):
(_, code), _ = compile_and_pack(program)
compiled = assemble_inst... | tests/test_on_vm.py | import subprocess
import pytest
from wewcompiler.backend.rustvm import compile_and_pack, assemble_instructions
from tests.helpers import for_feature
def run_code_on_vm(location: int, value: int, size: int, program: str, binary_location: str):
(_, code), _ = compile_and_pack(program)
compiled = assemble_inst... | 0.708011 | 0.483892 |
def simple(q, arr, prep=None):
return [e for e in arr if e.startswith(q)]
# ------------------------------------------------------------------------------
import math
def narrow_prep(arr):
return sorted(arr)
def narrow(q, arr, prep=None):
if prep == None:
prep = narrow_prep(arr)
low, high = narrow_searc... | src/0011-autocomplete/autocomplete.py | def simple(q, arr, prep=None):
return [e for e in arr if e.startswith(q)]
# ------------------------------------------------------------------------------
import math
def narrow_prep(arr):
return sorted(arr)
def narrow(q, arr, prep=None):
if prep == None:
prep = narrow_prep(arr)
low, high = narrow_searc... | 0.278747 | 0.351422 |
import cv2
import numpy as np
def convex_hull(pts, ccw=True):
"""
Returns the convex hull of points, ordering them in ccw/cw fashion
Note: Since the orientation of the coordinate system is x-right,
y-up, ccw is interpreted as cw in the function call.
"""
assert(pts.ndim == 2 and pts.shape[... | pybot/vision/geom_utils.py |
import cv2
import numpy as np
def convex_hull(pts, ccw=True):
"""
Returns the convex hull of points, ordering them in ccw/cw fashion
Note: Since the orientation of the coordinate system is x-right,
y-up, ccw is interpreted as cw in the function call.
"""
assert(pts.ndim == 2 and pts.shape[... | 0.722625 | 0.818882 |
from database import Database
from collections import Counter
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.stem.lancaster import LancasterStemmer
import re, string
from nlp_stock import strip_punc
Title = "" #Title of the document AFTER calling summarize functio... | newsbuddy/summarize.py | from database import Database
from collections import Counter
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.stem.lancaster import LancasterStemmer
import re, string
from nlp_stock import strip_punc
Title = "" #Title of the document AFTER calling summarize functio... | 0.456168 | 0.203114 |
from threading import Semaphore, Thread, Lock
numero_de_autos=0
cuenta_motor = 0 #cuentas de elementos independientes
cuenta_seccion_de_chasis = 0
cuenta_seccion_de_transmision = 0
cuenta_llantas = 0
cuenta_pinturas = 0
cuenta_motor_chasis = 0 #cuentas de elementos compuestos
cuenta_transmision_llantas = 0
cuenta_... | proyectos/2/LoidiJavier/ensamblaje_de_autos.py | from threading import Semaphore, Thread, Lock
numero_de_autos=0
cuenta_motor = 0 #cuentas de elementos independientes
cuenta_seccion_de_chasis = 0
cuenta_seccion_de_transmision = 0
cuenta_llantas = 0
cuenta_pinturas = 0
cuenta_motor_chasis = 0 #cuentas de elementos compuestos
cuenta_transmision_llantas = 0
cuenta_... | 0.249996 | 0.235867 |
import pandas as pd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import StrMethodFormatter
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import mean_... | data_analysis.py | import pandas as pd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import StrMethodFormatter
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import mean_... | 0.359477 | 0.29559 |
import os
import pygments
from pygments.token import Comment, Error, Keyword, Literal, Name, Number, Punctuation, String, Text
import sys
sys.path.insert(0, os.path.dirname(__file__))
from procyonlexer import ProcyonLexer
def test_null():
assert list(pygments.lex("null", ProcyonLexer())) == [
(Keyword.C... | misc/pygments/test_procyonlexer.py |
import os
import pygments
from pygments.token import Comment, Error, Keyword, Literal, Name, Number, Punctuation, String, Text
import sys
sys.path.insert(0, os.path.dirname(__file__))
from procyonlexer import ProcyonLexer
def test_null():
assert list(pygments.lex("null", ProcyonLexer())) == [
(Keyword.C... | 0.44553 | 0.262172 |
from flask import Flask, render_template, request
import logging
import call
import queue
import cdr
import time
from contextlib import contextmanager
import argparse
INCOMING_NAME = "incoming"
INCOMING_NUM_THREAD = 30
OUTGOING_NAME = "outgoing"
OUTGOING_NUM_THREAD = 300
CDR_NAME = "cdr"
CDR_NUM_THREAD = 5
TIME_MULT... | mockivr/mockivr.py | from flask import Flask, render_template, request
import logging
import call
import queue
import cdr
import time
from contextlib import contextmanager
import argparse
INCOMING_NAME = "incoming"
INCOMING_NUM_THREAD = 30
OUTGOING_NAME = "outgoing"
OUTGOING_NUM_THREAD = 300
CDR_NAME = "cdr"
CDR_NUM_THREAD = 5
TIME_MULT... | 0.240775 | 0.082883 |
from ekidata import db
class Company(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
railway_id = db.Column(
db.SmallInteger,
nullable=False,
index=True
)
common_name = db.Column(db.String(256), nullable=False)
kana_name = db.Column(db.String(25... | ekidata/models.py | from ekidata import db
class Company(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
railway_id = db.Column(
db.SmallInteger,
nullable=False,
index=True
)
common_name = db.Column(db.String(256), nullable=False)
kana_name = db.Column(db.String(25... | 0.499756 | 0.066691 |
from meeting import Meeting
from extract import extract
class Section:
@staticmethod
def exists(soup, count):
return bool(soup.find_all(id='u245_line' + str(count)))
@staticmethod
def create(soup, count):
if not Section.exists(soup, count):
return None
return Sec... | uoft_scraper/section.py | from meeting import Meeting
from extract import extract
class Section:
@staticmethod
def exists(soup, count):
return bool(soup.find_all(id='u245_line' + str(count)))
@staticmethod
def create(soup, count):
if not Section.exists(soup, count):
return None
return Sec... | 0.444083 | 0.188175 |
from typing import List, Dict, Tuple
import requests
import os
import json
import uuid
from datetime import datetime
from AccountInfo import Balance
class LoginCredential:
def __init__(self, area_code: str, login_name: str, password: str):
self.area_code = area_code
self.login_name = login_name... | OKExAPI/Web/Api.py | from typing import List, Dict, Tuple
import requests
import os
import json
import uuid
from datetime import datetime
from AccountInfo import Balance
class LoginCredential:
def __init__(self, area_code: str, login_name: str, password: str):
self.area_code = area_code
self.login_name = login_name... | 0.627381 | 0.16228 |
from __future__ import print_function
import argparse
import logging
import os
import random
import re
import six
from .config import CONFIG
def _make_main_parser():
"""Construct the argparse parser for the main CLI.
This exists as a separate function so the parser can be used to
auto-generate CLI doc... | diluvian/__main__.py | from __future__ import print_function
import argparse
import logging
import os
import random
import re
import six
from .config import CONFIG
def _make_main_parser():
"""Construct the argparse parser for the main CLI.
This exists as a separate function so the parser can be used to
auto-generate CLI doc... | 0.734691 | 0.16228 |
from typing import List, Dict, Any, Optional
import logging
from collections import Counter
from reval.dataset_utils import train_val_split
from reval.probing_task_example import ProbingTaskExample
logger = logging.getLogger(__name__)
def generate_task_examples(
data: List[Dict[str, Any]],
argument: str,
... | reval/probing_tasks/argument_type.py | from typing import List, Dict, Any, Optional
import logging
from collections import Counter
from reval.dataset_utils import train_val_split
from reval.probing_task_example import ProbingTaskExample
logger = logging.getLogger(__name__)
def generate_task_examples(
data: List[Dict[str, Any]],
argument: str,
... | 0.773772 | 0.344933 |
# no imports
# no functions
# classes
class zipimporter(object):
"""
zipimporter(archivepath) -> zipimporter object
Create a new zipimporter instance. 'archivepath' must be a path to
a zipfile, or to a specific path inside a zipfile. For example, it can be
'/tmp/myimport.zip', or '/tmp/myimpo... | resources/dot_PyCharm/system/python_stubs/-762174762/zipimport.py | # no imports
# no functions
# classes
class zipimporter(object):
"""
zipimporter(archivepath) -> zipimporter object
Create a new zipimporter instance. 'archivepath' must be a path to
a zipfile, or to a specific path inside a zipfile. For example, it can be
'/tmp/myimport.zip', or '/tmp/myimpo... | 0.576065 | 0.361644 |
import ed25519
import binascii
import socket
import struct
import time
import hashlib
# opcodes
TIME_SYNC = chr(0)
CERT_REQUEST_INIT = chr(1)
CERT_REQUEST_CONFIRM = chr(2)
CERT_REQUEST_INVALID_AUTH = chr(3)
class CS(object):
def __init__(self, port, keypair_seed):
self.socket = socket.socket(socket.AF_I... | certificate_service.py | import ed25519
import binascii
import socket
import struct
import time
import hashlib
# opcodes
TIME_SYNC = chr(0)
CERT_REQUEST_INIT = chr(1)
CERT_REQUEST_CONFIRM = chr(2)
CERT_REQUEST_INVALID_AUTH = chr(3)
class CS(object):
def __init__(self, port, keypair_seed):
self.socket = socket.socket(socket.AF_I... | 0.277375 | 0.177829 |
import sys
import importlib
import manifest
sys.path.insert(0, '../../common')
_module = importlib.import_module(manifest.sdk)
for exportObject in _module.exportObjects: __builtins__[exportObject] = _module.__getattribute__(exportObject)
_NEWLINE_ = '\n'
# __ABX_IMPLEMENTATIONS_START__
#======================... | devs/abx/custom_resource/resources/deployment/resource_update.py | import sys
import importlib
import manifest
sys.path.insert(0, '../../common')
_module = importlib.import_module(manifest.sdk)
for exportObject in _module.exportObjects: __builtins__[exportObject] = _module.__getattribute__(exportObject)
_NEWLINE_ = '\n'
# __ABX_IMPLEMENTATIONS_START__
#======================... | 0.165796 | 0.03498 |
from zeit.cms.i18n import MessageFactory as _
import zc.form.field
import zeit.cms.interfaces
import zeit.cms.related.interfaces
import zeit.cms.section.interfaces
import zeit.content.article.interfaces
import zeit.content.cp.interfaces
import zeit.content.gallery.interfaces
import zeit.content.link.interfaces
import z... | core/src/zeit/magazin/interfaces.py | from zeit.cms.i18n import MessageFactory as _
import zc.form.field
import zeit.cms.interfaces
import zeit.cms.related.interfaces
import zeit.cms.section.interfaces
import zeit.content.article.interfaces
import zeit.content.cp.interfaces
import zeit.content.gallery.interfaces
import zeit.content.link.interfaces
import z... | 0.589126 | 0.121451 |
import logging
import re
import warnings
import cryptography
from jnpr.junos.utils.start_shell import StartShell
from jnpr.junos.exception import ConnectError
from .conn_device import ConnDevice
with warnings.catch_warnings():
warnings.simplefilter('ignore', cryptography.utils)
import cryptography.hazmat.prim... | Executor/lib/junos_cli_trigger.py | import logging
import re
import warnings
import cryptography
from jnpr.junos.utils.start_shell import StartShell
from jnpr.junos.exception import ConnectError
from .conn_device import ConnDevice
with warnings.catch_warnings():
warnings.simplefilter('ignore', cryptography.utils)
import cryptography.hazmat.prim... | 0.619471 | 0.128034 |
# https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
# * algorithms
# * Hard (38.05%)
# * Total Accepted: 6.8K
# * Total Submissions: 16.2K
# * Testcase Example: '["RandomizedCollection","insert","insert","insert","getRandom","remove","getRandom"]\n' +
# '[[],[1],[1],[2]... | python/381.insert-delete-getrandom-o1-duplicates-allowed.py |
# https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
# * algorithms
# * Hard (38.05%)
# * Total Accepted: 6.8K
# * Total Submissions: 16.2K
# * Testcase Example: '["RandomizedCollection","insert","insert","insert","getRandom","remove","getRandom"]\n' +
# '[[],[1],[1],[2]... | 0.734024 | 0.409929 |
from openprocurement.api.utils import (error_handler, raise_operation_error,
get_now)
from openprocurement.api.validation import validate_data, OPERATIONS
# tender documents
def validate_document_operation_in_not_allowed_tender_status(request):
if request.authenticated_role ... | openprocurement/tender/belowthreshold/validation.py | from openprocurement.api.utils import (error_handler, raise_operation_error,
get_now)
from openprocurement.api.validation import validate_data, OPERATIONS
# tender documents
def validate_document_operation_in_not_allowed_tender_status(request):
if request.authenticated_role ... | 0.234407 | 0.199172 |
from oslo_db import exception as db_exc
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import timeutils
from oslo_utils import uuidutils
from sqlalchemy import exc as sql_exc
from sqlalchemy.orm import exc
from neutron.db import common_db_mixin
from neutron.plugins.common import c... | networking_cisco/plugins/cisco/db/device_manager/hosting_devices_db.py |
from oslo_db import exception as db_exc
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import timeutils
from oslo_utils import uuidutils
from sqlalchemy import exc as sql_exc
from sqlalchemy.orm import exc
from neutron.db import common_db_mixin
from neutron.plugins.common import c... | 0.266453 | 0.050729 |
from flask import Flask, render_template, request, redirect, make_response, send_from_directory, session, jsonify
from datetime import datetime, timezone
from pymongo import MongoClient
from bson.objectid import ObjectId
import logging
import bcrypt
app = Flask(__name__)
app.config['SECRET_KEY'] = '364S1947RO713085892... | app.py | from flask import Flask, render_template, request, redirect, make_response, send_from_directory, session, jsonify
from datetime import datetime, timezone
from pymongo import MongoClient
from bson.objectid import ObjectId
import logging
import bcrypt
app = Flask(__name__)
app.config['SECRET_KEY'] = '364S1947RO713085892... | 0.334046 | 0.067577 |
# Sample Tinode REST/JSON-RPC authentication service.
# See https://github.com/tinode/chat/rest-auth for details.
from flask import Flask, jsonify, make_response, request
import base64
import json
dummy_data = {}
app = Flask(__name__)
def parse_secret(ecoded_secret):
secret = base64.b64decode(ecoded_secret)
... | rest-auth/auth.py |
# Sample Tinode REST/JSON-RPC authentication service.
# See https://github.com/tinode/chat/rest-auth for details.
from flask import Flask, jsonify, make_response, request
import base64
import json
dummy_data = {}
app = Flask(__name__)
def parse_secret(ecoded_secret):
secret = base64.b64decode(ecoded_secret)
... | 0.689619 | 0.086748 |
import pprint
import re # noqa: F401
import six
from sunshine_conversations_client.configuration import Configuration
from sunshine_conversations_client.undefined import Undefined
class ConversationCreateEventAllOfPayload(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://op... | sunshine_conversations_client/model/conversation_create_event_all_of_payload.py | import pprint
import re # noqa: F401
import six
from sunshine_conversations_client.configuration import Configuration
from sunshine_conversations_client.undefined import Undefined
class ConversationCreateEventAllOfPayload(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://op... | 0.746693 | 0.073264 |
import pygame
from pygame import *
from random import randint
FPS = 60
lost_ships = 0
score = 0
Color = (255, 255, 255)
update_level = 1
common_HP = 1
hard_HP = 2
super_HP = 4
flag = True
hard_flag_1 = True
hard_flag_2 = True
final_flag1 = True
final_flag2 = True
reload = False
reload_timer = 0... | Galaxy_ship.py | import pygame
from pygame import *
from random import randint
FPS = 60
lost_ships = 0
score = 0
Color = (255, 255, 255)
update_level = 1
common_HP = 1
hard_HP = 2
super_HP = 4
flag = True
hard_flag_1 = True
hard_flag_2 = True
final_flag1 = True
final_flag2 = True
reload = False
reload_timer = 0... | 0.131507 | 0.237742 |
import copy
import os
import re
from pathlib import Path
from django.core.exceptions import ValidationError
from resolwe.flow.utils import iterate_fields
def _hydrate_values(output, output_schema, data):
"""Hydrate basic:file and basic:json values.
Find fields with basic:file type and assign a full path to... | resolwe/flow/models/utils/hydrate.py | import copy
import os
import re
from pathlib import Path
from django.core.exceptions import ValidationError
from resolwe.flow.utils import iterate_fields
def _hydrate_values(output, output_schema, data):
"""Hydrate basic:file and basic:json values.
Find fields with basic:file type and assign a full path to... | 0.52829 | 0.387864 |
# http://www.apache.org/licenses/LICENSE-2.0
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permis... | src/contrib/hod/hodlib/GridServices/mapred.py |
# http://www.apache.org/licenses/LICENSE-2.0
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permis... | 0.460774 | 0.114196 |
from qtpy import QtCore, QtGui, QtWidgets, uic
import os
import copy
import sys
import pathlib
import json
from logzero import logger
from modules.multithreading import Worker, ProgressDialog
class_name = 'source_update_tab'
class AddProcessingRuleDialog(QtWidgets.QDialog):
def __init__(self):
super(Add... | modules/source_update_tab.py | from qtpy import QtCore, QtGui, QtWidgets, uic
import os
import copy
import sys
import pathlib
import json
from logzero import logger
from modules.multithreading import Worker, ProgressDialog
class_name = 'source_update_tab'
class AddProcessingRuleDialog(QtWidgets.QDialog):
def __init__(self):
super(Add... | 0.319971 | 0.050988 |
import os
import json
from primehub import PrimeHub, PrimeHubConfig
class Config(object):
"""
Primehub Remote Deploy Config
"""
# Primehub Remote Deploy Config
master_config = None
worker_configs = []
def __init__(self):
self.load_sdk_config_files()
pass
def load_sdk... | primehub_remote_deploy/config.py |
import os
import json
from primehub import PrimeHub, PrimeHubConfig
class Config(object):
"""
Primehub Remote Deploy Config
"""
# Primehub Remote Deploy Config
master_config = None
worker_configs = []
def __init__(self):
self.load_sdk_config_files()
pass
def load_sdk... | 0.321034 | 0.065276 |
import enum
from typing import Tuple, Optional
import persistent
import persistent.list
from BTrees.OOBTree import OOBTree
class NAT(enum.Enum):
"""Indicates the current known state of NAT on the target host"""
UNKNOWN = enum.auto()
""" We currently don't have enough information to determine if NAT is u... | pwncat/target.py | import enum
from typing import Tuple, Optional
import persistent
import persistent.list
from BTrees.OOBTree import OOBTree
class NAT(enum.Enum):
"""Indicates the current known state of NAT on the target host"""
UNKNOWN = enum.auto()
""" We currently don't have enough information to determine if NAT is u... | 0.883003 | 0.487185 |
from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import os
from PIL import Image
import filtering
UPLOAD_FOLDER = '/static/uploads'
UPLOAD_FOLDER_FULL = os.getcwd() + UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = Flask(__name__)
app.con... | app.py | from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import os
from PIL import Image
import filtering
UPLOAD_FOLDER = '/static/uploads'
UPLOAD_FOLDER_FULL = os.getcwd() + UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = Flask(__name__)
app.con... | 0.529263 | 0.090173 |
import cascade_py
class CascadeShardLinq:
def __init__(self, capi, _type, subgroup_index, shard_index, version):
self.capi = capi
self.subgroup_index = subgroup_index
self.shard_index = shard_index
self.version = version
self.type = _type
self.gi_running = True
... | src/service/python/cascadeLINQ.py | import cascade_py
class CascadeShardLinq:
def __init__(self, capi, _type, subgroup_index, shard_index, version):
self.capi = capi
self.subgroup_index = subgroup_index
self.shard_index = shard_index
self.version = version
self.type = _type
self.gi_running = True
... | 0.281109 | 0.121477 |
from encoded.reports.constants import BATCH_DOWNLOAD_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import SERIES_BATCH_DOWNLOAD_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import METADATA_LINK
from encoded.reports.constants import AT_IDS_AS_JSON_DATA_LINK
from encoded.reports.metadata import Metad... | src/encoded/reports/batch_download.py | from encoded.reports.constants import BATCH_DOWNLOAD_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import SERIES_BATCH_DOWNLOAD_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import METADATA_LINK
from encoded.reports.constants import AT_IDS_AS_JSON_DATA_LINK
from encoded.reports.metadata import Metad... | 0.716715 | 0.166913 |
import os
import socket
import time
import signal
import errno
SERVER_ADDRESS = (HOST, PORT) = '', 8887
REQUEST_QUEUE_SIZE = 5
def grim_reaper(signum, frame):
pid, status = os.wait()
print(
'Child {pid} terminated with status {status}'.format(
pid=pid, status=status
)
)
def ... | concurent_server.py | import os
import socket
import time
import signal
import errno
SERVER_ADDRESS = (HOST, PORT) = '', 8887
REQUEST_QUEUE_SIZE = 5
def grim_reaper(signum, frame):
pid, status = os.wait()
print(
'Child {pid} terminated with status {status}'.format(
pid=pid, status=status
)
)
def ... | 0.086287 | 0.074568 |
import requests
import json
import pandas as pd
import tweepy
import os
import config as cfg
import time
import asyncio
import aiohttp
from time import sleep
from datetime import datetime, timedelta
from pytz import timezone
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions im... | check.py | import requests
import json
import pandas as pd
import tweepy
import os
import config as cfg
import time
import asyncio
import aiohttp
from time import sleep
from datetime import datetime, timedelta
from pytz import timezone
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions im... | 0.141193 | 0.108779 |
from subprocess import call
import os
import requests
import numpy as np
import pandas as pd
from pandas.errors import EmptyDataError
from datetime import datetime
from copy import deepcopy
SOURCES = ['NOAA', 'CPC']
PID = os.getpid()
TMP_FILE_PATH = os.environ['HOME'] + f'/temp_file_climIndices_{PID}.txt'
def file_l... | climIndices/tools.py | from subprocess import call
import os
import requests
import numpy as np
import pandas as pd
from pandas.errors import EmptyDataError
from datetime import datetime
from copy import deepcopy
SOURCES = ['NOAA', 'CPC']
PID = os.getpid()
TMP_FILE_PATH = os.environ['HOME'] + f'/temp_file_climIndices_{PID}.txt'
def file_l... | 0.317955 | 0.231397 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import models
from models import register
from utils import make_coord
import pdb
@register('liif')
class LIIF(nn.Module):
def __init__(self, encoder_spec, imnet_spec=None,
local_ensemble=True, feat_unfold=True, cell_decode=True)... | models/liif.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import models
from models import register
from utils import make_coord
import pdb
@register('liif')
class LIIF(nn.Module):
def __init__(self, encoder_spec, imnet_spec=None,
local_ensemble=True, feat_unfold=True, cell_decode=True)... | 0.813424 | 0.237134 |
from __future__ import annotations
from typing import Any, Dict, List, Optional
from classes.report_type import Type
from google.cloud import bigquery
class AbstractDatastore(object):
"""Abstract Datastore.
This is the Datastore contract to be fufilled by any storage method. It
contains the functions to be ... | application/classes/abstract_datastore.py | from __future__ import annotations
from typing import Any, Dict, List, Optional
from classes.report_type import Type
from google.cloud import bigquery
class AbstractDatastore(object):
"""Abstract Datastore.
This is the Datastore contract to be fufilled by any storage method. It
contains the functions to be ... | 0.894277 | 0.386358 |
from marshmallow import Schema, validate
from webargs import fields
class Polygon(Schema):
type = fields.Constant("Polygon", required=True, description="Object type")
coordinates = fields.List(
fields.List(fields.Tuple((fields.Float, fields.Float)), required=True),
required=True,
descr... | dotmeshgj/schemas.py | from marshmallow import Schema, validate
from webargs import fields
class Polygon(Schema):
type = fields.Constant("Polygon", required=True, description="Object type")
coordinates = fields.List(
fields.List(fields.Tuple((fields.Float, fields.Float)), required=True),
required=True,
descr... | 0.806777 | 0.465387 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from zope.interface import Interface
from zope.interface import taggedValue
from zope.schema import Object
from zope.schema import URI
from nti.schema.field import Dict
from nti.schema.field import TextLine
f... | src/nti/externalization/tests/benchmarks/profileinterfaces.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from zope.interface import Interface
from zope.interface import taggedValue
from zope.schema import Object
from zope.schema import URI
from nti.schema.field import Dict
from nti.schema.field import TextLine
f... | 0.681833 | 0.091018 |
import os
import tarfile
from collections import defaultdict
from unittest.mock import patch
from torchtext.datasets.yelpreviewfull import YelpReviewFull
from torchtext.datasets.yelpreviewpolarity import YelpReviewPolarity
from ..common.parameterized_utils import nested_params
from ..common.case_utils import TempDirM... | test/datasets/test_yelpreviews.py | import os
import tarfile
from collections import defaultdict
from unittest.mock import patch
from torchtext.datasets.yelpreviewfull import YelpReviewFull
from torchtext.datasets.yelpreviewpolarity import YelpReviewPolarity
from ..common.parameterized_utils import nested_params
from ..common.case_utils import TempDirM... | 0.476092 | 0.263842 |
import argparse
import cv2
import numpy as np
import random
from PIL import Image,ImageDraw,ImageFont
import os
import uuid
if __name__ == '__main__':
parse = argparse.ArgumentParser()
parse.add_argument('--font_path', required=True, help='the font location')
parse.add_argument('--font_size', required=Tru... | captcha_generate.py | import argparse
import cv2
import numpy as np
import random
from PIL import Image,ImageDraw,ImageFont
import os
import uuid
if __name__ == '__main__':
parse = argparse.ArgumentParser()
parse.add_argument('--font_path', required=True, help='the font location')
parse.add_argument('--font_size', required=Tru... | 0.263789 | 0.101367 |
import numpy as np
def gen_outcomes(X, T, seed=0):
"""Synthetically generate outcome data from provided covariates and treatment assignment.
Args:
X: input covariates
T: treatment assignment
seed (int): seed to fix the random number generator
Returns:
y: observed outc... | causallib/contrib/hemm/gen_synthetic_data.py | import numpy as np
def gen_outcomes(X, T, seed=0):
"""Synthetically generate outcome data from provided covariates and treatment assignment.
Args:
X: input covariates
T: treatment assignment
seed (int): seed to fix the random number generator
Returns:
y: observed outc... | 0.829837 | 0.74454 |
from modelos.percentil import Percentil
DESEMPENO_NARRATIVO = 'desempeno_narrativo'
COMPRENSION_DISCURSO_NARRATIVO = 'comprension_discurso_narrativo'
LEER = {
DESEMPENO_NARRATIVO: 'desempeño narrativo',
COMPRENSION_DISCURSO_NARRATIVO: 'comprensión discurso narrativo'
}
PRUEBAS_EDNA = {
DESEMPENO_NARRATIV... | modelos/edna.py | from modelos.percentil import Percentil
DESEMPENO_NARRATIVO = 'desempeno_narrativo'
COMPRENSION_DISCURSO_NARRATIVO = 'comprension_discurso_narrativo'
LEER = {
DESEMPENO_NARRATIVO: 'desempeño narrativo',
COMPRENSION_DISCURSO_NARRATIVO: 'comprensión discurso narrativo'
}
PRUEBAS_EDNA = {
DESEMPENO_NARRATIV... | 0.228286 | 0.281572 |
from django.db import models
from django.contrib.auth.models import Group
class PrintTemplate(models.Model):
PRINT_TYPE_CHOICES = [
('Dymo', 'Dymo Labelwriter'),
('Paper', 'Regular Paper'),
]
name = models.CharField(max_length=200)
type = models.CharField(max_length=16,choices=PRINT_TY... | captiveportal/voucher/models.py |
from django.db import models
from django.contrib.auth.models import Group
class PrintTemplate(models.Model):
PRINT_TYPE_CHOICES = [
('Dymo', 'Dymo Labelwriter'),
('Paper', 'Regular Paper'),
]
name = models.CharField(max_length=200)
type = models.CharField(max_length=16,choices=PRINT_TY... | 0.5 | 0.17989 |
import init_args_serializer.function_arg_capture as uut
# Positional and keyword args land in the kwargs
def simple_capturing_function(arg1, arg2="default_arg2", arg3="default_arg3"):
# Capture and return args
return uut.capture_args(simple_capturing_function, locals())
def test_simple_nooptional():
arg... | tests/test_argcapture.py | import init_args_serializer.function_arg_capture as uut
# Positional and keyword args land in the kwargs
def simple_capturing_function(arg1, arg2="default_arg2", arg3="default_arg3"):
# Capture and return args
return uut.capture_args(simple_capturing_function, locals())
def test_simple_nooptional():
arg... | 0.493164 | 0.648494 |
import sqlite3
def query(sql,data):
with sqlite3.connect(DATABASE) as db:
cursor = db.cursor()
cursor.execute(sql,data)
db.commit()
def query_with_results(sql,data):
with sqlite3.connect(DATABASE) as db:
cursor = db.cursor()
if data == None:
cursor.execute... | unit_07/02/main.py |
import sqlite3
def query(sql,data):
with sqlite3.connect(DATABASE) as db:
cursor = db.cursor()
cursor.execute(sql,data)
db.commit()
def query_with_results(sql,data):
with sqlite3.connect(DATABASE) as db:
cursor = db.cursor()
if data == None:
cursor.execute... | 0.304765 | 0.156717 |
import aesara
import aesara.tensor as at
import numpy as np
import pytest
import scipy as sp
from aesara.graph.fg import FunctionGraph
from numdifftools import Jacobian
from aeppl.joint_logprob import joint_logprob
from aeppl.transforms import (
DEFAULT_TRANSFORM,
LogOddsTransform,
LogTransform,
RVTran... | tests/test_transforms.py | import aesara
import aesara.tensor as at
import numpy as np
import pytest
import scipy as sp
from aesara.graph.fg import FunctionGraph
from numdifftools import Jacobian
from aeppl.joint_logprob import joint_logprob
from aeppl.transforms import (
DEFAULT_TRANSFORM,
LogOddsTransform,
LogTransform,
RVTran... | 0.720565 | 0.60507 |
import pytest
import unittest
import numpy as np
from dacbench import AbstractEnv
from dacbench.benchmarks.sgd_benchmark import SGDBenchmark, SGD_DEFAULTS
class TestSGDEnv(unittest.TestCase):
def make_env(self):
bench = SGDBenchmark()
env = bench.get_environment()
return env
def test_... | tests/envs/test_sgd.py | import pytest
import unittest
import numpy as np
from dacbench import AbstractEnv
from dacbench.benchmarks.sgd_benchmark import SGDBenchmark, SGD_DEFAULTS
class TestSGDEnv(unittest.TestCase):
def make_env(self):
bench = SGDBenchmark()
env = bench.get_environment()
return env
def test_... | 0.61832 | 0.590307 |
from .logger import logger
from .query import Query
import elasticsearch
# ### HIGHLIGHT HANDLING
# DONT_HIGHLIGHT = {
# 'kind',
# 'kind_he',
# 'budget_code',
# 'entity_kind',
# 'entity_id',
# 'code',
# }
class Controllers():
def __init__(self,
search_indexes,
... | apies/controllers.py | from .logger import logger
from .query import Query
import elasticsearch
# ### HIGHLIGHT HANDLING
# DONT_HIGHLIGHT = {
# 'kind',
# 'kind_he',
# 'budget_code',
# 'entity_kind',
# 'entity_id',
# 'code',
# }
class Controllers():
def __init__(self,
search_indexes,
... | 0.520496 | 0.169543 |
from pero import Frame, Graphics, OrdinalScale, Path, colors
from pero.enums import *
from pero.properties import *
from .annotation import Annotation
from .axes import Axis
from .enums import ANNOTS_Z, GRID_Z, LABELS_Z, LEGEND_Z, PLOT_TAG, SERIES_Z, TITLE_Z
from .graphics import InGraphics, OutGraphics
from .grid imp... | perrot/plot/plot.py |
from pero import Frame, Graphics, OrdinalScale, Path, colors
from pero.enums import *
from pero.properties import *
from .annotation import Annotation
from .axes import Axis
from .enums import ANNOTS_Z, GRID_Z, LABELS_Z, LEGEND_Z, PLOT_TAG, SERIES_Z, TITLE_Z
from .graphics import InGraphics, OutGraphics
from .grid imp... | 0.867233 | 0.500793 |
import socket
import logging
from emoji import demojize
import time
import progressbar
from datetime import datetime
import re
import pandas as pd
from processChat import get_chat_dataframe
class ChatBot:
def __init__(self, nickname, channel,
server = 'irc.chat.twitch.tv',
... | twitchChatBot.py |
import socket
import logging
from emoji import demojize
import time
import progressbar
from datetime import datetime
import re
import pandas as pd
from processChat import get_chat_dataframe
class ChatBot:
def __init__(self, nickname, channel,
server = 'irc.chat.twitch.tv',
... | 0.361503 | 0.066116 |
import os
import argparse
import sys
import logging
from datetime import datetime
from abc import ABC, abstractmethod
logger = logging.getLogger(__name__)
class BaseValidator(ABC):
def __init__(self, param):
self.param = param
@abstractmethod
def is_valid(self):
pass
class DateRangeValid... | picco/validators.py | import os
import argparse
import sys
import logging
from datetime import datetime
from abc import ABC, abstractmethod
logger = logging.getLogger(__name__)
class BaseValidator(ABC):
def __init__(self, param):
self.param = param
@abstractmethod
def is_valid(self):
pass
class DateRangeValid... | 0.39036 | 0.081739 |
import math
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import matplotlib.gridspec as grid_spec
import seaborn as sns
from pywaffle import Waffle
from pandas.plotting import andrews_curves
class Visualizations():
def __init__(self, snsPalette="Paired", fontSize=1... | visualizations.py | import math
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import matplotlib.gridspec as grid_spec
import seaborn as sns
from pywaffle import Waffle
from pandas.plotting import andrews_curves
class Visualizations():
def __init__(self, snsPalette="Paired", fontSize=1... | 0.61878 | 0.378115 |
from __future__ import absolute_import, division, print_function, unicode_literals
from future.builtins import * # noqa pylint: disable=W0401, W0614
from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614
# === End Python 2/3 compatibility
import pytest
import numpy as np
import os
import re
f... | tests/test_freqsplit.py | from __future__ import absolute_import, division, print_function, unicode_literals
from future.builtins import * # noqa pylint: disable=W0401, W0614
from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614
# === End Python 2/3 compatibility
import pytest
import numpy as np
import os
import re
f... | 0.458591 | 0.247067 |
import os
import time
import threading
from pprint import pprint
from sensible.database import selectDataAll, selectOtherDataAll, selectDataSummary, selectOtherDataSummary
def runBaseInterface(virtualDevices):
devicesString = "Virtual devices running on ports: " + str(list(virtualDevices.keys()))
print(device... | sensible/interactive_interface.py |
import os
import time
import threading
from pprint import pprint
from sensible.database import selectDataAll, selectOtherDataAll, selectDataSummary, selectOtherDataSummary
def runBaseInterface(virtualDevices):
devicesString = "Virtual devices running on ports: " + str(list(virtualDevices.keys()))
print(device... | 0.139162 | 0.128006 |
from __future__ import annotations
from collections.abc import Iterator
from math import ceil
import random
from typing import Any, Union
from discopy import Tensor
class Dataset:
"""Dataset class for the training of a lambeq model.
Data is returned in the format of :py:class:`discopy.tensor.Tensor`'s
... | lambeq/training/dataset.py | from __future__ import annotations
from collections.abc import Iterator
from math import ceil
import random
from typing import Any, Union
from discopy import Tensor
class Dataset:
"""Dataset class for the training of a lambeq model.
Data is returned in the format of :py:class:`discopy.tensor.Tensor`'s
... | 0.950284 | 0.576542 |
from __future__ import (
annotations,
)
import json
from datetime import (
datetime,
)
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Optional,
Type,
Union,
)
from uuid import (
UUID,
)
from minos.common import (
NULL_UUID,
MinosJsonBinaryProtocol,
import_module,
)
... | minos/aggregate/snapshots/entries.py | from __future__ import (
annotations,
)
import json
from datetime import (
datetime,
)
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Optional,
Type,
Union,
)
from uuid import (
UUID,
)
from minos.common import (
NULL_UUID,
MinosJsonBinaryProtocol,
import_module,
)
... | 0.89005 | 0.184198 |
import pytest
from opyapi import build_validator_for
def test_validate_if_then_validator() -> None:
# given
validate = build_validator_for(
{
"if": {"type": "object"},
"then": {
"properties": {
"age": {
"type": "integ... | tests/validators/test_combining_validators.py | import pytest
from opyapi import build_validator_for
def test_validate_if_then_validator() -> None:
# given
validate = build_validator_for(
{
"if": {"type": "object"},
"then": {
"properties": {
"age": {
"type": "integ... | 0.583322 | 0.555375 |
from unittest import TestCase
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import config, url
from routes.util import URLGenerator
from webtest import TestApp
import pylons.test
from elixir import *
from kwmo.model import *
from kwmo.model import meta
from kwmo import ... | web/kwmo/kwmo/tests/__init__.py | from unittest import TestCase
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import config, url
from routes.util import URLGenerator
from webtest import TestApp
import pylons.test
from elixir import *
from kwmo.model import *
from kwmo.model import meta
from kwmo import ... | 0.37399 | 0.203807 |
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from scapy.layers.inet import *
from scapy.layers.dhcp import *
from scapy.layers.dns import *
def naive(dst_ip, dst_port, pkt_size=100, inter=0.05):
send_tcp(dst_ip, dst_port, pkt_size, inter)
# Probing Attack
... | Scripts/attack.py |
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from scapy.layers.inet import *
from scapy.layers.dhcp import *
from scapy.layers.dns import *
def naive(dst_ip, dst_port, pkt_size=100, inter=0.05):
send_tcp(dst_ip, dst_port, pkt_size, inter)
# Probing Attack
... | 0.390708 | 0.169372 |
from pyrate.algorithms.aisparser import run, AIS_CSV_COLUMNS, readcsv
from pyrate.repositories.aisdb import AISdb
from pyrate.repositories import file
from utilities import setup_database
import os
import tempfile
from pytest import fixture
import csv
def make_temporary_file():
""" Returns a temporary file name
... | tests/test_aisparser.py | from pyrate.algorithms.aisparser import run, AIS_CSV_COLUMNS, readcsv
from pyrate.repositories.aisdb import AISdb
from pyrate.repositories import file
from utilities import setup_database
import os
import tempfile
from pytest import fixture
import csv
def make_temporary_file():
""" Returns a temporary file name
... | 0.654564 | 0.246431 |