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 context
from zincbase import KB
kb = KB()
kb.seed(555)
kb.store('person(tom)')
kb.store('person(shamala)')
kb.store('knows(tom, shamala)')
assert kb.neighbors('tom') == [('shamala', [{'pred': 'knows'}])]
kb.node('tom')['grains'] = 0
tom = kb.node('tom')
assert tom.grains == 0
assert tom.i_dont_exist is None... | test/test_attr.py | import context
from zincbase import KB
kb = KB()
kb.seed(555)
kb.store('person(tom)')
kb.store('person(shamala)')
kb.store('knows(tom, shamala)')
assert kb.neighbors('tom') == [('shamala', [{'pred': 'knows'}])]
kb.node('tom')['grains'] = 0
tom = kb.node('tom')
assert tom.grains == 0
assert tom.i_dont_exist is None... | 0.431105 | 0.53279 |
from __future__ import division
import torch
import math
import random
from PIL import Image, ImageOps, ImageFilter
try:
import accimage
except ImportError:
accimage = None
import scipy.ndimage as ndimage
import numpy as np
import numbers
import types
import collections
class Compose(object):
"""Composes... | util/data_transformer.py | from __future__ import division
import torch
import math
import random
from PIL import Image, ImageOps, ImageFilter
try:
import accimage
except ImportError:
accimage = None
import scipy.ndimage as ndimage
import numpy as np
import numbers
import types
import collections
class Compose(object):
"""Composes... | 0.896707 | 0.473596 |
"""Module containing the BoxResidues class and the command line interface."""
import argparse
from biobb_common.generic.biobb_object import BiobbObject
from biobb_common.configuration import settings
from biobb_common.tools import file_utils as fu
from biobb_common.tools.file_utils import launchlogger
from biobb_vs.u... | biobb_vs/utils/box_residues.py |
"""Module containing the BoxResidues class and the command line interface."""
import argparse
from biobb_common.generic.biobb_object import BiobbObject
from biobb_common.configuration import settings
from biobb_common.tools import file_utils as fu
from biobb_common.tools.file_utils import launchlogger
from biobb_vs.u... | 0.910658 | 0.509825 |
import argparse
import ipaddress
import logging
import os
import re
import sys
from typing import Tuple
from ssl_certinfo import __author__, __email__, __version__, ssl_certinfo, validation
from ssl_certinfo.ssl_certinfo import OutputFormat
VERSION = rf"""
ssl_certinfo {__version__}
Copyright (C) 2020 {__author__} ({... | ssl_certinfo/cli.py | import argparse
import ipaddress
import logging
import os
import re
import sys
from typing import Tuple
from ssl_certinfo import __author__, __email__, __version__, ssl_certinfo, validation
from ssl_certinfo.ssl_certinfo import OutputFormat
VERSION = rf"""
ssl_certinfo {__version__}
Copyright (C) 2020 {__author__} ({... | 0.558086 | 0.173323 |
import unittest
import ..src.common as common_funcs
import ..src.global_settings as global_settings
import ..src.logger as logger
glob = global_settings.settings()
common = common_funcs.init(glob)
glob.log = logger.start_logging("UNITTEST", "unittest" + "_" + glob.time_str + ".log", glob)
class TestBuilder(unittest... | dev/func_tests.py | import unittest
import ..src.common as common_funcs
import ..src.global_settings as global_settings
import ..src.logger as logger
glob = global_settings.settings()
common = common_funcs.init(glob)
glob.log = logger.start_logging("UNITTEST", "unittest" + "_" + glob.time_str + ".log", glob)
class TestBuilder(unittest... | 0.377196 | 0.259472 |
from scrapy.http import Request
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.contrib.linkextractors import LinkExtractor
from neweggs.processors import NeweggProcessor
class NeweggSpider(Spider):
name = 'newegg'
allowed_domains = ['newegg.com']
start_urls = [
... | neweggs/spiders/newegg.py | from scrapy.http import Request
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.contrib.linkextractors import LinkExtractor
from neweggs.processors import NeweggProcessor
class NeweggSpider(Spider):
name = 'newegg'
allowed_domains = ['newegg.com']
start_urls = [
... | 0.478773 | 0.129018 |
import numpy as np
import pandas as pd
import os
import time
import sys
from build_arrays import *
from features import *
from util import *
from config import *
np.set_printoptions(suppress=True)
if __name__ == '__main__':
# Load chosen worm & model information:
home = config['home']
d... | search.py | import numpy as np
import pandas as pd
import os
import time
import sys
from build_arrays import *
from features import *
from util import *
from config import *
np.set_printoptions(suppress=True)
if __name__ == '__main__':
# Load chosen worm & model information:
home = config['home']
d... | 0.241489 | 0.14069 |
import os
import yaml
import launch
import launch_ros
from ament_index_python import get_package_share_directory
def get_package_file(package, file_path):
"""Get the location of a file installed in an ament package"""
package_path = get_package_share_directory(package)
absolute_file_path = os.path.join(pac... | exercises/4.0/ros2/src/myworkcell_support/launch/urdf.launch.py | import os
import yaml
import launch
import launch_ros
from ament_index_python import get_package_share_directory
def get_package_file(package, file_path):
"""Get the location of a file installed in an ament package"""
package_path = get_package_share_directory(package)
absolute_file_path = os.path.join(pac... | 0.426799 | 0.223271 |
from __future__ import unicode_literals
import os
import random
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.db.models import Q
# Create your models here.
'... | src/products/models.py | from __future__ import unicode_literals
import os
import random
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.db.models import Q
# Create your models here.
'... | 0.502686 | 0.118845 |
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import numpy as np
import math
# State vector:
# 0-3: quaternions (q0, q1, q2, q3)
# 4-6: Velocity - m/sec (North, East, Down)
# 7-9: Position - m (North, East, Down)
# 10-12: Delta Angle bias - rad (X,Y,Z)
# 13-14: Wind V... | code/plot_flow.py |
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import numpy as np
import math
# State vector:
# 0-3: quaternions (q0, q1, q2, q3)
# 4-6: Velocity - m/sec (North, East, Down)
# 7-9: Position - m (North, East, Down)
# 10-12: Delta Angle bias - rad (X,Y,Z)
# 13-14: Wind V... | 0.602412 | 0.680772 |
"""The st config."""
import os
import shutil
import sys
import tempfile
import pytest
from mindinsight.datavisual.data_transform.data_manager import DataManager
from mindinsight.lineagemgr.cache_item_updater import LineageCacheItemUpdater
from ....utils import mindspore
from ....utils.mindspore.dataset.engine.seria... | tests/st/func/lineagemgr/conftest.py | """The st config."""
import os
import shutil
import sys
import tempfile
import pytest
from mindinsight.datavisual.data_transform.data_manager import DataManager
from mindinsight.lineagemgr.cache_item_updater import LineageCacheItemUpdater
from ....utils import mindspore
from ....utils.mindspore.dataset.engine.seria... | 0.391406 | 0.186929 |
from __future__ import (
absolute_import,
unicode_literals,
)
import contextlib
import sqlite3
from typing import (
Any,
Generator,
Optional,
Tuple,
cast,
)
from conformity import fields
import six
from pymetrics.publishers.sql import SqlPublisher
__all__ = (
'SqlitePublisher',
)
... | pymetrics/publishers/sqlite.py | from __future__ import (
absolute_import,
unicode_literals,
)
import contextlib
import sqlite3
from typing import (
Any,
Generator,
Optional,
Tuple,
cast,
)
from conformity import fields
import six
from pymetrics.publishers.sql import SqlPublisher
__all__ = (
'SqlitePublisher',
)
... | 0.835484 | 0.111434 |
import cdurllib
import urllib.parse
import tempfile
import os
import time
import cdmsobj
import sys
import errno
import shelve
from .error import CDMSError
MethodNotImplemented = "Method not yet implemented"
SchemeNotSupported = "Scheme not supported: "
LockError = "Lock error:"
TimeOutError = "Wait for read completion... | Lib/cache.py | import cdurllib
import urllib.parse
import tempfile
import os
import time
import cdmsobj
import sys
import errno
import shelve
from .error import CDMSError
MethodNotImplemented = "Method not yet implemented"
SchemeNotSupported = "Scheme not supported: "
LockError = "Lock error:"
TimeOutError = "Wait for read completion... | 0.304352 | 0.087603 |
import numpy as np
from numpy import array, unique, zeros, sort, where, argsort, r_, ones
from numpy import sum as npsum
from datetime import datetime
def RawMigrationDb2AggrRiskDrivers(db,t_start,t_end):
# This function processes the raw database of credit migrations to extract
# the aggregate risk drivers.... | functions_legacy/RawMigrationDb2AggrRiskDrivers.py | import numpy as np
from numpy import array, unique, zeros, sort, where, argsort, r_, ones
from numpy import sum as npsum
from datetime import datetime
def RawMigrationDb2AggrRiskDrivers(db,t_start,t_end):
# This function processes the raw database of credit migrations to extract
# the aggregate risk drivers.... | 0.25303 | 0.572484 |
import mdptoolbox
import mdptoolbox.mdp as mdp
import doctest
import numpy as np
INFINITE_COST = 1e30 # used to denote illegal actions (np.inf does not work)
# The number of states depends on the maximum channel capacity - the maximum number of coins Alice holds initially.
# To keep the number of states at a re... | old/mdpwallet.py | import mdptoolbox
import mdptoolbox.mdp as mdp
import doctest
import numpy as np
INFINITE_COST = 1e30 # used to denote illegal actions (np.inf does not work)
# The number of states depends on the maximum channel capacity - the maximum number of coins Alice holds initially.
# To keep the number of states at a re... | 0.538012 | 0.462655 |
import os
from typing import List, Callable, Union
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
tf.disable_eager_execution() # tensorflow-hub is based on v1 of tf which doesnot support eager mode
class USE(object):
def __init__(self, cache_path):
super(USE, self).... | attacks/sem_sim_model.py |
import os
from typing import List, Callable, Union
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
tf.disable_eager_execution() # tensorflow-hub is based on v1 of tf which doesnot support eager mode
class USE(object):
def __init__(self, cache_path):
super(USE, self).... | 0.807954 | 0.350116 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | stations/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 0.533397 | 0.254104 |
import sys
import textwrap
import argparse
import networkx as nx
from config import *
import re
import os
import math
import random
import numpy as np
def parse_node_name(node_name, max_router, max_host):
try:
val = int(node_name[:-1])
if(node_name[-1] == 'r'):
if(val > max_router):
... | scripts/create_topo_ned_file.py | import sys
import textwrap
import argparse
import networkx as nx
from config import *
import re
import os
import math
import random
import numpy as np
def parse_node_name(node_name, max_router, max_host):
try:
val = int(node_name[:-1])
if(node_name[-1] == 'r'):
if(val > max_router):
... | 0.138899 | 0.215351 |
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('OUTPUT.avi', fourcc, 20.0, (640, 480))
font = cv2.FONT_HERSHEY_SIMPLEX
while cap.isOpened():
_, img = cap.read()
#print(c... | dronecontrol.py | import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('OUTPUT.avi', fourcc, 20.0, (640, 480))
font = cv2.FONT_HERSHEY_SIMPLEX
while cap.isOpened():
_, img = cap.read()
#print(c... | 0.046627 | 0.186299 |
from app.catalog.domain.category import Category
from app.catalog.domain.product import Product
from app.catalog.infra.repository.sql_product_repository import SqlProductRepository
def test_save(db_session):
# Given
product = Product(name='꼬북칩', price=1000, detail='바삭하고 맛이 있지요')
# When
SqlProductRepos... | app/tests/catalog/infra/repository/test_sql_product_repository.py | from app.catalog.domain.category import Category
from app.catalog.domain.product import Product
from app.catalog.infra.repository.sql_product_repository import SqlProductRepository
def test_save(db_session):
# Given
product = Product(name='꼬북칩', price=1000, detail='바삭하고 맛이 있지요')
# When
SqlProductRepos... | 0.567577 | 0.506713 |
import os
import numpy as np
import h5py
from PIL import Image
from numpy.core.shape_base import stack
from utils.data_io import numpy2image, image2numpy
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']
def read_images_from_folder(data_path, img_size=224, img_nc=3):
img_list = sorted([f for f i... | dataloader/aligned_dataset.py | import os
import numpy as np
import h5py
from PIL import Image
from numpy.core.shape_base import stack
from utils.data_io import numpy2image, image2numpy
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']
def read_images_from_folder(data_path, img_size=224, img_nc=3):
img_list = sorted([f for f i... | 0.214774 | 0.347842 |
from ... pyaz_utils import _call_az
from . import file, subtask
def create(job_id, account_endpoint=None, account_key=None, account_name=None, affinity_id=None, application_package_references=None, command_line=None, environment_settings=None, json_file=None, max_task_retry_count=None, max_wall_clock_time=None, resou... | pyaz/batch/task/__init__.py | from ... pyaz_utils import _call_az
from . import file, subtask
def create(job_id, account_endpoint=None, account_key=None, account_name=None, affinity_id=None, application_package_references=None, command_line=None, environment_settings=None, json_file=None, max_task_retry_count=None, max_wall_clock_time=None, resou... | 0.795857 | 0.262354 |
import numpy as np
from typing import Tuple
from IMLearn.metalearners.adaboost import AdaBoost
from IMLearn.learners.classifiers import DecisionStump
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.nd... | exercises/adaboost_scenario.py | import numpy as np
from typing import Tuple
from IMLearn.metalearners.adaboost import AdaBoost
from IMLearn.learners.classifiers import DecisionStump
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.nd... | 0.911316 | 0.681789 |
from __future__ import print_function
import numpy as np
import pickle
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter
import datetime
# TODO: maybe would be cleaner to put this as functions rather than script
class BandPass(object):
"""A class to perform bandpass filtering using Butter ... | processing_scripts/filter_resample_csvWrite_acceleration.py | from __future__ import print_function
import numpy as np
import pickle
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter
import datetime
# TODO: maybe would be cleaner to put this as functions rather than script
class BandPass(object):
"""A class to perform bandpass filtering using Butter ... | 0.412294 | 0.260766 |
from amuse.test import amusetest
import numpy
class harmonic_oscillator(object):
def __init__(self,x,v,method=None):
self.x=x
self.v=v
self.model_time=0
self.method=method
def kick(self,dt):
self.v+=-self.x*dt
def drift(self,dt):
self.x+=self.v*dt
def total_energy(self):
return (se... | src/amuse/test/suite/ext_tests/test_composition_methods.py | from amuse.test import amusetest
import numpy
class harmonic_oscillator(object):
def __init__(self,x,v,method=None):
self.x=x
self.v=v
self.model_time=0
self.method=method
def kick(self,dt):
self.v+=-self.x*dt
def drift(self,dt):
self.x+=self.v*dt
def total_energy(self):
return (se... | 0.544801 | 0.171685 |
import base64
import io
import pandas as pd
import matplotlib.pyplot as plt
from cachetools import cached, TTLCache
from statsmodels.tsa.arima_model import ARIMA
from flask import Flask, request, render_template, jsonify, abort
app = Flask(__name__)
categories = ['confirmed_US', 'confirmed_global', 'deaths_US', 'de... | src/app.py | import base64
import io
import pandas as pd
import matplotlib.pyplot as plt
from cachetools import cached, TTLCache
from statsmodels.tsa.arima_model import ARIMA
from flask import Flask, request, render_template, jsonify, abort
app = Flask(__name__)
categories = ['confirmed_US', 'confirmed_global', 'deaths_US', 'de... | 0.511717 | 0.186077 |
import lxml.html
import lxml.etree
def remove(obj):
obj.getparent().remove(obj)
def remove_all(document, *paths):
for path in paths:
for obj in document.findall(path):
remove(obj)
def pacify(obj):
obj.tag = 'span'
def pacify_all(document, *paths):
for path in paths:
for ... | tidy.py |
import lxml.html
import lxml.etree
def remove(obj):
obj.getparent().remove(obj)
def remove_all(document, *paths):
for path in paths:
for obj in document.findall(path):
remove(obj)
def pacify(obj):
obj.tag = 'span'
def pacify_all(document, *paths):
for path in paths:
for ... | 0.214362 | 0.057812 |
import psutil, base64, os, sys, hashlib, datetime, discord, random
from PIL import Image, ImageDraw, ImageFont
import configparser
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta
if __name__=="__main__":
print("FATAL : Run this bot from right way.")
sys.exit(1)
e_... | modules/m_etc.py | import psutil, base64, os, sys, hashlib, datetime, discord, random
from PIL import Image, ImageDraw, ImageFont
import configparser
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta
if __name__=="__main__":
print("FATAL : Run this bot from right way.")
sys.exit(1)
e_... | 0.121308 | 0.282153 |
import frappe
import json
from empg_erp.utils import get_post_body,get_config_by_name,str_to_date
from datetime import datetime, timedelta
import time
from empg_erp.modules.common.error_handler import ErrorHandler
from empg_erp.modules.mustang.employee.employee_roster import EmployeeRoster
from empg_erp.constants.globa... | empg_erp/modules/mustang/attendance/sync_attendance.py | import frappe
import json
from empg_erp.utils import get_post_body,get_config_by_name,str_to_date
from datetime import datetime, timedelta
import time
from empg_erp.modules.common.error_handler import ErrorHandler
from empg_erp.modules.mustang.employee.employee_roster import EmployeeRoster
from empg_erp.constants.globa... | 0.21767 | 0.063453 |
import sys
import nltk
nltk.download(['punkt', 'wordnet', 'stopwords', 'averaged_perceptron_tagger'])
import pandas as pd
import numpy as np
import re
import pickle
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus im... | models/train_classifier.py | import sys
import nltk
nltk.download(['punkt', 'wordnet', 'stopwords', 'averaged_perceptron_tagger'])
import pandas as pd
import numpy as np
import re
import pickle
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus im... | 0.531696 | 0.425963 |
from collections import namedtuple
import io
import os
import git
import pexpect
import pytest
Command = namedtuple('Command', ('cmd', 'return_code', 'out'))
class Koan:
TIMEOUT = 3
def __init__(self, tmpdir_factory):
self.verbose = False
self._workspace = tmpdir_factory.mktemp('workspace'... | git_koan/koan.py | from collections import namedtuple
import io
import os
import git
import pexpect
import pytest
Command = namedtuple('Command', ('cmd', 'return_code', 'out'))
class Koan:
TIMEOUT = 3
def __init__(self, tmpdir_factory):
self.verbose = False
self._workspace = tmpdir_factory.mktemp('workspace'... | 0.596433 | 0.236362 |
from sklearn.metrics import confusion_matrix, f1_score, roc_curve
import numpy as np
import pandas as pd
class analysis:
def __init__(self):
pass
def _getComplexParams(self, abs=False):
"""
Function for extracting the data associated with
the second component of the complex source.
To call:
_getComp... | regularized/analysis.py | from sklearn.metrics import confusion_matrix, f1_score, roc_curve
import numpy as np
import pandas as pd
class analysis:
def __init__(self):
pass
def _getComplexParams(self, abs=False):
"""
Function for extracting the data associated with
the second component of the complex source.
To call:
_getComp... | 0.566858 | 0.495606 |
import datetime
import os
import boto3
import dateutil.parser
import dateutil.tz
from make_table import ScrapedJob, session_scope
SQS_QUEUE = os.environ.get('SQS_QUEUE')
SQS_REGION = os.environ.get('SQS_REGION')
RDS_CREDENTIALS = os.environ.get('RDS_CREDENTIALS')
def reformat_sqs_message(message):
job = {}
... | poll_sqs.py | import datetime
import os
import boto3
import dateutil.parser
import dateutil.tz
from make_table import ScrapedJob, session_scope
SQS_QUEUE = os.environ.get('SQS_QUEUE')
SQS_REGION = os.environ.get('SQS_REGION')
RDS_CREDENTIALS = os.environ.get('RDS_CREDENTIALS')
def reformat_sqs_message(message):
job = {}
... | 0.27513 | 0.068475 |
import logging
from argparse import Namespace, ArgumentParser
from typing import Final, Optional
import jupiter.command.command as command
from jupiter.domain.adate import ADate
from jupiter.use_cases.metrics.entry.update import MetricEntryUpdateUseCase
from jupiter.framework.update_action import UpdateAction
from ju... | jupiter/command/metric_entry_update.py |
import logging
from argparse import Namespace, ArgumentParser
from typing import Final, Optional
import jupiter.command.command as command
from jupiter.domain.adate import ADate
from jupiter.use_cases.metrics.entry.update import MetricEntryUpdateUseCase
from jupiter.framework.update_action import UpdateAction
from ju... | 0.93878 | 0.111096 |
import textwrap
import unittest
from mock import patch
class TestParseVagrantMachineReadableBoxList(unittest.TestCase):
def test_machine_readable_box_list(self):
with patch('fabtools.vagrant.local') as mock_local:
mock_local.return_value = textwrap.dedent(r"""
1391708688,,box... | fabtools/tests/test_vagrant_base_boxes.py | import textwrap
import unittest
from mock import patch
class TestParseVagrantMachineReadableBoxList(unittest.TestCase):
def test_machine_readable_box_list(self):
with patch('fabtools.vagrant.local') as mock_local:
mock_local.return_value = textwrap.dedent(r"""
1391708688,,box... | 0.453746 | 0.174024 |
from PIL import Image
from django.conf import settings
from django.core.exceptions import ValidationError
def _is_allowed_extension(image, valid_extensions):
img = Image.open(image)
if img.format.lower() not in valid_extensions:
return False
return True
def _is_image_width_less_than_or_equal(im,... | Validators/image_validators.py | from PIL import Image
from django.conf import settings
from django.core.exceptions import ValidationError
def _is_allowed_extension(image, valid_extensions):
img = Image.open(image)
if img.format.lower() not in valid_extensions:
return False
return True
def _is_image_width_less_than_or_equal(im,... | 0.538255 | 0.170128 |
import requests
from lxml import etree
from bs4 import BeautifulSoup
import os
import re
class RSpider:
def __init__(self):
self.url = 'http://www.kekenet.com/Article/media/economist/'
def get_html(self, url):
try:
# print(url)
html = requests.get(url=url)
... | EngLearner/mainsys/readSpider.py | import requests
from lxml import etree
from bs4 import BeautifulSoup
import os
import re
class RSpider:
def __init__(self):
self.url = 'http://www.kekenet.com/Article/media/economist/'
def get_html(self, url):
try:
# print(url)
html = requests.get(url=url)
... | 0.067651 | 0.061819 |
import unittest
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.operators.symplectic import PauliTable, pauli_basis
class TestPauliBasis(QiskitTestCase):
"""Test pauli_basis function"""
def test_standard_order_1q(self):
"""Test 1-qubit pauli_basis function."""
labels = ["I", ... | test/python/quantum_info/operators/symplectic/test_pauli_utils.py | import unittest
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.operators.symplectic import PauliTable, pauli_basis
class TestPauliBasis(QiskitTestCase):
"""Test pauli_basis function"""
def test_standard_order_1q(self):
"""Test 1-qubit pauli_basis function."""
labels = ["I", ... | 0.757256 | 0.759359 |
import math
from PySide import QtCore, QtGui
class View(QtGui.QGraphicsView):
'''A View supporting smooth panning and zooming. Use Alt+Left Mouse to
pan and Alt+Middle or Right Mouse to zoom. Dragging without Alt drags out
a selection marquee.
.. seealso::
Documentation for :class:`QtGui.QGr... | nodify/view.py | import math
from PySide import QtCore, QtGui
class View(QtGui.QGraphicsView):
'''A View supporting smooth panning and zooming. Use Alt+Left Mouse to
pan and Alt+Middle or Right Mouse to zoom. Dragging without Alt drags out
a selection marquee.
.. seealso::
Documentation for :class:`QtGui.QGr... | 0.615435 | 0.244758 |
import logging
logger = logging.getLogger(__name__)
class ConstIterations:
"""Stopping Criterion: After certain iterations
Args:
num_iters (:obj:`int`): Number of iterations
Attributes:
num_iters (:obj:`int`): Number of iterations
cur_iter (:obj:`int`): Current number of iterati... | pyActLearn/learning/nn/criterion.py | import logging
logger = logging.getLogger(__name__)
class ConstIterations:
"""Stopping Criterion: After certain iterations
Args:
num_iters (:obj:`int`): Number of iterations
Attributes:
num_iters (:obj:`int`): Number of iterations
cur_iter (:obj:`int`): Current number of iterati... | 0.865352 | 0.367327 |
from flask_app import flask_app,db
from datetime import datetime
enable_search = True
import flask_whooshalchemy as whooshalchemy
class Message(db.Model):
#Note the __bind_key__ below --> as this table is going to a different database
__bind_key__ = 'message'
id = db.Column(db.Integer, primary_key=True)
... | flask_app/models.py | from flask_app import flask_app,db
from datetime import datetime
enable_search = True
import flask_whooshalchemy as whooshalchemy
class Message(db.Model):
#Note the __bind_key__ below --> as this table is going to a different database
__bind_key__ = 'message'
id = db.Column(db.Integer, primary_key=True)
... | 0.425844 | 0.080177 |
import numpy as np
import scipy as sp
import scipy.spatial.distance
from .. import kernels
import itertools
import numpy.random as npr
import collections
Tile=collections.namedtuple('Tile',['look','grab','put'])
MultiTile=collections.namedtuple('MultiTile',['look','grab','put'])
def downsample_multitile(mt,ds):
... | bardensr/singlefov/tiling.py | import numpy as np
import scipy as sp
import scipy.spatial.distance
from .. import kernels
import itertools
import numpy.random as npr
import collections
Tile=collections.namedtuple('Tile',['look','grab','put'])
MultiTile=collections.namedtuple('MultiTile',['look','grab','put'])
def downsample_multitile(mt,ds):
... | 0.233619 | 0.42662 |
import sys
import json
import socket
import spotipy
import asyncio
import webbrowser
from time import time
from spotipy import oauth2
from config import *
def listen_for_callback_code():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', int(redirect_uri.split(":")[-1])))
s.listen... | spotify.py | import sys
import json
import socket
import spotipy
import asyncio
import webbrowser
from time import time
from spotipy import oauth2
from config import *
def listen_for_callback_code():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', int(redirect_uri.split(":")[-1])))
s.listen... | 0.152221 | 0.120155 |
import csv
import xml.etree.ElementTree as ET
from json import load
from typing import Dict, List, Tuple, Text, Set
def webprocessing(a: Dict, b: List, c: Text, d: Text = "") -> Tuple[Dict, Text]:
"""
:param a: temporary account storage
:param b: ref to xml object (groups, accounts, logins)
:param c... | passexporter.py | import csv
import xml.etree.ElementTree as ET
from json import load
from typing import Dict, List, Tuple, Text, Set
def webprocessing(a: Dict, b: List, c: Text, d: Text = "") -> Tuple[Dict, Text]:
"""
:param a: temporary account storage
:param b: ref to xml object (groups, accounts, logins)
:param c... | 0.466359 | 0.280687 |
import json
from django.db import models
from django.forms import model_to_dict
import six
class DefaultContextSerializer(object):
"""
Default class for serializing context data
"""
def __init__(self, context):
super(DefaultContextSerializer, self).__init__()
self.context = context
... | entity_event/context_serializer.py | import json
from django.db import models
from django.forms import model_to_dict
import six
class DefaultContextSerializer(object):
"""
Default class for serializing context data
"""
def __init__(self, context):
super(DefaultContextSerializer, self).__init__()
self.context = context
... | 0.786869 | 0.3027 |
import os
import json
import pickle
import pandas as pd
import tensorflow as tf
from NCF import NCF
from dataset.dataset import Dataset
from dataset.python_splitters import python_chrono_split
from evaluate import evaluate_model_spark
from grid_search import GridSearch
flags = tf.app.flags
flags.DEFINE_string("data"... | training/training_code/train_ncf.py | import os
import json
import pickle
import pandas as pd
import tensorflow as tf
from NCF import NCF
from dataset.dataset import Dataset
from dataset.python_splitters import python_chrono_split
from evaluate import evaluate_model_spark
from grid_search import GridSearch
flags = tf.app.flags
flags.DEFINE_string("data"... | 0.617167 | 0.204362 |
import argparse
import logging
import math
import random
from argparse import ArgumentParser, ArgumentTypeError, FileType
import ignite
import torch
from ignite.engine import Engine, Events, State, create_supervised_evaluator, create_supervised_trainer
from ignite.handlers import EarlyStopping, Timer
from ignite.metri... | sock/cli/train/__main__.py | import argparse
import logging
import math
import random
from argparse import ArgumentParser, ArgumentTypeError, FileType
import ignite
import torch
from ignite.engine import Engine, Events, State, create_supervised_evaluator, create_supervised_trainer
from ignite.handlers import EarlyStopping, Timer
from ignite.metri... | 0.771198 | 0.307228 |
import json
import pytest
from pathlib import Path
from django.conf import settings
from snoop.data import models, filesystem
from snoop.data.analyzers import archives
from snoop.data.utils import time_from_unix
pytestmark = [pytest.mark.django_db]
STOCK_PHOTO = {
'blob_pk': 'f7281c8a9cc404816f019382bd121c5fff28e... | testsuite/test_archives.py | import json
import pytest
from pathlib import Path
from django.conf import settings
from snoop.data import models, filesystem
from snoop.data.analyzers import archives
from snoop.data.utils import time_from_unix
pytestmark = [pytest.mark.django_db]
STOCK_PHOTO = {
'blob_pk': 'f7281c8a9cc404816f019382bd121c5fff28e... | 0.322313 | 0.326459 |
from .function import Function
# Instantiate one of each function class to use
data = []
#region Basic IO
def o(variable):
print(variable.value, end='')
data.append(Function('o', 1, o))
def O(variable):
print(variable.value, end='')
quit()
data.append(Function('O', 1, O))
def p(variable):
print(var... | flog/functions/__init__.py | from .function import Function
# Instantiate one of each function class to use
data = []
#region Basic IO
def o(variable):
print(variable.value, end='')
data.append(Function('o', 1, o))
def O(variable):
print(variable.value, end='')
quit()
data.append(Function('O', 1, O))
def p(variable):
print(var... | 0.114579 | 0.378746 |
import sys
import os
import matplotlib.pyplot as plt
import logging
from nukleus.SexpWriter import SexpWriter
sys.path.append('src')
sys.path.append('../src')
import nukleus
from nukleus.draw import Dot, Label, Line, Element
from nukleus import Circuit
from nukleus.Netlist import Netlist
from nukleus.spice.Potentio... | samples/draw2.py | import sys
import os
import matplotlib.pyplot as plt
import logging
from nukleus.SexpWriter import SexpWriter
sys.path.append('src')
sys.path.append('../src')
import nukleus
from nukleus.draw import Dot, Label, Line, Element
from nukleus import Circuit
from nukleus.Netlist import Netlist
from nukleus.spice.Potentio... | 0.301259 | 0.256395 |
import json as _json
import logging
import os
import time
from logging.config import dictConfig
from attr import attrib, attrs, validators
from dateutil.parser import isoparse
from flask import Blueprint, Flask, current_app, make_response, request
from .auth import authenticate
from .rate_limiter import limiter
bp =... | nad_logging_service/nad_logging_service/logger.py | import json as _json
import logging
import os
import time
from logging.config import dictConfig
from attr import attrib, attrs, validators
from dateutil.parser import isoparse
from flask import Blueprint, Flask, current_app, make_response, request
from .auth import authenticate
from .rate_limiter import limiter
bp =... | 0.413477 | 0.073463 |
from __future__ import print_function
from __future__ import absolute_import
import inspect
from .util import *
from .base_nodes import PyNode
# Base class for all Value Literals
class PyValueLiteral(PyNode):
tag = "value_literal"
def __init__(self, lineno, value):
super(PyValueLiteral,self).__init_... | pyxie/model/pynodes/values.py |
from __future__ import print_function
from __future__ import absolute_import
import inspect
from .util import *
from .base_nodes import PyNode
# Base class for all Value Literals
class PyValueLiteral(PyNode):
tag = "value_literal"
def __init__(self, lineno, value):
super(PyValueLiteral,self).__init_... | 0.488039 | 0.143308 |
import sys
import json
from .common import team_users_lower, dialog_min_len
def calc_score(q):
if len(q) > 0:
return sum(q) / float(len(q))
else:
return 0
user_evaluations = dict()
user_names = dict()
user_bots = dict()
lines = sys.stdin.readlines()
for line in lines:
d = json.loads(l... | utils/user_leaderboard.py |
import sys
import json
from .common import team_users_lower, dialog_min_len
def calc_score(q):
if len(q) > 0:
return sum(q) / float(len(q))
else:
return 0
user_evaluations = dict()
user_names = dict()
user_bots = dict()
lines = sys.stdin.readlines()
for line in lines:
d = json.loads(l... | 0.101045 | 0.126731 |
import os
import logging
import numpy as np
from math import ceil, floor
from PIL import Image, ImageDraw, ImageFont
from configs.paths import EVAL_DIR
log = logging.getLogger()
colors = np.load(os.path.join(EVAL_DIR, 'Extra/colors.npy')).tolist()
palette = np.load(os.path.join(EVAL_DIR, 'Extra/palette.npy')).tolist... | utils/utils_bbox.py | import os
import logging
import numpy as np
from math import ceil, floor
from PIL import Image, ImageDraw, ImageFont
from configs.paths import EVAL_DIR
log = logging.getLogger()
colors = np.load(os.path.join(EVAL_DIR, 'Extra/colors.npy')).tolist()
palette = np.load(os.path.join(EVAL_DIR, 'Extra/palette.npy')).tolist... | 0.550849 | 0.383641 |
import pytest
from os.path import join
import numpy as np
import pandas as pd
from delphi_jhu.geo import geo_map, INCIDENCE_BASE
from delphi_utils import GeoMapper
class TestGeoMap:
def test_incorrect_geo(self, jhu_confirmed_test_data):
df = jhu_confirmed_test_data
with pytest.raises(ValueError... | jhu/tests/test_geo.py | import pytest
from os.path import join
import numpy as np
import pandas as pd
from delphi_jhu.geo import geo_map, INCIDENCE_BASE
from delphi_utils import GeoMapper
class TestGeoMap:
def test_incorrect_geo(self, jhu_confirmed_test_data):
df = jhu_confirmed_test_data
with pytest.raises(ValueError... | 0.659844 | 0.676339 |
import numpy as np
from scipy import ndimage
from scipy import misc
from PIL import Image
import torch
import torch.nn.functional as tf
import skimage.io as io
import png
TAG_CHAR = np.array([202021.25], np.float32)
UNKNOWN_FLOW_THRESH = 1e7
def compute_color(u, v):
"""
compute optical flow color map
:... | demo/demo_generator/utils_misc.py | import numpy as np
from scipy import ndimage
from scipy import misc
from PIL import Image
import torch
import torch.nn.functional as tf
import skimage.io as io
import png
TAG_CHAR = np.array([202021.25], np.float32)
UNKNOWN_FLOW_THRESH = 1e7
def compute_color(u, v):
"""
compute optical flow color map
:... | 0.74512 | 0.55097 |
from __future__ import annotations
from dataclasses import astuple, dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, Callable, Generic, Iterator, TypeVar
from dcor._dcor_internals import _af_inv_scaled
from ._dcor_internals import (
MatrixCentered,
_distance_matrix,
_u_distance_matr... | dcor/_dcor.py | from __future__ import annotations
from dataclasses import astuple, dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, Callable, Generic, Iterator, TypeVar
from dcor._dcor_internals import _af_inv_scaled
from ._dcor_internals import (
MatrixCentered,
_distance_matrix,
_u_distance_matr... | 0.919643 | 0.166337 |
import argparse
import logging
import os
import pandas as pd
from vlne.eval.eval import eval_model
from vlne.data.data_generator import DataSmear
from vlne.plot.profile import plot_profile
from vlne.presets import PRESETS_EVAL
from vlne.utils import setup_logging
from vlne.u... | scripts/studies/make_input_importance_plot_via_perturb.py | import argparse
import logging
import os
import pandas as pd
from vlne.eval.eval import eval_model
from vlne.data.data_generator import DataSmear
from vlne.plot.profile import plot_profile
from vlne.presets import PRESETS_EVAL
from vlne.utils import setup_logging
from vlne.u... | 0.592431 | 0.211722 |
from creator.files.models import File
from creator.events.models import Event
from creator.studies.factories import StudyFactory
from django.contrib.auth import get_user_model
User = get_user_model()
UPDATE_FILE = """
mutation (
$kfId:String!,
$description: String!,
$name: String!,
$fileType: FileTyp... | tests/events/test_files.py | from creator.files.models import File
from creator.events.models import Event
from creator.studies.factories import StudyFactory
from django.contrib.auth import get_user_model
User = get_user_model()
UPDATE_FILE = """
mutation (
$kfId:String!,
$description: String!,
$name: String!,
$fileType: FileTyp... | 0.475118 | 0.328785 |
from django.db import models
# Creating Database models for Market Indicies:
# The SPY 500 Index Composition:
class SPYIndexComposition(models.Model):
"""A data model representing a database table containing information
on the S&P500 market index composition.
It is built for the velkozz API with the ETL... | velkozz_web_api/apps/finance_api/models/market_indicies/market_indicies_models.py | from django.db import models
# Creating Database models for Market Indicies:
# The SPY 500 Index Composition:
class SPYIndexComposition(models.Model):
"""A data model representing a database table containing information
on the S&P500 market index composition.
It is built for the velkozz API with the ETL... | 0.820829 | 0.50238 |
import json
import os
import uuid
from typing import Any, Dict
import boto3 # type: ignore
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.logging.correlation_paths import API_GATEWAY_HTTP
logger = Logger()
tracer = Tracer()
# Pull out the DynamoDB table name from the environment
table_n... | src/app.py | import json
import os
import uuid
from typing import Any, Dict
import boto3 # type: ignore
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.logging.correlation_paths import API_GATEWAY_HTTP
logger = Logger()
tracer = Tracer()
# Pull out the DynamoDB table name from the environment
table_n... | 0.760517 | 0.116814 |
import pytest
from marshmallow import Schema, fields, RAISE, INCLUDE, EXCLUDE
from marshmallow_jsonschema import UnsupportedValueError, JSONSchema
from . import validate_and_dump
def test_additional_properties_default():
class TestSchema(Schema):
foo = fields.Integer()
schema = TestSchema()
dum... | tests/test_additional_properties.py | import pytest
from marshmallow import Schema, fields, RAISE, INCLUDE, EXCLUDE
from marshmallow_jsonschema import UnsupportedValueError, JSONSchema
from . import validate_and_dump
def test_additional_properties_default():
class TestSchema(Schema):
foo = fields.Integer()
schema = TestSchema()
dum... | 0.581303 | 0.349533 |
import numpy as _np
import os as _os
import hyperopt as _hyperopt
import time as _time
import functools as _functools
import warnings as _warnings
import matplotlib.pyplot as _plt
import sklearn.model_selection as _sklearn_model_selection
from .. import NeuralNet as _NeuralNet
from ... import file_utils as _file_utils... | pyDSlib/ML/model_selection/_search.py | import numpy as _np
import os as _os
import hyperopt as _hyperopt
import time as _time
import functools as _functools
import warnings as _warnings
import matplotlib.pyplot as _plt
import sklearn.model_selection as _sklearn_model_selection
from .. import NeuralNet as _NeuralNet
from ... import file_utils as _file_utils... | 0.596316 | 0.209955 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensor2tensor.layers import gaussian_process
from tensor2tensor.utils import test_utils
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
class GaussianProcessTest(tf.tes... | t2t_bert/utils/tensor2tensor/layers/gaussian_process_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensor2tensor.layers import gaussian_process
from tensor2tensor.utils import test_utils
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
class GaussianProcessTest(tf.tes... | 0.931936 | 0.505066 |
from pandas import json_normalize
def activities_to_frame(data):
'''
Takes a data drilling activity object which is a dict from the Collabor8 response and
flattens it into a normalized data fram table to be used for further processing
Structure coming in from the Collabor8 drilling activity objec... | subsurfaceCollabor8/drilling_frames.py | from pandas import json_normalize
def activities_to_frame(data):
'''
Takes a data drilling activity object which is a dict from the Collabor8 response and
flattens it into a normalized data fram table to be used for further processing
Structure coming in from the Collabor8 drilling activity objec... | 0.821939 | 0.662514 |
import grpc
from google.cloud.devtools.cloudbuild_v1.proto import (
cloudbuild_pb2 as google_dot_devtools_dot_cloudbuild__v1_dot_proto_dot_cloudbuild__pb2,
)
from google.longrunning import (
operations_pb2 as google_dot_longrunning_dot_operations__pb2,
)
from google.protobuf import empty_pb2 as google_dot_prot... | cloudbuild/google/cloud/devtools/cloudbuild_v1/proto/cloudbuild_pb2_grpc.py | import grpc
from google.cloud.devtools.cloudbuild_v1.proto import (
cloudbuild_pb2 as google_dot_devtools_dot_cloudbuild__v1_dot_proto_dot_cloudbuild__pb2,
)
from google.longrunning import (
operations_pb2 as google_dot_longrunning_dot_operations__pb2,
)
from google.protobuf import empty_pb2 as google_dot_prot... | 0.612889 | 0.078184 |
import sys
import pathlib
from PySide6 import QtCore, QtWidgets, QtGui
from classes import DowTagEditor
from classes import DowConfig
from classes import DowDatabase
from classes import DowMimeType
from classes import DowGlImage
class MainWidget(QtWidgets.QWidget):
def __init__(self, app):
super().__init__()
... | dow/tag_editor.py | import sys
import pathlib
from PySide6 import QtCore, QtWidgets, QtGui
from classes import DowTagEditor
from classes import DowConfig
from classes import DowDatabase
from classes import DowMimeType
from classes import DowGlImage
class MainWidget(QtWidgets.QWidget):
def __init__(self, app):
super().__init__()
... | 0.307982 | 0.059866 |
ANSIBLE_METADATA = {
'metadata_version': '0.2',
'status': ['preview'],
'supported_by': 'godspeed-you'
}
DOCUMENTATION = """
---
module: pvesh
short_description: Managing Proxmox Nodes and Cluster through the command line tool pvesh
description: With the C(pvesh) module it is possible to use the Proxmox ... | pvesh.py |
ANSIBLE_METADATA = {
'metadata_version': '0.2',
'status': ['preview'],
'supported_by': 'godspeed-you'
}
DOCUMENTATION = """
---
module: pvesh
short_description: Managing Proxmox Nodes and Cluster through the command line tool pvesh
description: With the C(pvesh) module it is possible to use the Proxmox ... | 0.473901 | 0.353205 |
from onagame2015.validations import coord_in_arena, direction_is_valid
from onagame2015.lib import (
GameBaseObject,
Coordinate,
UNIT_TYPE_ATTACK,
UNIT_TYPE_BLOCKED,
UNIT_TYPE_HQ,
)
class BaseUnit(GameBaseObject):
def __init__(self, coordinate, player_id, arena):
self.id = id(self)
... | onagame2015/units.py | from onagame2015.validations import coord_in_arena, direction_is_valid
from onagame2015.lib import (
GameBaseObject,
Coordinate,
UNIT_TYPE_ATTACK,
UNIT_TYPE_BLOCKED,
UNIT_TYPE_HQ,
)
class BaseUnit(GameBaseObject):
def __init__(self, coordinate, player_id, arena):
self.id = id(self)
... | 0.708515 | 0.36139 |
import json
import logging
import time
from urllib.request import urlopen, Request
from logging import Formatter, LogRecord
from newrelic.api.time_trace import get_linking_metadata
from newrelic.common.object_names import parse_exc_info
from newrelic.core.config import is_expected_error
def format_exc_info(exc_inf... | newrelic/api/log.py |
import json
import logging
import time
from urllib.request import urlopen, Request
from logging import Formatter, LogRecord
from newrelic.api.time_trace import get_linking_metadata
from newrelic.common.object_names import parse_exc_info
from newrelic.core.config import is_expected_error
def format_exc_info(exc_inf... | 0.554953 | 0.144028 |
import json
import boto3
from boto3.dynamodb.conditions import Key
import datetime
from datetime import datetime, timedelta, date
dynamodb = boto3.resource('dynamodb', region_name='eu-west-2')
def lambda_handler(event, context):
room_to_be_booked = query_room(event)
room_capacity = int(room_to_be_booked[0][... | infrastructure/lambda-functions/add-booking.py | import json
import boto3
from boto3.dynamodb.conditions import Key
import datetime
from datetime import datetime, timedelta, date
dynamodb = boto3.resource('dynamodb', region_name='eu-west-2')
def lambda_handler(event, context):
room_to_be_booked = query_room(event)
room_capacity = int(room_to_be_booked[0][... | 0.168686 | 0.103115 |
import argparse
import textwrap
from starthinker.util.configuration import Configuration
from starthinker.task.dataset.run import dataset
from starthinker.task.google_api.run import google_api
from starthinker.task.bigquery.run import bigquery
def recipe_barnacle_dv360(config, auth_read, auth_write, partner, recipe... | examples/barnacle_dv360_example.py |
import argparse
import textwrap
from starthinker.util.configuration import Configuration
from starthinker.task.dataset.run import dataset
from starthinker.task.google_api.run import google_api
from starthinker.task.bigquery.run import bigquery
def recipe_barnacle_dv360(config, auth_read, auth_write, partner, recipe... | 0.546012 | 0.167593 |
from __future__ import absolute_import, division, print_function
from ansible.module_utils.six import iteritems
try:
from openshift.helper.kubernetes import KubernetesObjectHelper
from openshift.helper.openshift import OpenShiftObjectHelper
from openshift.helper.exceptions import KubernetesException
... | myven/lib/python3.8/site-packages/ansible/module_utils/k8s/inventory.py |
from __future__ import absolute_import, division, print_function
from ansible.module_utils.six import iteritems
try:
from openshift.helper.kubernetes import KubernetesObjectHelper
from openshift.helper.openshift import OpenShiftObjectHelper
from openshift.helper.exceptions import KubernetesException
... | 0.586286 | 0.091707 |
from musx import Score, Note, Seq, MidiFile, keynum
def sierpinski(score, tone, shape, trans, levels, dur, amp):
"""
Generates a melodic shape based on successive transpositions (levels) of
itself.
Parameters
----------
score : Score
The musical score to add events to.
tone :... | demos/sierpinski.py | from musx import Score, Note, Seq, MidiFile, keynum
def sierpinski(score, tone, shape, trans, levels, dur, amp):
"""
Generates a melodic shape based on successive transpositions (levels) of
itself.
Parameters
----------
score : Score
The musical score to add events to.
tone :... | 0.621885 | 0.494385 |
from datetime import date, timedelta
from django.test import TestCase
from django.urls import reverse
from bookclubs.models import User, Book, Club, Meeting, MeetingAttendance, Role
from bookclubs.tests.helpers import reverse_with_next
class MeetingListViewTestCase(TestCase):
"""Tests for showing list of club m... | bookclubs/tests/views/meeting_views/test_meeting_list_view.py | from datetime import date, timedelta
from django.test import TestCase
from django.urls import reverse
from bookclubs.models import User, Book, Club, Meeting, MeetingAttendance, Role
from bookclubs.tests.helpers import reverse_with_next
class MeetingListViewTestCase(TestCase):
"""Tests for showing list of club m... | 0.585101 | 0.169767 |
import argparse
import multiprocessing
import sys
import orcha.properties
from ..plugins import ListPlugin, query_plugins
from ..utils.logging_utils import get_logger
from ..utils.packages import version
# application universal logger
log = get_logger()
def main():
"""Main application entry point. Multiple arg... | orcha/bin/main.py | import argparse
import multiprocessing
import sys
import orcha.properties
from ..plugins import ListPlugin, query_plugins
from ..utils.logging_utils import get_logger
from ..utils.packages import version
# application universal logger
log = get_logger()
def main():
"""Main application entry point. Multiple arg... | 0.498291 | 0.202798 |
import hashlib
import struct
from collections import OrderedDict
from typing import IO, Any, Optional, Iterable, Mapping, Dict, \
NamedTuple, ClassVar, TypeVar, Type
from pymap.mailbox import MailboxSnapshot
from .io import FileWriteable
__all__ = ['Record', 'UidList']
_UDT = TypeVar('_UDT', bound='UidList')
... | pymap/backend/maildir/uidlist.py | import hashlib
import struct
from collections import OrderedDict
from typing import IO, Any, Optional, Iterable, Mapping, Dict, \
NamedTuple, ClassVar, TypeVar, Type
from pymap.mailbox import MailboxSnapshot
from .io import FileWriteable
__all__ = ['Record', 'UidList']
_UDT = TypeVar('_UDT', bound='UidList')
... | 0.890223 | 0.247993 |
from typing import Optional
import traceback
import os
import sqlite3
import time
import re
from threading import Thread
from flask import render_template, jsonify
import requests
from framework import path_data, scheduler, app, db, celery
from framework.common.plugin import LogicModuleBase, default_route_socketio
f... | main.py | from typing import Optional
import traceback
import os
import sqlite3
import time
import re
from threading import Thread
from flask import render_template, jsonify
import requests
from framework import path_data, scheduler, app, db, celery
from framework.common.plugin import LogicModuleBase, default_route_socketio
f... | 0.52902 | 0.072703 |
from msrest.service_client import SDKClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .version import VERSION
from .operations.clusters_operations import ClustersOperations
from .operations.cluster_versions_operations import ClusterVersionsOperations
from .operations.o... | sdk/servicefabric/azure-mgmt-servicefabric/azure/mgmt/servicefabric/service_fabric_management_client.py |
from msrest.service_client import SDKClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .version import VERSION
from .operations.clusters_operations import ClustersOperations
from .operations.cluster_versions_operations import ClusterVersionsOperations
from .operations.o... | 0.873066 | 0.07373 |
import collections
import os.path as osp
import time
import warnings
import torch
from torch.nn.parallel import DataParallel, DistributedDataParallel
from ..core.label_generators import LabelGenerator
from ..core.metrics.accuracy import accuracy
from ..data import build_train_dataloader, build_val_dataloader
from ..... | openunreid/apis/runner.py |
import collections
import os.path as osp
import time
import warnings
import torch
from torch.nn.parallel import DataParallel, DistributedDataParallel
from ..core.label_generators import LabelGenerator
from ..core.metrics.accuracy import accuracy
from ..data import build_train_dataloader, build_val_dataloader
from ..... | 0.566139 | 0.169028 |
import sys, os
from datetime import datetime
pasta = 'c:'
#print(os.path.isfile('caixa.txt'))
def main():
dinheiro(preco())
def preco():
while 1:
preco = raw_input('Preço: ')
try:
preco = preco.replace(',','.')
preco = eval(preco)
print(preco)
... | python-examples-master/caixa.py | import sys, os
from datetime import datetime
pasta = 'c:'
#print(os.path.isfile('caixa.txt'))
def main():
dinheiro(preco())
def preco():
while 1:
preco = raw_input('Preço: ')
try:
preco = preco.replace(',','.')
preco = eval(preco)
print(preco)
... | 0.03816 | 0.066782 |
import chk,calc,test,cnst,trig
import sys # Surely I am allowed to get command line options
#NOTE: infix operator control characters must be one character
OPERATORS = [
[
# Infix
[['^'],lambda a,b: a**b],
[['C'],trig.comb],
[['x','*'],lambda a,b: a*b],
[['/'],lambda a,b: a/b]... | main.py | import chk,calc,test,cnst,trig
import sys # Surely I am allowed to get command line options
#NOTE: infix operator control characters must be one character
OPERATORS = [
[
# Infix
[['^'],lambda a,b: a**b],
[['C'],trig.comb],
[['x','*'],lambda a,b: a*b],
[['/'],lambda a,b: a/b]... | 0.271252 | 0.473901 |
l=None
k='group.txt'
j='0'
i=True
h=open
c='art'
b='saveSlot.txt'
a=int
Z=range
I=str
from microbit import pin0 as N,pin1 as O,pin2 as U,button_a as P,button_b as Q,display as R,Image as Y,sleep as V
W=[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
def D(data):R.scroll(data)
def K(file,backup):
A=backup... | MINIFIED.py | l=None
k='group.txt'
j='0'
i=True
h=open
c='art'
b='saveSlot.txt'
a=int
Z=range
I=str
from microbit import pin0 as N,pin1 as O,pin2 as U,button_a as P,button_b as Q,display as R,Image as Y,sleep as V
W=[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
def D(data):R.scroll(data)
def K(file,backup):
A=backup... | 0.056075 | 0.18374 |
from google.appengine.ext.appstats import recording
from third_party.prodeagle import counter_names, config
import datetime
import math
import re
class AppStatsExport():
def append(self, end_time, key, value, result):
if key not in result:
result[key] = {}
slot = counter_names.getEpochRounded(end_tim... | deps/mrtaskman/server/third_party/prodeagle/appstats_export.py |
from google.appengine.ext.appstats import recording
from third_party.prodeagle import counter_names, config
import datetime
import math
import re
class AppStatsExport():
def append(self, end_time, key, value, result):
if key not in result:
result[key] = {}
slot = counter_names.getEpochRounded(end_tim... | 0.271735 | 0.101589 |
def load_use_conditions(use_cond, zone_usage, data_class):
"""Load use conditions from JSON, according to DIN 18599,
SIA2024 in addition some AixLib specific use conditions for central AHU
are defined.
Parameters
----------
use_cond : UseConditions()
Instance of TEASERs
Building... | teaser/data/input/usecond_input.py | def load_use_conditions(use_cond, zone_usage, data_class):
"""Load use conditions from JSON, according to DIN 18599,
SIA2024 in addition some AixLib specific use conditions for central AHU
are defined.
Parameters
----------
use_cond : UseConditions()
Instance of TEASERs
Building... | 0.774455 | 0.243654 |
import boto3
import os
from boto3.dynamodb.conditions import Key, Attr
# event["userId", "rank1", "rank2", "createdAt"]
def lambda_handler(event, context):
print(event)
dynamo = boto3.resource('dynamodb')
picks_table = dynamo.Table(os.environ["picks_table"])
available_players_table = dynamo.Table(os.environ["a... | lambda/freeAgentDraft2019SwitchPicks/lambda_function.py | import boto3
import os
from boto3.dynamodb.conditions import Key, Attr
# event["userId", "rank1", "rank2", "createdAt"]
def lambda_handler(event, context):
print(event)
dynamo = boto3.resource('dynamodb')
picks_table = dynamo.Table(os.environ["picks_table"])
available_players_table = dynamo.Table(os.environ["a... | 0.288068 | 0.161883 |
import numpy as np
import pytest
from scipy.stats import norm as nm
import orbitize.priors as priors
threshold = 1e-1
initialization_inputs = {
priors.GaussianPrior : [1000., 1.],
priors.LogUniformPrior : [1., 2.],
priors.UniformPrior : [0., 1.],
priors.SinPrior : [],
priors.LinearPrior : [-2., 2.]
}
expec... | tests/test_priors.py | import numpy as np
import pytest
from scipy.stats import norm as nm
import orbitize.priors as priors
threshold = 1e-1
initialization_inputs = {
priors.GaussianPrior : [1000., 1.],
priors.LogUniformPrior : [1., 2.],
priors.UniformPrior : [0., 1.],
priors.SinPrior : [],
priors.LinearPrior : [-2., 2.]
}
expec... | 0.676086 | 0.800614 |
from gbdxtools import Interface
from gbdxtools.workflow import Workflow
from auth_mock import get_mock_gbdx_session
import vcr
import unittest
import os
import json
"""
How to use the mock_gbdx_session and vcr to create unit tests:
1. Add a new test that is dependent upon actually hitting GBDX APIs.
2. Decorate the te... | tests/unit/test_workflow.py | from gbdxtools import Interface
from gbdxtools.workflow import Workflow
from auth_mock import get_mock_gbdx_session
import vcr
import unittest
import os
import json
"""
How to use the mock_gbdx_session and vcr to create unit tests:
1. Add a new test that is dependent upon actually hitting GBDX APIs.
2. Decorate the te... | 0.564339 | 0.408749 |
import sys
import json, re
def load(fn, handle_index=True, handle_v=False):
fp=open(fn, 'r')
return handel_value(handle_index_on_key(json.load(fp), handle_index), handle_v)
def loads(s, handle_index=True, handle_v=False):
return handel_value(handle_index_on_key(json.loads(s), handle_index), handle_v)
def... | pyop4/opbase/opjson.py | import sys
import json, re
def load(fn, handle_index=True, handle_v=False):
fp=open(fn, 'r')
return handel_value(handle_index_on_key(json.load(fp), handle_index), handle_v)
def loads(s, handle_index=True, handle_v=False):
return handel_value(handle_index_on_key(json.loads(s), handle_index), handle_v)
def... | 0.053539 | 0.158826 |
import json
import GlobalTools
def getRivalsScores(hash):
with GlobalTools.dbLock:
GlobalTools.cur.execute('''
SELECT rr.name AS name, rr.id AS id, ss.clear AS clear, ss.notes AS notes,
ss.pg*2+ss.gr AS score, ss.minbp AS minbp, rr.active AS active
FROM rivals AS rr INNER JOIN scores AS ss ON rr.id=ss.i... | tools/RankingRequestHandler.py | import json
import GlobalTools
def getRivalsScores(hash):
with GlobalTools.dbLock:
GlobalTools.cur.execute('''
SELECT rr.name AS name, rr.id AS id, ss.clear AS clear, ss.notes AS notes,
ss.pg*2+ss.gr AS score, ss.minbp AS minbp, rr.active AS active
FROM rivals AS rr INNER JOIN scores AS ss ON rr.id=ss.i... | 0.055797 | 0.078678 |
import django.contrib.gis.db.models.fields
import django.db.models.deletion
from django.conf import settings
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("air_quali... | api/woeip/apps/air_quality/migrations/0006_auto_20190726_1709.py | import django.contrib.gis.db.models.fields
import django.db.models.deletion
from django.conf import settings
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("air_quali... | 0.48121 | 0.136752 |
from __future__ import annotations
import pathlib
from typing import Union
def create_parent_symlink(
destination_path: Union[str, pathlib.Path],
symlink_name: str,
*,
levels: int = 2,
overwrite_symlink: bool = False,
) -> bool:
"""Create a symbolic link in a parent directory,
$levels lev... | src/zocalo/util/symlink.py | from __future__ import annotations
import pathlib
from typing import Union
def create_parent_symlink(
destination_path: Union[str, pathlib.Path],
symlink_name: str,
*,
levels: int = 2,
overwrite_symlink: bool = False,
) -> bool:
"""Create a symbolic link in a parent directory,
$levels lev... | 0.9079 | 0.548432 |
import streamlit as st
import os
import requests
from streamlit_folium import folium_static
import folium
def render_streamlit():
url_api = os.getenv('URL_API')
cols = st.columns((1, 3, 1))
cols[1].title("More Antartic penguins...")
st.write(
"*Check out this to know more!* 🐧 [link](https... | src/streamlit_dashboard/src/islands.py | import streamlit as st
import os
import requests
from streamlit_folium import folium_static
import folium
def render_streamlit():
url_api = os.getenv('URL_API')
cols = st.columns((1, 3, 1))
cols[1].title("More Antartic penguins...")
st.write(
"*Check out this to know more!* 🐧 [link](https... | 0.47926 | 0.198258 |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
"""Load the pretrained ResNet152 and replace top fc layer."""
super(EncoderCNN, self).__init__()
resnet = models.resnet152(pretrained=True)
for param in... | model.py | import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
"""Load the pretrained ResNet152 and replace top fc layer."""
super(EncoderCNN, self).__init__()
resnet = models.resnet152(pretrained=True)
for param in... | 0.965601 | 0.591104 |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import fit
from models import calc_cs, calc_ffs, calc_ge_gm, calc_rho, dipole_ffs, get_b2, hbarc
matplotlib.rcParams["text.usetex"] = True
matplotlib.rcParams["font.size"] = 13
matplotlib.rcParams["font.family"] = "lmodern"
matp... | plot.py |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import fit
from models import calc_cs, calc_ffs, calc_ge_gm, calc_rho, dipole_ffs, get_b2, hbarc
matplotlib.rcParams["text.usetex"] = True
matplotlib.rcParams["font.size"] = 13
matplotlib.rcParams["font.family"] = "lmodern"
matp... | 0.73431 | 0.550668 |
import os, sys
from bob.math import pavx, pavxWidth, pavxWidthHeight
import numpy
def pavx_check(y, ghat_ref, w_ref, h_ref):
"""Make a full test for a given sample"""
ghat = pavx(y)
assert numpy.all(numpy.abs(ghat - ghat_ref) < 1e-4)
pavx(y, ghat)
assert numpy.all(numpy.abs(ghat - ghat_ref) < 1e-4)
w=pavx... | bob/math/test_pavx.py | import os, sys
from bob.math import pavx, pavxWidth, pavxWidthHeight
import numpy
def pavx_check(y, ghat_ref, w_ref, h_ref):
"""Make a full test for a given sample"""
ghat = pavx(y)
assert numpy.all(numpy.abs(ghat - ghat_ref) < 1e-4)
pavx(y, ghat)
assert numpy.all(numpy.abs(ghat - ghat_ref) < 1e-4)
w=pavx... | 0.348534 | 0.584805 |
from HDPython.ast.ast_classes.ast_base import v_ast_base, add_class,gIndent
import HDPython.hdl_converter as hdl
from HDPython.base import HDPython_base
from HDPython.v_enum import v_enum
from HDPython.v_symbol import v_symbol
class v_compare(v_ast_base):
def __init__(self,lhs,ops,rhs,astParser):
self.... | HDPython/ast/ast_classes/ast_compare.py | from HDPython.ast.ast_classes.ast_base import v_ast_base, add_class,gIndent
import HDPython.hdl_converter as hdl
from HDPython.base import HDPython_base
from HDPython.v_enum import v_enum
from HDPython.v_symbol import v_symbol
class v_compare(v_ast_base):
def __init__(self,lhs,ops,rhs,astParser):
self.... | 0.563378 | 0.200303 |
from math import *
from sympy import symbols,diff
from sympy.abc import x,y
def standardNR():
print("standard nr")
f = input("enter f(x) in pyth n syntax,ie. x^2 as x**2 , write math functions as func() , like exp(), tan().\n")
fx = diff(f, x)
lf = eval("lambda x:"+str(f))
lfx = eval("lambda x:"+... | Newton-Raphson_Method.py | from math import *
from sympy import symbols,diff
from sympy.abc import x,y
def standardNR():
print("standard nr")
f = input("enter f(x) in pyth n syntax,ie. x^2 as x**2 , write math functions as func() , like exp(), tan().\n")
fx = diff(f, x)
lf = eval("lambda x:"+str(f))
lfx = eval("lambda x:"+... | 0.243552 | 0.418756 |
import numpy as np
import scipy
#--------------------------------------------------
def diaganal_average(matrix, reverse = True,
samesize = False, averaging = True):
'''
Hankel averaging
(or diaganale averaging) of the matrix.
Parameters
------------
* matrix: 2d n... | dsatools/operators/_diagnalization.py | import numpy as np
import scipy
#--------------------------------------------------
def diaganal_average(matrix, reverse = True,
samesize = False, averaging = True):
'''
Hankel averaging
(or diaganale averaging) of the matrix.
Parameters
------------
* matrix: 2d n... | 0.704567 | 0.535706 |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from copy import deepcopy
from math import floor
from math import ceil
from compas.datastructures import meshes_join_and_weld
from compas.topology import adjacency_from_edges
from compas.topology import connec... | src/compas_rv2/singular/datastructures/mesh_quad_coarse/mesh_quad_coarse.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from copy import deepcopy
from math import floor
from math import ceil
from compas.datastructures import meshes_join_and_weld
from compas.topology import adjacency_from_edges
from compas.topology import connec... | 0.89903 | 0.395835 |