id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
1830256 | <gh_stars>1-10
#matrix_builder.py
#builds ecludian distance matrixes
from __future__ import division
from custom import build_distance_matrix
import numpy
import pickle
import time
import sys
if __name__ == "__main__":
try:
size = int(sys.argv[1])
except IndexError:
print("no size given, defau... | StarcoderdataPython |
11346957 | <reponame>swkim01/gps
#!/usr/bin/python3
from flask import Flask, render_template
import json
app = Flask(__name__, template_folder=".", static_url_path='')
try:
import gps
except ImportError:
has_gps_module = False
if has_gps_module:
import gpsreceiver
gpsr = gpsreceiver.GpsReceiver()
gpsr.daem... | StarcoderdataPython |
12837809 | import urllib, json
import urllib.request,os
import socket
import random
import re
socket.setdefaulttimeout(50)
#https://www.hide-my-ip.com/fr/proxylist.shtml
# .*(\[\{.*\]).*
KEY="A00239D3-45F6-4A0A-810C-54A347F144C2"
KEY="<KEY>"
KEY="35d28185-0ca1-47f0-8caf-edc457802c9d"
KEY="B36714DE794D0080A183B5A12BEA... | StarcoderdataPython |
9766899 | <filename>pmapper/pmap.py
"""Several specialized implementations of the PMAP super-resolution algorithm."""
from .backend import np, ft_fwd, ft_rev, ndimage
from .bayer import decomposite_bayer, demosaic_malvar
# If you wish to understand how PMAP works from this code, it is recommended
# that you read :class:PMAP fi... | StarcoderdataPython |
1667943 | import lxml.etree
def parse_xml(xml):
if not len(xml):
return {xml.tag: xml.text}
result = {}
for child in xml:
child_result = parse_xml(child)
if child.tag != 'object':
result[child.tag] = child_result[child.tag]
else:
if child.tag not in result:
... | StarcoderdataPython |
283374 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def binarySearch (arr, l, r, x):
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
... | StarcoderdataPython |
1903615 | # coding=utf-8
"""
The Fax API endpoint send
Documentation: https://voip.ms/m/apidocs.php
"""
from voipms.baseapi import BaseApi
from voipms.helpers import validate_email, convert_bool
class FaxSend(BaseApi):
"""
Send for the Fax endpoint.
"""
def __init__(self, *args, **kwargs):
"""
... | StarcoderdataPython |
193772 | #!/usr/bin/python3
# Additionally format C++ code for further entropy reduction
# Assumes clang-format already run
# Does not work for all possible C++ programs
# Test carefully before reusing in other projects!
import argparse
import os
import re
parser = argparse.ArgumentParser(description="Additionally format C++ ... | StarcoderdataPython |
133619 | """This file contains code used in "Think Bayes",
by <NAME>, available from greenteapress.com
Copyright 2012 <NAME>
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function
import matplotlib.pyplot as pyplot
import thinkplot
import numpy
import csv
import random
import shelv... | StarcoderdataPython |
6586687 | from re import M
from kivymd.uix.button import MDRectangleFlatIconButton
from kivymd.uix.boxlayout import MDBoxLayout
class ButtonGeneric(MDBoxLayout):
def __init__(self, widget, *args, **kwargs):
super(ButtonGeneric, self).__init__(*args, **kwargs)
self.md_bg_color = widget['cores']['background'... | StarcoderdataPython |
6659631 | #!/usr/bin/python3
import os
import time
import pickle
import configparser
import shutil
from time import localtime, strftime
from subprocess import call
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--config_file", dest="config_file")
(options, args) = parser.parse_args()
config_file =... | StarcoderdataPython |
6583059 | <filename>tools/nrtest-swmm/nrtest_swmm/output_reader.py
# -*- coding: utf-8 -*-
#
# output_reader.py
#
# Date Created: 11/14/2017
#
# Author: <NAME>
# US EPA - ORD/NRMRL
#
'''
The module output_reader provides the class used to implement the output
generator.
'''
import sys
# project import
... | StarcoderdataPython |
5009437 | <reponame>contradict/Stomp
import serial
import sys
from binascii import hexlify
import threading
def monitor(portname, outfile=sys.stdout, stop_evt=None):
data = b""
extra = b""
with serial.Serial(portname, 115200, timeout=0.01) as sp:
while True if stop_evt is None else not stop_evt.wait(0):
... | StarcoderdataPython |
12830824 |
import datetime as _dt
from lib2to3.pgen2.token import OP
import pydantic as pydantic
from pydantic import Field
from uuid import UUID
from typing import List, Optional
from validators import email
from bigfastapi.schemas.organisation_schemas import _OrganizationBase
import bigfastapi.schemas.users_schemas as User... | StarcoderdataPython |
5016318 | <filename>Python/PythonExercicios/ex082.py
# Exercício Python 082:
# Crie um programa que vai ler vários números e colocar em uma lista.
# Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente.
# Ao final, mostre o conteúdo das três listas geradas.
... | StarcoderdataPython |
1888774 | # stdlib
import ast
from collections import OrderedDict
import copy
import inspect
from itertools import islice
import os
from pathlib import Path
import sys
from typing import Any
from typing import Callable
from typing import Dict
from typing import Iterator
from typing import List
from typing import Optional
from ty... | StarcoderdataPython |
6606472 | class Entries(object):
def __init__(self, http_client):
self.http_client = http_client
def list(self, **kwargs):
return self.http_client.get('v1/entries/', params=kwargs)
def delete(self, id):
return self.http_client.delete('v1/entries/{}/'.format(id))
def stats_idxid(self, i... | StarcoderdataPython |
11310894 | <filename>src/pi/lib/state.py<gh_stars>1-10
from lib.position import RobotPosition
from math import pi
class RobotState:
def __init__(self, position, facing):
self.position = position
self.facing = facing.normalise()
self.forward_distance = 0
def forward(self, distance):
self.forward_distance = distance
... | StarcoderdataPython |
1719799 | from collections import namedtuple
def get_row_col(text):
text = list(text)
convert = []
row = text[1]
column = text[0]
if row == "1":
convert.append(0)
elif row == "2":
convert.append(1)
elif row == "3":
convert.append(2)
if column == "A":
convert.... | StarcoderdataPython |
3200775 | #!/usr/bin/python3
"""Quantum Computer Module.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from abc import ABC, abstractmethod
import math
import psi4
import numpy
from .ciwavefunction import HF_CIWavefunction, CIS_CIWavefunction
from ..project_2.cis import CIS
from ..psithon.util import rearrange_eigenpairs, check_sim
_... | StarcoderdataPython |
1613506 | #!/usr/bin/env python3
"""
Este é um bot renovador de livros para o sistema Pergamum da UFBA.
Para usar basta executar o script (de preferencia todos os dias)
com as variáveis de ambiente PERGAMUM_LOGIN e PERGAMUM_PASS setadas
com seu RM e senha da biblioteca.
Além disso, você pode receber um emai... | StarcoderdataPython |
5034166 | <reponame>harvard-nrg/mrverify<filename>mrverify/scanner/siemens/prisma.py
import logging
from mrverify.scanner.siemens import Siemens
logger = logging.getLogger(__name__)
class Prisma(Siemens):
def __init__(self, config):
super().__init__(config['Siemens']['Prisma'])
@classmethod
def... | StarcoderdataPython |
1979881 | from selenium.webdriver import Chrome
from bs4 import BeautifulSoup
import csv
from time import sleep
import json
driver = Chrome("chromedriver")
allcatlist = ["https://www.noon.com/uae-en/electronics",
"https://www.noon.com/uae-en/beauty", "https://www.noon.com/uae-en/fashion", "https://www.noon.c... | StarcoderdataPython |
8115670 | #
# @lc app=leetcode id=169 lang=python3
#
# [169] Majority Element
#
# https://leetcode.com/problems/majority-element/description/
#
# algorithms
# Easy (55.16%)
# Likes: 2284
# Dislikes: 192
# Total Accepted: 481.8K
# Total Submissions: 871.2K
# Testcase Example: '[3,2,3]'
#
# Given an array of size n, find th... | StarcoderdataPython |
11268298 |
import json
import re
import subprocess
import os
from urllib.request import Request
from urllib.request import urlopen
from itertools import repeat
def mock_log_handler(line):
print(line)
class DockerHelper:
@staticmethod
def pushed_tags(registry, repo):
response = urlopen(f"https://{registry}/... | StarcoderdataPython |
81379 | <filename>scripts/convertDiagnoseTargets2Table.py
__author__ = 'dan'
import sys
import argparse
import csv
import vcf
import pybedtools
import tabix
from collections import defaultdict
#Arguments and commenad line parsing
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help="Input vcf file")
p... | StarcoderdataPython |
6555148 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# DATE: 2021/8/17
# Author: <EMAIL>
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Optional, Type, NoReturn, Union, Callable
Number: Type = Union[str, int]
class Validator(ABC):
def __set_name__(self, owner: object, name: str) -> N... | StarcoderdataPython |
38548 | # -*- coding: utf-8 -*-
import sys
import time
import json
import pickle
import hashlib
import requests
from urlparse import urljoin
from config import *
from spiders.common import *
from spiders.html_parser import *
from logs.log import logger
reload(sys)
sys.setdefaultencoding('utf8')
class Spider(object):
d... | StarcoderdataPython |
3257412 | #!/usr/bin/python3
# SPDX-License-Identifier: Unlicense
import os.path
import sys
import inspect
import datetime
template_cfg=None
replacements={}
filters={}
shortline=0
shortname='<file>'
fullname='<file>'
activeoutname='<Out>'
activeoutline=0
activedatetime=str(datetime.datetime.now().timestamp())
iserr=False
def g... | StarcoderdataPython |
3221798 | #
# Author: <NAME> (<EMAIL>) 2017
#
#__author__ = "<NAME>"
#__copyright__ = "Copyright 2017, <NAME>"
#__credits__ = ["<NAME>"]
#__license__ = "Apache"
#__version__ = "1.0.0"
#__maintainer__ = "<NAME>"
#__email__ = "<EMAIL>"
#__status__ = "Production"
from __future__ import division
#import direct.directbase.DirectStar... | StarcoderdataPython |
11287699 | <gh_stars>0
from django.forms import ModelForm
from .models import Attachment
class AttachmentForm(ModelForm):
class Meta:
model = Attachment
fields = ('name', 'file')
| StarcoderdataPython |
9730415 | <reponame>MaximDecherf/F1-21_udp_data<filename>src/F121UdpData/F1Data.py
import socket
from .packets.packet import Packet
class F1Data:
PACKET_SIZE_MAPPER = {'MOTION': 1464, 'SESSION': 625, 'LAP_DATA': 970, 'EVENT': 36, 'PARTICIPANTS': 1257, 'CAR_SETUPS': 1102,
'CAR_TELEMETRY': 1347, 'C... | StarcoderdataPython |
1710956 | import tensorflow as tf
tf.InteractiveSession()
a = tf.zeros((2,2))
b = tf.ones((2,2))
print(a.eval())
print(b .eval())
print(tf.reduce_sum(b, reduction_indices=1).eval())
print(a.get_shape())
print(tf.reshape(a, (1, 4)).eval())
| StarcoderdataPython |
95955 | import unittest
from msdm.domains import GridWorld
class GridWorldTestCase(unittest.TestCase):
def test_feature_locations(self):
gw = GridWorld([
"cacg",
"sabb"])
fl = gw.feature_locations
lf = gw.location_features
fl2 = {}
for l, f in lf.items():
... | StarcoderdataPython |
14753 | <gh_stars>1-10
"""
Query construction tests.
"""
from hamcrest import assert_that, is_, equal_to
from influxdbnagiosplugin.query import ExplicitQueryBuilder, SingleMeasurementQueryBuilder
def test_explicit_query():
query = ExplicitQueryBuilder("SHOW MEASUREMENTS")
assert_that(query().query, is_(equal_to(
... | StarcoderdataPython |
12820821 | <filename>yatai/yatai/configuration/__init__.py
import os
def get_local_config_file():
if "YATAI_CONFIG" in os.environ:
# User local config file for customizing Yatai
return expand_env_var(os.environ.get("YATAI_CONFIG"))
return None
def inject_dependencies():
"""Inject dependencis and c... | StarcoderdataPython |
300562 | from .tsl2561 import *
| StarcoderdataPython |
12861986 | #!/usr/bin/env python3
import yoda, sys
import h5py
import numpy as np
def chunkIt(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
# Fix size, sometimes there is spillover
# TODO: replac... | StarcoderdataPython |
6596401 | <gh_stars>1-10
import globalvars
from gamestate import *
from random import randint
def play():
setElevatorDestination(7)
#------------ bitte hier stehen lassen
execfile ("functions.py")
| StarcoderdataPython |
264292 | <filename>benchmark_client.py<gh_stars>1-10
#!/usr/bin/env python
# encoding: utf-8
"""
Created by <NAME> on 2013-03-12
Published under the MIT license.
"""
import os, sys, logging
from miniredis.client import RedisClient
from multiprocessing import Pool
import time
import random
log = logging.getLogger()
if __name_... | StarcoderdataPython |
9716548 | #!/usr/bin/env python3
from ast import literal_eval
import time
import serial as pyserial
import struct
from HeimdallMultiwii.constants import CTYPE_PATTERNS
from HeimdallMultiwii.exeptions import MissingCodeError, ResponseParserNotImpl, MWCMessageNotSupported
from HeimdallMultiwii.mspcommands import MSPMessagesEnum
... | StarcoderdataPython |
1974217 | <gh_stars>1-10
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import pytest
from wa_kat.analyzers.creation_date_detector import TimeResource
from wa_kat.analyzers.creation_date_detector import mementow... | StarcoderdataPython |
3499502 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 expandtab number
"""
Authors: qianweishuo<<EMAIL>>
Date: 2019/9/29 下午6:17
"""
import os
import re
import sys
import six
from kinoko.misc.log_writer import init_log
def test_writing_files(mocker):
mocker.spy(os.path, 'dirname')
mo... | StarcoderdataPython |
3400923 | <gh_stars>0
"""
Module for doing the training
"""
from __future__ import division
import numpy as np
import plot as plot
from numpy import matrix
from numpy import linalg
def train (train_X, train_Y, learning_rate=1, delay=0.2, type="curve"):
"""
Trains the linear regression model on training data
Sets t... | StarcoderdataPython |
383075 | <reponame>picsldev/pyerp
# Librerias Django
from django.db import models
# Librerias de terceros
from apps.base.models import PyPartner
# Librerias en carpetas locales
from .campaign import PyCampaign
from .channel import PyChannel
class MarketingPartner(PyPartner):
class Meta:
app_label = 'base'
c... | StarcoderdataPython |
1779898 | ##########################
# Test script to check for the presence of brackets in scripted loc
# By Pelmen, https://github.com/Pelmen323
##########################
import glob
import os
import re
from ..test_classes.generic_test_class import FileOpener, ResultsReporter
from ..data.scripted_localisation_functions import... | StarcoderdataPython |
3531024 | <reponame>demusis/risco_fuzzy_mc<filename>Modelo 01.py<gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import sys
import pandas as pd
import numpy as np
import arisco
import seaborn as sns
sns.set_style('darkgrid')
# Teste
# In[2]:
print(sys.version)
# In[3]:
print(np.version.version) # É necessári... | StarcoderdataPython |
8117402 | <gh_stars>0
# https://open.kattis.com/problems/sevenwonders
import collections
print((lambda c: min(c['T'], c['G'], c['C']) * 7 + sum([c[k] ** 2 for k in c]))(collections.Counter({'T': 0, 'C': 0, 'G': 0}) + collections.Counter(input())))
| StarcoderdataPython |
12839194 | import os, sys, copy
import pickle
import math
import time
import numpy as np
from typing import Dict, Any, List, Set, Tuple
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.utils.rnn import pad_sequence
import torch.nn.utils.rnn as rnn_utils
from agent.environment.position import Pos... | StarcoderdataPython |
9657343 | from dagster.tutorials.intro_tutorial.unittesting import (
execute_test_only_final,
execute_test_a_plus_b_final_subdag,
)
def test_only_final():
execute_test_only_final()
def test_a_plus_b_final_subdag():
execute_test_a_plus_b_final_subdag()
| StarcoderdataPython |
3510325 | """
Osd backfill test
"""
import logging
import time
from tasks import ceph_manager
from teuthology import misc as teuthology
log = logging.getLogger(__name__)
def rados_start(ctx, remote, cmd):
"""
Run a remote rados command (currently used to only write data)
"""
log.info("rados %s" % ' '.join(cmd... | StarcoderdataPython |
258566 | import numpy as np
def sigmoidDerivada(sig):
return sig * (1 - sig)
def sigmoid(soma):
return 1 / (1 + np.exp(-soma)) #fórmula da função Sigmoidal
'''
a = sigmoid = (-1.5) # exemplo
b = np.exp(0) # exemplo
c = sigmoid(0.5) # exemplo
d = sigmoidDerivada(c) # exemplo
'''
# Cada registro possue duas entradas
ent... | StarcoderdataPython |
4915360 | '''
This module contains a tool kit for loading data in the app_model_validation.py file
'''
import os
import pandas as pd
training_data_path = 'data/training/220128.csv'
def load_train_and_validation_data(frac_ = 0.8):
'''
This method loads training and testing data as pandas data frames.
'''
# ... | StarcoderdataPython |
262711 | <reponame>xiaoxiaofenyge/-<filename>wechatsogou/structuring.py<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import re
import json
from lxml import etree
from lxml.etree import XML
import requests
from wechatsogou.tools import get_elem_text, list_or_e... | StarcoderdataPython |
3271037 | <gh_stars>0
# -*- coding: utf-8 -*-
from scrapy.spiders import Spider
from uuid import uuid4
from ..items import ComponentItem
class GarrysmodSpider(Spider):
name = 'garrysmod'
allowed_domains = ['wiki.garrysmod.com']
start_urls = ['https://wiki.garrysmod.com/navbar/']
state = {}
def parse_nav(... | StarcoderdataPython |
9705266 | import os
from os import path
import math
os.environ['OPENBLAS_NUM_THREADS'] = '1'
import numpy as np
import sys, json, time
import pandas as pd
import multiprocessing as mp # TODO remove from final version
from datetime import datetime, timedelta
from ortools.constraint_solver import routing_enums_pb2
from ortools.c... | StarcoderdataPython |
6635807 | <filename>pivoteer/collectors/api.py
import logging
import requests
import json
class PassiveTotal(object):
base_url = "https://api.passivetotal.org"
headers = { 'Content-Type': 'application/json' }
api_versions = {"v2": "/v2",
"current": "/current"}
GET_resources = {"metadata"... | StarcoderdataPython |
4834333 | <gh_stars>0
# Write a Python program to find files and skip directories of a given directory.
import os
print([f for f in os.listdir('/home/oem/adi_workspace') if os.path.isfile(os.path.join('/home/oem/adi_workspace', f))])
| StarcoderdataPython |
3587316 | __author__ = 'moshebasanchig'
from hydro.topology_base import Topology
class GeoWidgetTopology(Topology):
def _submit(self, params):
"""
topology consists of several steps, defining one source stream or more, combining and transformations
"""
main_stream = self.query_engine.get('g... | StarcoderdataPython |
1795174 | <reponame>AmeetR/Monocular-Depth-Estimation-DAV<filename>src/data/DIODE_pointcloud.py
import open3d
import pandas as pd
import cv2
import numpy as np
import matplotlib.pyplot as plt
def plot_depth_map(dm, validity_mask):
validity_mask = validity_mask > 0
MIN_DEPTH = 0.
MAX_DEPTH = min(300, np.percentile(dm... | StarcoderdataPython |
12816332 | from abc import abstractmethod
from typing import Dict, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from transformers import AutoModel, AutoConfig
from .layers import WordSequence
class BackBone(nn.Module):
def __init__(self, n_class, binary_mode=F... | StarcoderdataPython |
3532382 | from collections import defaultdict
# 入力
N = int(input())
A = list(map(int, input().split()))
# dp[s]: A_1 + ... + A_i = s となるような i の個数
dp = defaultdict(int, {0: 1})
# 和
s = 0
# 解
ans = 0
# 各iについて、 A_1 + ... + A_i = A_1 + ... + A_j となるような 0 <= j < N の個数を求める
for a in A:
s += a
ans += dp[s]
dp[s] += 1
# 出力... | StarcoderdataPython |
8015810 | from keras.layers import Dense, Input
from keras.models import Model
from keras.utils import np_utils
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
iris = datasets.load_iris()
X, y = iris.data, iris.target
# print(y_one_hot)
def creat... | StarcoderdataPython |
5183882 | """
MIT License
Copyright (c) 2021 AkshuAgarwal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... | StarcoderdataPython |
3218871 | # Generated by Django 3.0.6 on 2020-07-30 20:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0008_auto_20200730_1452'),
]
operations = [
migrations.AlterField(
model_name='fish',
name='description',
... | StarcoderdataPython |
186812 | <reponame>BananaLoaf/restpass<gh_stars>1-10
from restpass.generator import Generator
CHECK = ["y", "eL", "7w1", "uwYO", "1HcR8", "jbGAV4", "KrOoKrg", "gBzUnbWk", "xkFn85JHz", "Sj4WS93zPX"]
if __name__ == "__main__":
phrase = "Hello, World!"
generator = Generator(phrase)
generator.set_rules(digits=True, ... | StarcoderdataPython |
11224668 | """A large crowd-sourced dataset for developing natural language interfaces for relational databases"""
from __future__ import absolute_import, division, print_function
import json
import os
import nlp
_CITATION = """\
@article{zhongSeq2SQL2017,
author = {<NAME> and
<NAME> and
<N... | StarcoderdataPython |
6622892 | <reponame>adborden/WeVoteBase
# import_export_open_civic_data/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.db import models
# https://github.com/opencivicdata/python-opencivicdata-django
# There are models for the ocd data types
# Other Open Civic Data identifiers that refer t... | StarcoderdataPython |
8126920 | <filename>trees-and-graphs/reconstruct-a-binary-tree-from-a-preorder-traversal-with-markers.py
# 9.13 in Elements of Programming Interviews in Python (Sep 15, 2016)
# Design an algorithm for reconstructing a binary tree from a preorder traversal
# visit sequence that uses null to mark empty children.
import unittest
... | StarcoderdataPython |
6703808 | import datetime as dt
import pytest
from note_clerk import planning
@pytest.mark.parametrize(
"date, quarter",
[
(dt.datetime(2020, 1, 1), dt.datetime(2020, 1, 1)),
(dt.datetime(2020, 1, 2), dt.datetime(2020, 1, 1)),
(dt.datetime(2020, 4, 1), dt.datetime(2020, 4, 1)),
(dt.dat... | StarcoderdataPython |
8121914 | <reponame>vepakom/SplitLearning_Inference
from algos.simba_algo import SimbaDefence
class SplitInference(SimbaDefence):
def __init__(self, config, utils) -> None:
super(SplitInference, self).__init__(utils)
self.initialize(config)
def initialize(self, config):
self.client_model = self... | StarcoderdataPython |
8094550 | <gh_stars>10-100
# from . import core # DONT import core. this project module should be relatively independent
from buildercore import utils, config
from kids.cache import cache
from . import files
import copy
import logging
from functools import reduce
LOG = logging.getLogger(__name__)
#
# project data utilities
#
d... | StarcoderdataPython |
4851098 | #python
import pyodbc #for mssql connection with python
#connect db
conn = pyodbc.connect('Driver={SQL Server};'
'Server=USBLRVDEEPAK1;'
'Database=dbTemp;'
'Trusted_Connection=yes;')
#get table names
def list_of_tables(conn,dbName):
cursor =... | StarcoderdataPython |
9605441 | <reponame>LIIR-KULeuven/CLDR_CLNER_models<filename>CLDR/final_run/main.py<gh_stars>10-100
import json
import sys
import random
import os
import shutil
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.modules.module import Module
from torch.n... | StarcoderdataPython |
9782142 | <reponame>forsvarir/python-refactoring-exercises
from enum import Enum
import random
import time
PAUSE_PERIOD = 0
EVEN_BONUS = 10
ODD_PENALTY = 5
MINIMUM_SCORE = 0
class Player:
def __init__(self, name, score = 0):
self.name = name
self.score = score
def add_dice(score1, score2):
return score1 +... | StarcoderdataPython |
12843633 | import ipaddress
# =============================================== DEFAULT CONFIGURATION ================================================
# Default port to bind the translator's unicast server socket to.
DEFAULT_UNICAST_SRV_PORT = 9001
# Default address space to pick multicast destination addresses (groups) from for t... | StarcoderdataPython |
6470148 | <reponame>m2u/m2u
"""Commands for scene events tracking in maya.
Scene tracking observes if files are opened, closed or Maya exits.
That may be important for deleting and recreating callbacks automatically.
When Maya exits, we will try to disconnect from the Editor and save
settings.
"""
import logging
import pyme... | StarcoderdataPython |
3427992 | <filename>muninn/muninn/settings/prod.py
from .base import *
DEBUG=False
| StarcoderdataPython |
1745685 | #
# Copyright (C) 2007 <NAME>
# All rights reserved.
# For license terms see the file COPYING.txt.
#
from __future__ import print_function
import unittest, os, shutil, errno, sys, difflib, cgi, re
from roundup.admin import AdminTool
from . import db_test_base
from .test_mysql import skip_mysql
from .test_postgresql ... | StarcoderdataPython |
6557172 | # Suppose you have a bunch of markdown files in a root directory called RD1,
# and you list all these file links in another file called F2, now
# you want to check whether all the files in RD1 are listed in F2.
import os
# Use this filter_list when you want to skip checking some files
# filter_list = ['<file-name1.x... | StarcoderdataPython |
3563457 | import networkx as nx
from covariant_compositional_networks_tf2.CCN_Model import CCN_Model
import numpy as np
import tensorflow as tf
from ordered_set import OrderedSet
from covariant_compositional_networks_tf2.CCN_Model import CCN_Model
channels_in = 5
feature_vector_shape = [1]
k = 2
model = CCN_Model(optimizer= tf.... | StarcoderdataPython |
3309557 | <gh_stars>1-10
# Author:柠檬班-木森
# E-mail:<EMAIL>
import json
import os
import unittest
import time
import copy
from jinja2 import Environment, FileSystemLoader
from concurrent.futures.thread import ThreadPoolExecutor
from apin.core.initEvn import log
from apin.core.testResult import ReRunResult
from apin.core.resultPush... | StarcoderdataPython |
5190607 | <reponame>DryptoBZX/contractsV2
#!/usr/bin/python3
import pytest
from brownie import Contract, network
from helpers import setupLoanPool
def test_getTokens(Constants, bzx, accounts, TokenRegistry):
setupLoanPool(Constants, bzx, accounts[1], accounts[2])
setupLoanPool(Constants, bzx, accounts[3], accounts[4])
... | StarcoderdataPython |
5049209 | from asg.intermediate_lang import *
from asg.entities import *
from lark import Lark, Transformer
import os
from asg.grammar import *
class SExpressionTransformer(Transformer):
"""
Transform the parsed tree to an SExpressionList object. Also handles strings and literals.
"""
def string(self, string):... | StarcoderdataPython |
368972 | <filename>Dragon/python/dragon/vm/onnx/frontend.py
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# ... | StarcoderdataPython |
8149229 | import unittest
from mock import patch
class _Success(str):
@property
def failed(self):
return False
class TestVagrantVersion(unittest.TestCase):
def test_vagrant_version_1_3_0(self):
with patch('fabtools.vagrant.local') as mock_local:
mock_local.return_value = _Success("V... | StarcoderdataPython |
6554665 | <gh_stars>1-10
from pyopenproject.api_connection.exceptions.request_exception import RequestError
from pyopenproject.api_connection.requests.post_request import PostRequest
from pyopenproject.business.exception.business_error import BusinessError
from pyopenproject.business.services.command.user.user_command import Use... | StarcoderdataPython |
11251249 | import math, random, sys, numpy
import pygame
from pygame.locals import *
pygame.init()
# define display surface
ScrW = 1000
ScrH = 700
HW, HH = ScrW / 2, ScrH / 2
win = pygame.display.set_mode((ScrW, ScrH))
pygame.display.set_caption("BommerMan")
vol = 5
FPS = 10
clock = pygame.time.Clock()
# define some col... | StarcoderdataPython |
4980134 | <filename>dbmanage/bkrs/script/backupscripts/mysqlbackup.py<gh_stars>1-10
#!/usr/bin/python
import sys
import string
import shutil
import getopt
import os
import os.path
import syslog
import errno
import logging
import tempfile
import datetime
import subprocess
import readline
import json
from operator import itemget... | StarcoderdataPython |
8055810 | from scipy import optimize
import numpy as np
from matplotlib import pyplot as plt
import scipy.integrate as integrate
def curve(x, t):
period = 2 * np.pi / x[1]
if isinstance(t, float):
t = np.array((t,))
y = np.ndarray((t.shape[0],))
for i in range(t.shape[0]):
if t[i] < (period / 4... | StarcoderdataPython |
1978002 | <reponame>OneGneissGuy/detrend-ec
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 12:38:52 2018
script to read in conductivity data and correct for drift due to evaporation
@author: jsaracen
"""
import numpy as np
import pandas as pd
from scipy.signal import detrend
input_data_file = 'sc1000_data.csv'
#read... | StarcoderdataPython |
11143 |
""" shell sort tests module """
import unittest
import random
from sort import shell
from tests import helper
class ShellSortTests(unittest.TestCase):
""" shell sort unit tests class """
max = 100
arr = []
def setUp(self):
""" setting up for the test """
self.arr = random.sample(ran... | StarcoderdataPython |
1811223 | import json
from policy_storage import Policy_Storage
def validate_access_policies(resource_id, user_name):
mongo = Policy_Storage('mongodb')
data = mongo.get_policy_from_resource_id(str(resource_id))
operations = ['AND', 'OR']
if isinstance(data, list):
for i in range(0, len(data)):
... | StarcoderdataPython |
3458730 | <gh_stars>100-1000
import torch
import os
from im2mesh.utils.io import save_mesh
import time
from im2mesh.utils.onet_generator import Generator3D as Generator3DONet
class Generator3D(object):
''' Generator class for Occupancy Networks 4D.
It provides functions to generate the final mesh as well refining opt... | StarcoderdataPython |
11221860 | <gh_stars>0
# -*- coding: utf-8 -*-
import re
"""
Created on Tue Jun 2 11:46:18 2020
class format city
@author: Rizilip
"""
## landmarks
# mansion tours
def formatString(f,m):
##
string = f.strip()
name = ""
method = m
match = re.findall("[\w+\s+ ..\w+\s+]+", string)
... | StarcoderdataPython |
3560116 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#读取Excel表格中的信息,并将信息写入json文件中
from collections import OrderedDict
from pyexcel_xls import get_data
from pyexcel_xls import save_data
import json
map_filename='editor\\地图信息.xlsx'
current_sheet=1
while True:
xls_data=get_data(map_filename)
messages=xls... | StarcoderdataPython |
1918427 | import os
import shutil
from cement.utils import fs
from cement.utils.misc import rando as _rando
import pytest
@pytest.fixture(scope="function")
def tmp(request):
t = fs.Tmp()
yield t
# cleanup
if os.path.exists(t.dir) and t.cleanup is True:
shutil.rmtree(t.dir)
@pytest.fixture(scope="fu... | StarcoderdataPython |
5142423 | import pandas as pd
import numpy as np
from rdkit import Chem
from scipy import stats
import pubchempy as pcp
df = pd.read_excel("../2_bbb_all_complete_CID_out_smiles_fixed_updated.xlsx")
df = df[~df["logBB"].isna()]
df["logBB"] = df["logBB"].astype(float)
# remove molecules with logBB <= -9
df = df[df["logBB"] > -9... | StarcoderdataPython |
5042328 | from typing import List
import autofit as af
import autogalaxy as ag
from autogalaxy.aggregator.abstract import AbstractAgg
from autolens.lens.ray_tracing import Tracer
def _tracer_from(fit: af.Fit, galaxies: List[ag.Galaxy]) -> Tracer:
"""
Returns a `Tracer` object from a PyAutoFit database `Fit... | StarcoderdataPython |
3592514 | <reponame>zhouyijiaren/commons<filename>src/python/twitter/common/log/tracer.py
# ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licen... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.