uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
5309ed80b83114b99da0d0ae
train
function
def JPPNet_wrapper(): #resizing image img=Image.open(r'C:\Users\lenovo\Desktop\try_on\custom\test\image/000183_0.jpg') img = img.resize((192,256)) #print(img.size) img.save(r'C:\Users\lenovo\Desktop\try_on\custom\test\image/000183_0.jpg') #file_writing file_w.f_write() #..................
def JPPNet_wrapper(): #resizing image
img=Image.open(r'C:\Users\lenovo\Desktop\try_on\custom\test\image/000183_0.jpg') img = img.resize((192,256)) #print(img.size) img.save(r'C:\Users\lenovo\Desktop\try_on\custom\test\image/000183_0.jpg') #file_writing file_w.f_write() #............................pose_estimation.................
# coding=utf-8 from PIL import Image import cv2 import numpy as np import file_w import evaluate_pose_JPPNet_s2 import evaluate_parsing_JPPNet_s2 from v2 import * import json def JPPNet_wrapper(): #resizing image
63
222
742
12
50
Arpita-25/Invincible-Myntra
WebD_File/try_on/v1.py
Python
JPPNet_wrapper
JPPNet_wrapper
11
52
11
12
8c6f638b59b8877b768f987d93296977bed52978
bigcode/the-stack
train
773cbd421b022a2a31f597f7
train
class
class SubscriberError: NOT_FOUND = 'NOT_FOUND' INVALID_ARGUMENT = 'INVALID_ARGUMENT' INTERNAL = 'INTERNAL' TOO_MANY_TOPICS = 'TOO_MANY_TOPICS' ERRORS_MESSAGE = { NOT_FOUND: 'The registration token has been deleted or the app has been uninstalled.', INVALID_ARGUMENT: 'The registratio...
class SubscriberError:
NOT_FOUND = 'NOT_FOUND' INVALID_ARGUMENT = 'INVALID_ARGUMENT' INTERNAL = 'INTERNAL' TOO_MANY_TOPICS = 'TOO_MANY_TOPICS' ERRORS_MESSAGE = { NOT_FOUND: 'The registration token has been deleted or the app has been uninstalled.', INVALID_ARGUMENT: 'The registration token provided is not...
class SubscriberError:
4
64
120
4
0
BookWorm0103/the-blue-alliance
tbans/consts/subscriber_error.py
Python
SubscriberError
SubscriberError
1
12
1
1
4b2160166574682eeea78cb41e62e3e9df5afa68
bigcode/the-stack
train
e5630f0bf52b494779668bae
train
class
class PSDraw(object): """ Sets up printing to the given file. If **file** is omitted, :py:attr:`sys.stdout` is assumed. """ def __init__(self, fp=None): if not fp: fp = sys.stdout self.fp = fp def _fp_write(self, to_write): if bytes is str or self.fp == sys....
class PSDraw(object):
""" Sets up printing to the given file. If **file** is omitted, :py:attr:`sys.stdout` is assumed. """ def __init__(self, fp=None): if not fp: fp = sys.stdout self.fp = fp def _fp_write(self, to_write): if bytes is str or self.fp == sys.stdout: se...
# # The Python Imaging Library # $Id$ # # simple postscript graphics interface # # History: # 1996-04-20 fl Created # 1999-01-10 fl Added gsave/grestore to image method # 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge) # # Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved. # ...
150
256
1,034
5
145
lucasLB7/Zoomin-Photos-
venv/lib/python3.6/site-packages/PIL/PSDraw.py
Python
PSDraw
PSDraw
25
142
25
25
2bd52401482461a105ae4a3d3c6aa9561ab989b1
bigcode/the-stack
train
a40d95eb5058b3f560725d39
train
class
class ReadabilitySpider(scrapy.Spider): name = "readability" login_url = 'https://www.readability.com/login/' reading_list_url = 'https://www.readability.com/reading-list?page={0}' archive_list_url = ( 'https://www.readability.com/reading-list/archives?page={0}' ) # Utility Functions ...
class ReadabilitySpider(scrapy.Spider):
name = "readability" login_url = 'https://www.readability.com/login/' reading_list_url = 'https://www.readability.com/reading-list?page={0}' archive_list_url = ( 'https://www.readability.com/reading-list/archives?page={0}' ) # Utility Functions def make_readability_list_link(self,...
import scrapy class ReadabilitySpider(scrapy.Spider):
12
152
507
9
2
jambonrose/readability-scraper
readability_scraper/spiders/readability_spider.py
Python
ReadabilitySpider
ReadabilitySpider
4
76
4
4
44baec702b5c268d8409cbaf0d397bf822af5ebc
bigcode/the-stack
train
df301cd0308d667049983039
train
function
def convert_units(props, conversion_dict): """Converts dictionary of properties to the desired units. Args: props (dict): dictionary containing the properties of interest. conversion_dict (dict): constants to convert. Returns: props (dict): dictionary with properties converted. ...
def convert_units(props, conversion_dict):
"""Converts dictionary of properties to the desired units. Args: props (dict): dictionary containing the properties of interest. conversion_dict (dict): constants to convert. Returns: props (dict): dictionary with properties converted. """ props = props.copy() for prop...
(os.path.dirname(os.path.abspath(__file__)), # "elec_config.json"), "r") as f: # ELEC_CONFIG = json.load(f) # ELEC_CONFIG = {int(key): val for key, val in ELEC_CONFIG.items()} def convert_units(props, conversion_dict):
63
64
121
8
55
jkaraguesian/NeuralForceField
nff/utils/constants.py
Python
convert_units
convert_units
156
176
156
156
13b2111e0e5fd33baf3cc646e35cc50abc8debdb
bigcode/the-stack
train
5341dad8ef6a807c0b1d1d81
train
function
def exc_ev_to_hartree(props, add_ground_energy=False): """ Note: only converts excited state energies from ev to hartree, not gradients. """ assert "energy_0" in props.keys() exc_keys = [key for key in props.keys() if key.startswith('energy') and 'grad' not i...
def exc_ev_to_hartree(props, add_ground_energy=False):
""" Note: only converts excited state energies from ev to hartree, not gradients. """ assert "energy_0" in props.keys() exc_keys = [key for key in props.keys() if key.startswith('energy') and 'grad' not in key and key != 'energy_0'] energy_0 = props['energy_0']...
.keys(): for conv_key, conv_const in conversion_dict.items(): if conv_key in prop_key: props[prop_key] = [ x * conv_const for x in props[prop_key] ] return props def exc_ev_to_hartree(props, add_ground...
64
64
143
15
48
jkaraguesian/NeuralForceField
nff/utils/constants.py
Python
exc_ev_to_hartree
exc_ev_to_hartree
179
198
179
180
f372d090774c8905e02b6fe9ec440b585ded540b
bigcode/the-stack
train
205a3ff31ab0b34c8ce71d1b
train
function
def get_c(a, b): c_value = math.sqrt(a ** 2 + b ** 2) return round(c_value, 2)
def get_c(a, b):
c_value = math.sqrt(a ** 2 + b ** 2) return round(c_value, 2)
import math import random RANGE = 50 def get_c(a, b):
19
64
32
7
11
snigdhasjg/Pythagorean-Triplate
TripletHelper/Generate_Triple.py
Python
get_c
get_c
7
9
7
7
a05d661f1ac3349c63c886b1ddb2c408eb430b26
bigcode/the-stack
train
702fa90227697d6bdf03bf51
train
function
def generate_triple(limit): number1 = random.randint(2, limit) + round(random.random(), 2) number2 = random.randint(2, limit) + round(random.random(), 2) number3 = get_c(number1, number2) return [number1, number2, number3]
def generate_triple(limit):
number1 = random.randint(2, limit) + round(random.random(), 2) number2 = random.randint(2, limit) + round(random.random(), 2) number3 = get_c(number1, number2) return [number1, number2, number3]
import math import random RANGE = 50 def get_c(a, b): c_value = math.sqrt(a ** 2 + b ** 2) return round(c_value, 2) def generate_triple(limit):
50
64
68
6
44
snigdhasjg/Pythagorean-Triplate
TripletHelper/Generate_Triple.py
Python
generate_triple
generate_triple
12
17
12
12
e4d24710e8f31063652036b25dadadd164575d1e
bigcode/the-stack
train
8c72e33c7f9585bd786e67a4
train
function
def generate_list(size): triple_list = [] for _ in range(size): triple_list.append(generate_triple(RANGE)) return triple_list
def generate_list(size):
triple_list = [] for _ in range(size): triple_list.append(generate_triple(RANGE)) return triple_list
random.randint(2, limit) + round(random.random(), 2) number2 = random.randint(2, limit) + round(random.random(), 2) number3 = get_c(number1, number2) return [number1, number2, number3] def generate_list(size):
63
64
32
5
58
snigdhasjg/Pythagorean-Triplate
TripletHelper/Generate_Triple.py
Python
generate_list
generate_list
20
25
20
20
ba7d5a3236399ccadbdf036570dd91bb150575f5
bigcode/the-stack
train
6d3d430773ef38ddec9971f5
train
class
class Proceso_deteccion_movimiento: import time tiempo_transcurrido_por_instruccion = time.time() @staticmethod def iniciar_proceso(): print("Proceso iniciado") def primer_movimiento_detectado(self): print("Primer movimiento") self.tiempo_transcurrido_por_instruccion = time...
class Proceso_deteccion_movimiento:
import time tiempo_transcurrido_por_instruccion = time.time() @staticmethod def iniciar_proceso(): print("Proceso iniciado") def primer_movimiento_detectado(self): print("Primer movimiento") self.tiempo_transcurrido_por_instruccion = time.time() @staticmethod def t...
IDEOS) historial_personas = dict() actual_cardholder = str() scan_beacon = Beacon_FCV(0, TIME_SCAN_BEACON) class Orden_mqtt_recibida: @staticmethod def public_ota(): print("Orden publica: OTA") @staticmethod def public_restart(): print("Orden publica: restart") @staticmethod ...
119
119
397
9
110
wisrovi/MANITOR-WISROVI
manitor.py
Python
Proceso_deteccion_movimiento
Proceso_deteccion_movimiento
45
93
45
45
9be83b7a4d53117c6783e21ff661421d10c97886
bigcode/the-stack
train
1f42c4d67fc4b083732ea0ae
train
function
@Sound("sound manitor") @Manitor("Manitor WISROVI") @Cardholder("cardholder manitor") @Mqtt("mqtt manitor") @Avatar("avatar manitor") def main(): global chrono_beacon_scan global PRIMER_CARDHOLDER global actual_cardholder while True: frame = dm.proceso_completo() black_screen, video_ini...
@Sound("sound manitor") @Manitor("Manitor WISROVI") @Cardholder("cardholder manitor") @Mqtt("mqtt manitor") @Avatar("avatar manitor") def main():
global chrono_beacon_scan global PRIMER_CARDHOLDER global actual_cardholder while True: frame = dm.proceso_completo() black_screen, video_inicial_final = avatar_class.proceso() if avatar_class.get_primer_inicio_avatar(): if abs(chrono_beacon_scan - currentTime()) >= ...
) avatar_class.iniciar_avatar() rta = f(*args, **kw_args) avatar_class.cerrar_avatar() return rta return none class Sound(object): def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): ...
159
159
531
45
113
wisrovi/MANITOR-WISROVI
manitor.py
Python
main
main
179
235
179
184
e4b0d57fcdad329f4801cc58d76aec349bf42f21
bigcode/the-stack
train
83d9a69e0d35a6bbc6edb5f9
train
class
class Mqtt(object): def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) MatricularFuncionRecibidoMQTT(Orden_mqtt_recibida()) IniciarEscuchaMQTT() rta = f(*args, **kw_args) Fina...
class Mqtt(object):
def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) MatricularFuncionRecibidoMQTT(Orden_mqtt_recibida()) IniciarEscuchaMQTT() rta = f(*args, **kw_args) FinalizarEscuchaMQTT() ...
def __call__(self, f): def none(*args, **kw_args): print(self.name) rta = f(*args, **kw_args) scan_beacon.terminar_procesos_beacon() return rta return none class Mqtt(object):
64
64
99
5
58
wisrovi/MANITOR-WISROVI
manitor.py
Python
Mqtt
Mqtt
116
129
116
116
ac3f4a89b5de49f42cd2aeec626252c1f9eea596
bigcode/the-stack
train
d6526dd68aac5c729696d17e
train
class
class Manitor(object): def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) rta = f(*args, **kw_args) dm.cerrar_camara() cv2.destroyAllWindows() return rta return none
class Manitor(object):
def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) rta = f(*args, **kw_args) dm.cerrar_camara() cv2.destroyAllWindows() return rta return none
print(self.name) MatricularFuncionRecibidoMQTT(Orden_mqtt_recibida()) IniciarEscuchaMQTT() rta = f(*args, **kw_args) FinalizarEscuchaMQTT() return rta return none class Manitor(object):
64
64
79
5
58
wisrovi/MANITOR-WISROVI
manitor.py
Python
Manitor
Manitor
132
144
132
132
31be470c0dddf3128ea9e0809279a7457de7cddb
bigcode/the-stack
train
79f01e1b00fa77179977f417
train
class
class Sound(object): def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) iniciar_sounds(PATH_VIDEOS) rta = f(*args, **kw_args) return rta return none
class Sound(object):
def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) iniciar_sounds(PATH_VIDEOS) rta = f(*args, **kw_args) return rta return none
def __call__(self, f): def none(*args, **kw_args): print(self.name) avatar_class.iniciar_avatar() rta = f(*args, **kw_args) avatar_class.cerrar_avatar() return rta return none class Sound(object):
64
64
73
4
59
wisrovi/MANITOR-WISROVI
manitor.py
Python
Sound
Sound
162
173
162
162
34480b2f901bb98d3b6314c3c33c3f95a7cbf295
bigcode/the-stack
train
00cb33d67c7ef13f5d1d3fce
train
class
class Avatar(object): def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) avatar_class.iniciar_avatar() rta = f(*args, **kw_args) avatar_class.cerrar_avatar() return rta ...
class Avatar(object):
def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) avatar_class.iniciar_avatar() rta = f(*args, **kw_args) avatar_class.cerrar_avatar() return rta return none
def __call__(self, f): def none(*args, **kw_args): print(self.name) rta = f(*args, **kw_args) dm.cerrar_camara() cv2.destroyAllWindows() return rta return none class Avatar(object):
64
64
78
4
59
wisrovi/MANITOR-WISROVI
manitor.py
Python
Avatar
Avatar
147
159
147
147
8fa4d39f8761557686e4286b73f4c607821dfe97
bigcode/the-stack
train
3e3df5ebf427a2e9c16e7d55
train
class
class Cardholder(object): def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) rta = f(*args, **kw_args) scan_beacon.terminar_procesos_beacon() return rta return none
class Cardholder(object):
def __init__(self, name): self.name = name def __call__(self, f): def none(*args, **kw_args): print(self.name) rta = f(*args, **kw_args) scan_beacon.terminar_procesos_beacon() return rta return none
ccion_actual]['time']) else: dm.set_time(INSTRUCCIONES[0]['time']) self.tiempo_transcurrido_por_instruccion = time.time() dm = Deteccion_movimiento(0, Proceso_deteccion_movimiento) # Decoradores class Cardholder(object):
64
64
78
5
58
wisrovi/MANITOR-WISROVI
manitor.py
Python
Cardholder
Cardholder
102
113
102
102
a880221a50942cfd2a50f4d5cb44107bdc68f4ba
bigcode/the-stack
train
efd3e5db9b83b080a26e7162
train
class
class Orden_mqtt_recibida: @staticmethod def public_ota(): print("Orden publica: OTA") @staticmethod def public_restart(): print("Orden publica: restart") @staticmethod def private_ota(): print("Orden privada: OTA") @staticmethod def private_restart(): ...
class Orden_mqtt_recibida: @staticmethod
def public_ota(): print("Orden publica: OTA") @staticmethod def public_restart(): print("Orden publica: restart") @staticmethod def private_ota(): print("Orden privada: OTA") @staticmethod def private_restart(): print("Orden privada: restart")
_scan = currentTime() PRIMER_CARDHOLDER = False avatar_class = Avatar_video(PATH_VIDEOS) historial_personas = dict() actual_cardholder = str() scan_beacon = Beacon_FCV(0, TIME_SCAN_BEACON) class Orden_mqtt_recibida: @staticmethod
64
64
78
12
52
wisrovi/MANITOR-WISROVI
manitor.py
Python
Orden_mqtt_recibida
Orden_mqtt_recibida
27
42
27
28
5ea9c8e25a68a60b449890f39367686bf31e4987
bigcode/the-stack
train
442701c6397c79c0b55d2e25
train
function
def download_case(case): abs_path = path.dirname(path.abspath(__file__)) output_file = path.join(abs_path, "{}_models.tar.gz".format(case)) url = "http://ecm2.mathcs.emory.edu/aneuriskdata/download/{}/{}_models.tar.gz".format(case, case) try: if platform == "darwin": system("curl {}...
def download_case(case):
abs_path = path.dirname(path.abspath(__file__)) output_file = path.join(abs_path, "{}_models.tar.gz".format(case)) url = "http://ecm2.mathcs.emory.edu/aneuriskdata/download/{}/{}_models.tar.gz".format(case, case) try: if platform == "darwin": system("curl {} --output {}".format(url,...
Kjeldsberg. All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ## PURPOSE. See the above copyright notices for more information. from os import system, path...
74
74
248
5
68
KVSlab/vascularManipulationToolkit
demo/get_test_data.py
Python
download_case
download_case
12
36
12
12
2bf08725372e24cacd486891bee5067f98687ea3
bigcode/the-stack
train
83f4132dcad1de9200642c14
train
class
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog', '0004_follow'), ] operations = [ migrations.AlterField( model_name='follow', name='date', field=models.DateTimeField(auto_...
class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog', '0004_follow'), ] operations = [ migrations.AlterField( model_name='follow', name='date', field=models.DateTimeField(auto_now=True), ), migrations...
# Generated by Django 3.0 on 2019-12-13 11:52 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
49
64
156
7
41
vijay-chauhan07/Xtension
blog/migrations/0005_auto_20191213_1722.py
Python
Migration
Migration
8
31
8
9
7ee922af402ed0435e94361faaa0b12eba662666
bigcode/the-stack
train
9adb580ed94d30706d54a429
train
class
class ManagedADObject: def __init__(self, samaccount_name: str, domain: 'ADDomain', location: str = None, password: str = None): self.samaccount_name = samaccount_name self.domain = domain self.domain_dns_name = self.domain.get_domain_dns_name() self.realm = self.do...
class ManagedADObject:
def __init__(self, samaccount_name: str, domain: 'ADDomain', location: str = None, password: str = None): self.samaccount_name = samaccount_name self.domain = domain self.domain_dns_name = self.domain.get_domain_dns_name() self.realm = self.domain_dns_name.upper() ...
ldap.ldap_format_utils import ( construct_object_distinguished_name ) from ms_active_directory.environment.security.security_config_constants import ( ADEncryptionType, ENCRYPTION_TYPE_STR_TO_ENUM, ) from ms_active_directory.exceptions import InvalidComputerParameterException logger = logging_utils.get_log...
64
64
141
5
59
TrinityDevelopers/ms_active_directory
ms_active_directory/core/managed_ad_objects.py
Python
ManagedADObject
ManagedADObject
60
78
60
61
a20a21e8ea9842bb50703ac1586c9c78dde99760
bigcode/the-stack
train
ee16d86a57abe4c44f778e60
train
class
class ManagedADComputer(ManagedADObject): def __init__(self, samaccount_name: str, domain: 'ADDomain', location: str = None, password: str = None, service_principal_names: List[str] = None, encryption_types: List[ADEncryptionType] = None, kvno: int = None): super().__init_...
class ManagedADComputer(ManagedADObject):
def __init__(self, samaccount_name: str, domain: 'ADDomain', location: str = None, password: str = None, service_principal_names: List[str] = None, encryption_types: List[ADEncryptionType] = None, kvno: int = None): super().__init__(samaccount_name, domain, location, passwo...
beros_keytab_ingester import ( process_keytab_file_to_extract_entries ) from ms_active_directory.environment.kerberos.kerberos_raw_key_generator import ( ad_password_string_to_key ) from ms_active_directory.environment.ldap.ldap_format_utils import ( construct_object_distinguished_name ) from ms_active_dire...
256
256
4,300
9
246
TrinityDevelopers/ms_active_directory
ms_active_directory/core/managed_ad_objects.py
Python
ManagedADComputer
ManagedADComputer
81
413
81
82
a91180aa8f2bb3951958005a053c4e6ca71fa1a0
bigcode/the-stack
train
79b53dafa27ac2f0949bc9a2
train
function
def fix_whitespace(s): return re.sub(r'\s+', ' ', s)
def fix_whitespace(s):
return re.sub(r'\s+', ' ', s)
import re import datetime from billy.scrape import NoDataForPeriod from billy.scrape.committees import Committee, CommitteeScraper import lxml.html def fix_whitespace(s):
42
64
18
6
35
Jgorsick/Advocacy_Angular
openstates/openstates-master/openstates/mn/committees.py
Python
fix_whitespace
fix_whitespace
8
9
8
8
3f05689b1541125da67b61331145e599695d8da0
bigcode/the-stack
train
e46720d20faccac1e0177543
train
class
class MNCommitteeScraper(CommitteeScraper): jurisdiction = 'mn' latest_only = True def scrape(self, term, chambers): if 'upper' in chambers: self.scrape_senate_committees(term) if 'lower' in chambers: self.scrape_house_committees(term) def scrape_senate_committe...
class MNCommitteeScraper(CommitteeScraper):
jurisdiction = 'mn' latest_only = True def scrape(self, term, chambers): if 'upper' in chambers: self.scrape_senate_committees(term) if 'lower' in chambers: self.scrape_house_committees(term) def scrape_senate_committees(self, term): for t in self.metada...
import re import datetime from billy.scrape import NoDataForPeriod from billy.scrape.committees import Committee, CommitteeScraper import lxml.html def fix_whitespace(s): return re.sub(r'\s+', ' ', s) class MNCommitteeScraper(CommitteeScraper):
64
245
817
10
54
Jgorsick/Advocacy_Angular
openstates/openstates-master/openstates/mn/committees.py
Python
MNCommitteeScraper
MNCommitteeScraper
11
105
11
11
f41a65a1cd48ed67eb004618ae09f669fc2957fe
bigcode/the-stack
train
54d137dc0a0c3812b5e4c3b2
train
function
def make_dataset(dir, recursive=False, read_cache=False, write_cache=False): images = [] if read_cache: possible_filelist = os.path.join(dir, "files.list") if os.path.isfile(possible_filelist): with open(possible_filelist, "r") as f: images = f.read().splitlines() ...
def make_dataset(dir, recursive=False, read_cache=False, write_cache=False):
images = [] if read_cache: possible_filelist = os.path.join(dir, "files.list") if os.path.isfile(possible_filelist): with open(possible_filelist, "r") as f: images = f.read().splitlines() return images if recursive: make_dataset_rec(dir, ...
directory" % dir for root, dnames, fnames in sorted(os.walk(dir, followlinks=True)): for fname in fnames: if is_image_file(fname): path = os.path.join(root, fname) images.append(path) def make_dataset(dir, recursive=False, read_cache=False, write_cache=False):
69
69
233
16
53
dukebw/MichiGAN
data/image_folder.py
Python
make_dataset
make_dataset
46
76
46
46
e596f788fe36b3fa10ecaa569a8e773fb08c4efd
bigcode/the-stack
train
d199b104565073f449361969
train
function
def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
IMG_EXTENSIONS = [ ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".ppm", ".PPM", ".bmp", ".BMP", ".tiff", ".webp", ] def is_image_file(filename):
64
64
20
6
58
dukebw/MichiGAN
data/image_folder.py
Python
is_image_file
is_image_file
32
33
32
32
7691dcc1bdb2bad4f3f5f582cf93cc8d75c395a6
bigcode/the-stack
train
439df72b8758a2f01c3b5dfa
train
function
def default_loader(path): return Image.open(path).convert("RGB")
def default_loader(path):
return Image.open(path).convert("RGB")
os.path.join(dir, "files.list") with open(filelist_cache, "w") as f: for path in images: f.write("%s\n" % path) print("wrote filelist cache at %s" % filelist_cache) return images def default_loader(path):
64
64
15
5
58
dukebw/MichiGAN
data/image_folder.py
Python
default_loader
default_loader
79
80
79
79
f07af77878cd864f5e771ec188c018204c775c4f
bigcode/the-stack
train
842fff46b7be1a1cfe05fce4
train
class
class ImageFolder(data.Dataset): def __init__(self, root, transform=None, return_paths=False, loader=default_loader): imgs = make_dataset(root) if len(imgs) == 0: raise ( RuntimeError( "Found 0 images in: " + root + "\n" "Supported ...
class ImageFolder(data.Dataset):
def __init__(self, root, transform=None, return_paths=False, loader=default_loader): imgs = make_dataset(root) if len(imgs) == 0: raise ( RuntimeError( "Found 0 images in: " + root + "\n" "Supported image extensions are: " + ",".joi...
"w") as f: for path in images: f.write("%s\n" % path) print("wrote filelist cache at %s" % filelist_cache) return images def default_loader(path): return Image.open(path).convert("RGB") class ImageFolder(data.Dataset):
64
64
192
6
58
dukebw/MichiGAN
data/image_folder.py
Python
ImageFolder
ImageFolder
83
111
83
83
baed9e181c8188d3382eab6687af09001c4901c4
bigcode/the-stack
train
f6a7b233328f9f21161840e8
train
function
def make_dataset_rec(dir, images): assert os.path.isdir(dir), "%s is not a valid directory" % dir for root, dnames, fnames in sorted(os.walk(dir, followlinks=True)): for fname in fnames: if is_image_file(fname): path = os.path.join(root, fname) images.append(...
def make_dataset_rec(dir, images):
assert os.path.isdir(dir), "%s is not a valid directory" % dir for root, dnames, fnames in sorted(os.walk(dir, followlinks=True)): for fname in fnames: if is_image_file(fname): path = os.path.join(root, fname) images.append(path)
".png", ".PNG", ".ppm", ".PPM", ".bmp", ".BMP", ".tiff", ".webp", ] def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) def make_dataset_rec(dir, images):
64
64
74
8
56
dukebw/MichiGAN
data/image_folder.py
Python
make_dataset_rec
make_dataset_rec
36
43
36
36
27b464938b614b680d03705206d358a985f5b729
bigcode/the-stack
train
08114baa68c3461c72946cf7
train
class
class SyncOnReset(BaseHostTest): """Host side test that handles device reset during case teardown. Given a device that performs a reset during a test case teardown. When the device notifies the host about the reset. Then the host: * keeps track of the test case index of the current test suite, ...
class SyncOnReset(BaseHostTest):
"""Host side test that handles device reset during case teardown. Given a device that performs a reset during a test case teardown. When the device notifies the host about the reset. Then the host: * keeps track of the test case index of the current test suite, * performs a dev-host handshake, ...
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import time from mbed_host_tests import BaseHostTest DEFAULT_SYNC_DELAY = 4....
119
119
398
8
111
spiio/mbed-os
TESTS/host_tests/sync_on_reset.py
Python
SyncOnReset
SyncOnReset
29
73
29
29
7139b7ff3336b4fedde4056941cb679e86b8f1c5
bigcode/the-stack
train
458d8b9a8239262adc71ecb9
train
class
class Reinforce: def __init__(self, env, alpha, gamma, the_d, pi_gen, log_pi, the_0=None): self.env = env self.a = alpha self.g = gamma self.the_d = the_d self.pi_gen = pi_gen self.log_pi = log_pi self.the_0 = the_0 self.reset() def train(self, n_ep): env, alp, the, g = self.env...
class Reinforce:
def __init__(self, env, alpha, gamma, the_d, pi_gen, log_pi, the_0=None): self.env = env self.a = alpha self.g = gamma self.the_d = the_d self.pi_gen = pi_gen self.log_pi = log_pi self.the_0 = the_0 self.reset() def train(self, n_ep): env, alp, the, g = self.env, self.a, self.th...
import numpy as np from utils import gen_traj class Reinforce:
16
91
306
4
11
mtrazzi/understanding-rl
chapter13/reinforce.py
Python
Reinforce
Reinforce
5
37
5
5
b31c1c728a01a6a9de13c194e55737ec7dd5b6ac
bigcode/the-stack
train
d5cc3888b545dac580149ed2
train
class
class AlipayEbppConfigProvinceSearchRequest(object): def __init__(self, biz_model=None): self._biz_model = biz_model self._order_type = None self._sub_order_type = None self._version = "1.0" self._terminal_type = None self._terminal_info = None self._prod_cod...
class AlipayEbppConfigProvinceSearchRequest(object):
def __init__(self, biz_model=None): self._biz_model = biz_model self._order_type = None self._sub_order_type = None self._version = "1.0" self._terminal_type = None self._terminal_info = None self._prod_code = None self._notify_url = None self....
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * class AlipayEbppConfigProvinceSearchRequest(object):
51
256
931
11
40
snowxmas/alipay-sdk-python-all
alipay/aop/api/request/AlipayEbppConfigProvinceSearchRequest.py
Python
AlipayEbppConfigProvinceSearchRequest
AlipayEbppConfigProvinceSearchRequest
11
153
11
12
9f963da23120d28b2ee878e1c3abf4ceb53d9c9a
bigcode/the-stack
train
01d1775cac22e608875debf7
train
class
class ServerTest(TestCase): def _getOne(self, *args, **kwargs): from soloftpd.server import Server return Server(*args, **kwargs) def test_make_authorizer(self): from soloftpd.authorizers import Authorizer server = self._getOne() authorizer = server.make_authorizer(serve...
class ServerTest(TestCase):
def _getOne(self, *args, **kwargs): from soloftpd.server import Server return Server(*args, **kwargs) def test_make_authorizer(self): from soloftpd.authorizers import Authorizer server = self._getOne() authorizer = server.make_authorizer(server.config) self.asser...
from unittest import TestCase from unittest import mock class ServerTest(TestCase):
17
73
246
6
10
tokibito/soloftpd
tests/test_server.py
Python
ServerTest
ServerTest
5
34
5
5
3f0f3c179682172fac55adac1a638b6622e801fe
bigcode/the-stack
train
18b03de28b1715498bbd237f
train
function
def transcribe(dna: str) -> str: """http://rosalind.info/problems/rna/ An RNA is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'. Given a DNA string t corresponding to a coding strand, its transcribed RNA string u is formed by replacing all occurrences of 'T' in t with 'U' in ...
def transcribe(dna: str) -> str:
"""http://rosalind.info/problems/rna/ An RNA is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'. Given a DNA string t corresponding to a coding strand, its transcribed RNA string u is formed by replacing all occurrences of 'T' in t with 'U' in u. Given: A DNA string t hav...
""" Practice for if/else/for/while """ # Problem 1. def transcribe(dna: str) -> str:
28
64
155
11
17
haochunchang/Bioinformatics_Course
basics/python/practice/03_processing.py
Python
transcribe
transcribe
5
22
5
5
86d41bed6e913d0e20d4bd6616796ee9ec638e15
bigcode/the-stack
train
58716eaad186870b29e26ada
train
function
def count_nucleotides(dna: str) -> str: """http://rosalind.info/problems/dna/ Given: A DNA string s of length at most 1000 nt. (whose alphabet only contains the symbols 'A', 'C', 'G', and 'T') Return: 4 integers (separated by spaces) counting the respective number of times that th...
def count_nucleotides(dna: str) -> str:
"""http://rosalind.info/problems/dna/ Given: A DNA string s of length at most 1000 nt. (whose alphabet only contains the symbols 'A', 'C', 'G', and 'T') Return: 4 integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur i...
string of t. Sample Dataset GATGGAACTTGACTACGTAAATT Sample Output GAUGGAACUUGACUACGUAAAUU """ pass # Problem 2. def count_nucleotides(dna: str) -> str:
64
64
164
14
50
haochunchang/Bioinformatics_Course
basics/python/practice/03_processing.py
Python
count_nucleotides
count_nucleotides
26
41
26
26
619be6f5d90580e68946b3cea53dec8475c364d2
bigcode/the-stack
train
70a09ea1ec28bc4385607197
train
function
def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('custom_notifications', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('description', sa.VARCHAR(length=255), nullable=False), sa.Column('type', sa.INTEGER(), nullable=False), sa.Column('user_i...
def downgrade(): ### commands auto generated by Alembic - please adjust! ###
op.create_table('custom_notifications', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('description', sa.VARCHAR(length=255), nullable=False), sa.Column('type', sa.INTEGER(), nullable=False), sa.Column('user_id', sa.INTEGER(), nullable=True), sa.ForeignKeyConstraint(['user_id'], [u'use...
', sa.Column('id', sa.Integer(), nullable=False), sa.Column('text', sa.Text(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.drop_table('custom_notification_settings') op.drop_table('custom_notifications') ### end Alembic commands ### def downgrade(): ### commands auto generated by...
77
78
263
17
60
billfor/alarmdecoder-webapp
alembic/versions/2b1f3d04a8de_.py
Python
downgrade
downgrade
29
51
29
30
805c201c55771bc492d6015f923c72692700663e
bigcode/the-stack
train
7042913d5f14b2271a0c34e8
train
function
def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('notification_messages', sa.Column('id', sa.Integer(), nullable=False), sa.Column('text', sa.Text(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.drop_table('custom_notification_settings') o...
def upgrade(): ### commands auto generated by Alembic - please adjust! ###
op.create_table('notification_messages', sa.Column('id', sa.Integer(), nullable=False), sa.Column('text', sa.Text(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.drop_table('custom_notification_settings') op.drop_table('custom_notifications')
# revision identifiers, used by Alembic. revision = '2b1f3d04a8de' down_revision = '51122360a73c' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ###
64
64
76
17
46
billfor/alarmdecoder-webapp
alembic/versions/2b1f3d04a8de_.py
Python
upgrade
upgrade
17
25
17
18
2520c77802e08456da6aacc49f98e6640a12d8b5
bigcode/the-stack
train
50b2bca977d79dc428764d09
train
function
def visualize_labelmaps(label_maps, N_class, colors=None, background_index=None): """ :param label_maps: :param N_class: :param colors: :param background_index: is none, the last the background index is taken as N_class-1 :return: """ if (background_index is None): background_i...
def visualize_labelmaps(label_maps, N_class, colors=None, background_index=None):
""" :param label_maps: :param N_class: :param colors: :param background_index: is none, the last the background index is taken as N_class-1 :return: """ if (background_index is None): background_index = N_class - 1 if (colors is None): colors = [colorsys.hsv_to_rgb...
_viz = val_imgs * (1 - alphas) + (alphas) * viz if(stack_images): a, b = get_factors(num_images) final_viz = stack_patches(final_viz, a, b) val_imgs = stack_patches(val_imgs, a,b) return final_viz, val_imgs def visualize_labelmaps(label_maps, N_class, colors=None, background_index=None...
91
91
305
17
73
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
visualize_labelmaps
visualize_labelmaps
164
199
164
164
fb90794ed27f9e33bb9bb5a34241f33baf44933a
bigcode/the-stack
train
c2925fdce7910aeb2ed7486e
train
function
def get_factors(x): # This function takes a number x and returns the two numbers a,b both factors of x # such that abs(a-b) is minimum among all factors of x root= int(np.sqrt(x)) if(root*root == int(x)): return root, root z = [] for i in range(1, x + 1): if x % i == 0: ...
def get_factors(x): # This function takes a number x and returns the two numbers a,b both factors of x # such that abs(a-b) is minimum among all factors of x
root= int(np.sqrt(x)) if(root*root == int(x)): return root, root z = [] for i in range(1, x + 1): if x % i == 0: z.append(i) n = int(len(z) / 2) - 1 return z[n], z[n + 1]
rows.append(col) row = np.concatenate(rows, axis=0) return row def get_factors(x): # This function takes a number x and returns the two numbers a,b both factors of x # such that abs(a-b) is minimum among all factors of x
64
64
124
44
19
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
get_factors
get_factors
263
276
263
266
be8d9699de4acc806d7bef1005940e5e5c1c0d55
bigcode/the-stack
train
3a721dbd1a11a11d2ff1fff0
train
function
def visualize_labels_overlay_labelmap(label_maps, val_imgs, n_classes, alpha_label=0.6, BG_INDEX=None, stack_images=True): """ :param label_maps: (n,H,W) where each pixel contain class index :param val_imgs: (n,H,W,C) where C=1 or 3 :n_classes number of classes used in visualization. It should be consi...
def visualize_labels_overlay_labelmap(label_maps, val_imgs, n_classes, alpha_label=0.6, BG_INDEX=None, stack_images=True):
""" :param label_maps: (n,H,W) where each pixel contain class index :param val_imgs: (n,H,W,C) where C=1 or 3 :n_classes number of classes used in visualization. It should be consistent with label_maps :param BG_INDEX: index of background class, if None then n_classes - 1 will be used :return: ...
.5 #alphas = alphas.astype(np.float32) final_viz = val_imgs * (1-alphas) + (alphas) * viz a, b = get_factors(num_images) final_viz = stack_patches(final_viz, a, b) val_imgs = stack_patches(val_imgs, a,b) return final_viz, val_imgs def visualize_labels_overlay_labelmap(label_maps, val_imgs, n_c...
116
116
388
30
85
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
visualize_labels_overlay_labelmap
visualize_labels_overlay_labelmap
125
161
125
125
3fb6318cfeed03a8de386c8adb1c8ac0416a5877
bigcode/the-stack
train
701e02ab5411afecd8ac7b48
train
function
def _visualize_probmaps_oneclass(alabel, class_label, color): alabel_r = np.zeros((alabel.shape[0], alabel.shape[1], 1)) alabel_g = np.zeros((alabel.shape[0], alabel.shape[1], 1)) alabel_b = np.zeros((alabel.shape[0], alabel.shape[1], 1)) mask_class = alabel == class_label np.place(alabel_r, mask_c...
def _visualize_probmaps_oneclass(alabel, class_label, color):
alabel_r = np.zeros((alabel.shape[0], alabel.shape[1], 1)) alabel_g = np.zeros((alabel.shape[0], alabel.shape[1], 1)) alabel_b = np.zeros((alabel.shape[0], alabel.shape[1], 1)) mask_class = alabel == class_label np.place(alabel_r, mask_class, color[0] * 255) np.place(alabel_g, mask_class, color...
.expand_dims(viz, 0)) vizim = np.vstack(labels_viz) return vizim else: alabel = label_maps viz = get_labelmap_viz(alabel) return viz def _visualize_probmaps_oneclass(alabel, class_label, color):
64
64
179
16
47
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
_visualize_probmaps_oneclass
_visualize_probmaps_oneclass
202
213
202
202
7b4e8e5b1777a1039fd953af693537cc7b006afc
bigcode/the-stack
train
7fc014668ad96b4b093c8b0d
train
function
def _pad_patches_stack(patches, N): """ Appends the image stack with the blank images to make total number of images in stack to be N :param patches: :param N: :return: padded patches """ n_blank = N - patches.shape[0] # assert (n_blank <= ngrid_x and n_blank <= ngrid_y), ' too many bl...
def _pad_patches_stack(patches, N):
""" Appends the image stack with the blank images to make total number of images in stack to be N :param patches: :param N: :return: padded patches """ n_blank = N - patches.shape[0] # assert (n_blank <= ngrid_x and n_blank <= ngrid_y), ' too many blank grids, ' + str(n_blank) if ...
] * 255) np.place(alabel_b, mask_class, color[2] * 255) im = np.concatenate([alabel_r, alabel_g, alabel_b], axis=2) return im.astype(np.uint8) def _pad_patches_stack(patches, N):
64
64
143
11
53
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
_pad_patches_stack
_pad_patches_stack
216
233
216
216
459c25c81c4838dbafbad2fa493fa0ab7a322930
bigcode/the-stack
train
8daa6b93bed4098d87156ed6
train
class
class VisualizeOutputCheckpoint(Callback): def __init__(self, datasource, viz_dir, model=None, predict_batch_size=2, num_images=6): """ :param test_datasource: :param viz_dir: :param model: if None, then the training model accessible through super class is used :param predic...
class VisualizeOutputCheckpoint(Callback):
def __init__(self, datasource, viz_dir, model=None, predict_batch_size=2, num_images=6): """ :param test_datasource: :param viz_dir: :param model: if None, then the training model accessible through super class is used :param predict_batch_size: :param num_images: ...
import colorsys import cv2 import numpy as np import os from tensorflow.keras.callbacks import Callback from dataflow import BatchData class VisualizeOutputCheckpoint(Callback):
38
181
604
8
29
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
VisualizeOutputCheckpoint
VisualizeOutputCheckpoint
9
78
9
9
90c809114907c2a5a2ce42954141a6ccce609177
bigcode/the-stack
train
a5b10c00fab5b52c4b7dd2cb
train
function
def visualize_labels_overlay(prob_map, val_imgs, num_images, alpha_label=0.6): """ :param prob_map: (n,H,W,C) where C= number of classes :param val_imgs: (n,H,W,C) where C=1 or 3 :return: """ n_classes = prob_map.shape[3] BG_INDEX = n_classes - 1 label_maps = np.argmax(prob_map, axis=...
def visualize_labels_overlay(prob_map, val_imgs, num_images, alpha_label=0.6):
""" :param prob_map: (n,H,W,C) where C= number of classes :param val_imgs: (n,H,W,C) where C=1 or 3 :return: """ n_classes = prob_map.shape[3] BG_INDEX = n_classes - 1 label_maps = np.argmax(prob_map, axis=3) alphas = np.ones_like(label_maps) * alpha_label alphas[label_maps ==...
.viz_dir, 'epoch' + str(epoch) + '.jpeg'), viz_out) if(epoch ==0): cv2.imwrite(os.path.join(self.viz_dir, 'ground_truth_epoch' + str(epoch) + '.jpeg'), viz_gt) cv2.imwrite(os.path.join(self.viz_dir, 'val_images_epoch' + str(epoch) + '.jpeg'), val_imgs) def visualize_labels_overlay(prob...
101
102
341
21
80
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
visualize_labels_overlay
visualize_labels_overlay
88
119
88
88
65ccab75d4d92a639a6dd600342d857885822286
bigcode/the-stack
train
91711408960b264ab033cdde
train
function
def stack_patches(patches, nr_row, nr_col): """ Stack patches, i.e, convert the image patches to a single image :param patches: N x H x W x c :return: nr_row*H x nr_col*W image """ assert (patches.shape[0] <= nr_row * nr_col), 'The number of patches should be equal to nr_row*nr_col' + str( ...
def stack_patches(patches, nr_row, nr_col):
""" Stack patches, i.e, convert the image patches to a single image :param patches: N x H x W x c :return: nr_row*H x nr_col*W image """ assert (patches.shape[0] <= nr_row * nr_col), 'The number of patches should be equal to nr_row*nr_col' + str( patches.shape[0]) + '<=' + str(nr_row) ...
_blank <= ngrid_y), ' too many blank grids, ' + str(n_blank) if n_blank > 0: ss = list(patches.shape) ss[0] = n_blank blank = np.zeros(tuple(ss)) patches = np.vstack([patches, blank]) return patches def stack_patches(patches, nr_row, nr_col):
79
79
266
13
65
parthi-bharathi/semantic-image-segmentation
segtrain/trainer/visializeoutput_checkpoint.py
Python
stack_patches
stack_patches
236
260
236
236
22c0d7604f741f3b1f83553dd9153e43afbeac7a
bigcode/the-stack
train
4f35a19ba79ba7f381485770
train
function
def main(): print (helloMessage("World"))
def main():
print (helloMessage("World"))
#!/usr/bin/env python def helloMessage(name): return "Hello, " + name + "!" def main():
25
64
11
3
22
wmacevoy/csci000-astudent
py3hello/hello/hello.py
Python
main
main
6
7
6
6
c34937d07dea93bdb8eef56ecdd6d693617fe588
bigcode/the-stack
train
6e8accf523c4a03549703543
train
function
def helloMessage(name): return "Hello, " + name + "!"
def helloMessage(name):
return "Hello, " + name + "!"
#!/usr/bin/env python def helloMessage(name):
11
64
16
5
5
wmacevoy/csci000-astudent
py3hello/hello/hello.py
Python
helloMessage
helloMessage
3
4
3
3
de0ea49d086dfea7583e192fa2ed21e7a9d96030
bigcode/the-stack
train
90e06b6d4714cf596172dff1
train
class
class UpdateCheckThread(QThread, Logger): checked = pyqtSignal(object) failed = pyqtSignal() def __init__(self): QThread.__init__(self) Logger.__init__(self) self.network = Network.get_instance() async def get_update_info(self): # note: Use long timeout here as it is no...
class UpdateCheckThread(QThread, Logger):
checked = pyqtSignal(object) failed = pyqtSignal() def __init__(self): QThread.__init__(self) Logger.__init__(self) self.network = Network.get_instance() async def get_update_info(self): # note: Use long timeout here as it is not critical that we get a response fast, ...
+ _("There is a new update available") + '</h2>') url = "<a href='{u}'>{u}</a>".format(u=UpdateCheck.download_url) self.detail_label.setText(_("You can download the new version from {}.").format(url)) else: self.heading_label.setText('<h2>' + _("Already up to...
152
152
507
9
143
Jesusown/electrum
electrum/gui/qt/update_checker.py
Python
UpdateCheckThread
UpdateCheckThread
97
144
97
97
204f0f38d7c4ee36f527475359be226f170e58a4
bigcode/the-stack
train
3a8ce360fa5698430d3e3ee3
train
class
class UpdateCheck(QDialog, Logger): url = "https://electrum.org/version" download_url = "https://electrum.org/#download" VERSION_ANNOUNCEMENT_SIGNING_KEYS = ( "13xjmVAB1EATPP8RshTE8S8sNwwSUM9p1P", # ThomasV (since 3.3.4) "1Nxgk6NTooV4qZsX5fdqQwrLjYcsQZAfTg", # ghost43 (since 4.1.2) ) ...
class UpdateCheck(QDialog, Logger):
url = "https://electrum.org/version" download_url = "https://electrum.org/#download" VERSION_ANNOUNCEMENT_SIGNING_KEYS = ( "13xjmVAB1EATPP8RshTE8S8sNwwSUM9p1P", # ThomasV (since 3.3.4) "1Nxgk6NTooV4qZsX5fdqQwrLjYcsQZAfTg", # ghost43 (since 4.1.2) ) def __init__(self, *, latest_ve...
# Copyright (C) 2019 The Electrum developers # Distributed under the MIT software license, see the accompanying # file LICENCE or http://www.opensource.org/licenses/mit-license.php import asyncio import base64 from distutils.version import StrictVersion from PyQt5.QtCore import Qt, QThread, pyqtSignal from PyQt5.QtWi...
163
216
723
8
154
Jesusown/electrum
electrum/gui/qt/update_checker.py
Python
UpdateCheck
UpdateCheck
22
94
22
22
a07cf675f83afbf883a31e186e693ca859773bb8
bigcode/the-stack
train
4d85a3f0f010f47219a6206b
train
class
class Solution(object): def titleToNumber(self, s): """ :type s: str :rtype: int """ n = 0 for c in s: n *= 26 n += 1 + ord(c) - ord('A') return n
class Solution(object):
def titleToNumber(self, s): """ :type s: str :rtype: int """ n = 0 for c in s: n *= 26 n += 1 + ord(c) - ord('A') return n
# https://leetcode.com/problems/excel-sheet-column-number/ class Solution(object):
16
64
66
4
12
Ravan339/LeetCode
Python/excel-sheet-column-number.py
Python
Solution
Solution
4
15
4
4
ea4f5623443ff220cc52e3fb8ca3fee78055831d
bigcode/the-stack
train
a5ab68754b9024656712749a
train
class
class PrometheusBeforeMiddleware(MiddlewareMixin): """Monitoring middleware that should run before other middlewares.""" metrics_cls = Metrics def __init__(self, get_response=None): super().__init__(get_response) self.metrics = self.metrics_cls.get_instance() def process_request(self,...
class PrometheusBeforeMiddleware(MiddlewareMixin):
"""Monitoring middleware that should run before other middlewares.""" metrics_cls = Metrics def __init__(self, get_response=None): super().__init__(get_response) self.metrics = self.metrics_cls.get_instance() def process_request(self, request): self.metrics.requests_total.inc(...
type.", ["type"], namespace=NAMESPACE, ) self.exceptions_by_view = self.register_metric( Counter, "django_http_exceptions_total_by_view", "Count of exceptions by view.", ["view"], namespace=NAMESPACE, ) class Pr...
64
64
149
9
55
markciecior/django-prometheus
django_prometheus/middleware.py
Python
PrometheusBeforeMiddleware
PrometheusBeforeMiddleware
194
215
194
194
5d1f1ee2c81322ba0ac9ba906d7c9b7e800fdd04
bigcode/the-stack
train
3c7e83a819a1c26c326c7f43
train
class
class PrometheusAfterMiddleware(MiddlewareMixin): """Monitoring middleware that should run after other middlewares.""" metrics_cls = Metrics def __init__(self, get_response=None): super().__init__(get_response) self.metrics = self.metrics_cls.get_instance() def _transport(self, reques...
class PrometheusAfterMiddleware(MiddlewareMixin):
"""Monitoring middleware that should run after other middlewares.""" metrics_cls = Metrics def __init__(self, get_response=None): super().__init__(get_response) self.metrics = self.metrics_cls.get_instance() def _transport(self, request): return "https" if request.is_secure() ...
namespace=NAMESPACE, ) # Set in process_exception self.exceptions_by_type = self.register_metric( Counter, "django_http_exceptions_total_by_type", "Count of exceptions by object type.", ["type"], namespace=NAMESPACE, ) ...
256
256
1,042
9
246
markciecior/django-prometheus
django_prometheus/middleware.py
Python
PrometheusAfterMiddleware
PrometheusAfterMiddleware
218
365
218
218
a554e039b52cb0219611f2ab447b42ee9134721a
bigcode/the-stack
train
10cbcf58d9169d4e0c508aff
train
class
class Metrics: _instance = None @classmethod def get_instance(cls): if not cls._instance: cls._instance = cls() return cls._instance def register_metric(self, metric_cls, name, documentation, labelnames=(), **kwargs): return metric_cls(name, documentation, labelname...
class Metrics:
_instance = None @classmethod def get_instance(cls): if not cls._instance: cls._instance = cls() return cls._instance def register_metric(self, metric_cls, name, documentation, labelnames=(), **kwargs): return metric_cls(name, documentation, labelnames=labelnames, *...
from django.conf import settings from django.utils.deprecation import MiddlewareMixin from prometheus_client import Counter, Histogram from django_prometheus.conf import NAMESPACE from django_prometheus.utils import PowersOf, Time, TimeSince DEFAULT_LATENCY_BUCKETS = ( 0.01, 0.025, 0.05, 0.075, 0....
159
256
1,083
3
156
markciecior/django-prometheus
django_prometheus/middleware.py
Python
Metrics
Metrics
29
191
29
29
c025676bd4c4eaf11a72d10e95962388b07468c2
bigcode/the-stack
train
228d0342a9e71a8a7c0f4441
train
class
class VenstarThermostat(ClimateDevice): """Representation of a Venstar thermostat.""" def __init__(self, client, humidifier): """Initialize the thermostat.""" self._client = client self._humidifier = humidifier self._mode_map = { HVAC_MODE_HEAT: self._client.MODE_HEA...
class VenstarThermostat(ClimateDevice):
"""Representation of a Venstar thermostat.""" def __init__(self, client, humidifier): """Initialize the thermostat.""" self._client = client self._humidifier = humidifier self._mode_map = { HVAC_MODE_HEAT: self._client.MODE_HEAT, HVAC_MODE_COOL: self._cli...
"temperature" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_HUMIDIFIER, default=True): cv.boolean, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_TIMEOUT,...
256
256
1,875
10
246
m2hofi94/home-assistant
homeassistant/components/venstar/climate.py
Python
VenstarThermostat
VenstarThermostat
94
346
94
94
7e5a40bc6d110adcae610e07bf0fa2e15aafa83e
bigcode/the-stack
train
721cf1e7a3af24755e7bcd9a
train
function
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Venstar thermostat.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) host = config.get(CONF_HOST) timeout = config.get(CONF_TIMEOUT) humidifier = config.get(CONF_HUMIDIFIER) if co...
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Venstar thermostat.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) host = config.get(CONF_HOST) timeout = config.get(CONF_TIMEOUT) humidifier = config.get(CONF_HUMIDIFIER) if config.get(CONF_SSL): proto = "https" else: proto =...
default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_TIMEOUT, default=5): vol.All( vol.Coerce(int), vol.Range(min=1) ), vol.Optional(CONF_USERNAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None):
64
64
141
15
49
m2hofi94/home-assistant
homeassistant/components/venstar/climate.py
Python
setup_platform
setup_platform
73
91
73
73
ef0b412e07f881245404ee6619980e69469dda0d
bigcode/the-stack
train
45b2e1a21182f5f4ce475f6b
train
class
class Ansible(base.Base): """ `Ansible`_ is the default provisioner. No other provisioner will be \ supported. Molecule's provisioner manages the instances lifecycle. However, the user must provide the create, destroy, and converge playbooks. Molecule's ``init`` subcommand will provide the n...
class Ansible(base.Base):
""" `Ansible`_ is the default provisioner. No other provisioner will be \ supported. Molecule's provisioner manages the instances lifecycle. However, the user must provide the create, destroy, and converge playbooks. Molecule's ``init`` subcommand will provide the necessary files for conveni...
including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be i...
256
256
6,192
6
250
joej164/molecule
molecule/provisioner/ansible.py
Python
Ansible
Ansible
34
943
34
34
f051e9cdbfd1b6f0772389a9a16eb1f2174e596b
bigcode/the-stack
train
6df58093d22d18327562f510
train
function
def create_impedance(net, from_bus, to_bus, rft_pu, xft_pu, sn_kva, rtf_pu=None, xtf_pu=None, name=None, in_service=True, index=None): """ Creates an per unit impedance element INPUT: **net** (pandapowerNet) - The pandapower network in which the element is created **fr...
def create_impedance(net, from_bus, to_bus, rft_pu, xft_pu, sn_kva, rtf_pu=None, xtf_pu=None, name=None, in_service=True, index=None):
""" Creates an per unit impedance element INPUT: **net** (pandapowerNet) - The pandapower network in which the element is created **from_bus** (int) - starting bus of the impedance **to_bus** (int) - ending bus of the impedance **r_pu** (float) - real part of the impedanc...
index** (int) - The unique ID of the created shunt """ q_kvar = -abs(q_kvar) # q is always negative for capacitor p_kw = abs(q_kvar * loss_factor) # p is always positive for active power losses return create_shunt(net, bus, q_kvar=q_kvar, p_kw=p_kw, **kwargs) def create_impedance(net, from_bus, to_bus...
133
133
445
49
84
mathildebadoual/pandapower
pandapower/create.py
Python
create_impedance
create_impedance
2,047
2,092
2,047
2,048
dc832292463c42d58a4157b39f4f7d9280e058dc
bigcode/the-stack
train
ae9fb952614a9df9a453f273
train
function
def create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None, df=1., parallel=1, in_service=True, max_loading_percent=nan): """ create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None, \ df=1., parallel=1, in_serv...
def create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None, df=1., parallel=1, in_service=True, max_loading_percent=nan):
""" create_line(net, from_bus, to_bus, length_km, std_type, name=None, index=None, geodata=None, \ df=1., parallel=1, in_service=True, max_loading_percent=nan) Creates a line element in net["line"] The line parameters are defined through the standard type library. INPUT: **net*...
"] = float(min_p_kw) if not isnan(max_p_kw): if "max_p_kw" not in net.ext_grid.columns: net.ext_grid.loc[:, "max_p_kw"] = pd.Series() net.ext_grid.loc[index, "max_p_kw"] = float(max_p_kw) if not isnan(min_q_kvar): if "min_q_kvar" not in net.ext_grid.columns: ne...
256
256
955
47
208
mathildebadoual/pandapower
pandapower/create.py
Python
create_line
create_line
1,173
1,268
1,173
1,174
4467f02d6a20570321b8aa91d65d210f29e9d781
bigcode/the-stack
train
bb9e5831b6f676f4b7286ea3
train
function
def create_gen(net, bus, p_kw, vm_pu=1., sn_kva=nan, name=None, index=None, max_q_kvar=nan, min_q_kvar=nan, min_p_kw=nan, max_p_kw=nan, scaling=1., type=None, controllable=nan, vn_kv=nan, xdss=nan, rdss=nan, cos_phi=nan, in_service=True): """create_gen(net, bus, p_kw, vm_pu=1., sn_kva=...
def create_gen(net, bus, p_kw, vm_pu=1., sn_kva=nan, name=None, index=None, max_q_kvar=nan, min_q_kvar=nan, min_p_kw=nan, max_p_kw=nan, scaling=1., type=None, controllable=nan, vn_kv=nan, xdss=nan, rdss=nan, cos_phi=nan, in_service=True):
"""create_gen(net, bus, p_kw, vm_pu=1., sn_kva=nan, name=None, index=None, max_q_kvar=nan, \ min_q_kvar=nan, min_p_kw=nan, max_p_kw=nan, scaling=1., type=None, \ controllable=nan, vn_kv=nan, xdss=nan, rdss=nan, cos_phi=nan, in_service=True) Adds a generator to the network. Gen...
_kvar"] = pd.Series() net.storage.loc[index, "min_q_kvar"] = float(min_q_kvar) if not isnan(max_q_kvar): if "max_q_kvar" not in net.storage.columns: net.storage.loc[:, "max_q_kvar"] = pd.Series() net.storage.loc[index, "max_q_kvar"] = float(max_q_kvar) if not isnan(contro...
256
256
1,416
93
162
mathildebadoual/pandapower
pandapower/create.py
Python
create_gen
create_gen
923
1,050
923
925
98e103c65eae78d6e3c0cb9d242849c5f5c96848
bigcode/the-stack
train
9024aa0a1d6f4187ae93ef5b
train
function
def create_transformer3w(net, hv_bus, mv_bus, lv_bus, std_type, name=None, tp_pos=nan, in_service=True, index=None, max_loading_percent=nan, tap_at_star_point=False): """create_transformer3w(net, hv_bus, mv_bus, lv_bus, std_type, name=None, tp_pos=nan, \ ...
def create_transformer3w(net, hv_bus, mv_bus, lv_bus, std_type, name=None, tp_pos=nan, in_service=True, index=None, max_loading_percent=nan, tap_at_star_point=False):
"""create_transformer3w(net, hv_bus, mv_bus, lv_bus, std_type, name=None, tp_pos=nan, \ in_service=True, index=None, max_loading_percent=nan, \ tap_at_star_point=False) Creates a three-winding transformer in table net["trafo3w"]. The trafo parameters are def...
_phase_shifter": tp_phase_shifter, "parallel": parallel, "df": df } if ("tp_mid" in v) and (tp_pos is nan): v["tp_pos"] = v["tp_mid"] else: v["tp_pos"] = tp_pos if type(tp_pos) == float: net.trafo.tp_pos = net.trafo.tp_pos.astype(float) # store dtypes dtypes = n...
256
256
1,230
49
206
mathildebadoual/pandapower
pandapower/create.py
Python
create_transformer3w
create_transformer3w
1,616
1,723
1,616
1,618
a5620c3037cfb7857e2db7d62bf60fe61f16a759
bigcode/the-stack
train
ae3aefd7e6b0b58d4106fed6
train
function
def create_empty_network(name="", f_hz=50., sn_kva=1e3): """ This function initializes the pandapower datastructure. OPTIONAL: **f_hz** (float, 50.) - power system frequency in hertz **name** (string, None) - name for the network **sn_kva** (float, 1e3) - reference apparent power ...
def create_empty_network(name="", f_hz=50., sn_kva=1e3):
""" This function initializes the pandapower datastructure. OPTIONAL: **f_hz** (float, 50.) - power system frequency in hertz **name** (string, None) - name for the network **sn_kva** (float, 1e3) - reference apparent power for per unit system OUTPUT: **net** (attrdic...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2018 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. import pandas as pd from numpy import nan, isnan, arange, dtype, zeros from pandapower.auxiliary import pandapowerNet, get_free_i...
145
256
2,985
20
125
mathildebadoual/pandapower
pandapower/create.py
Python
create_empty_network
create_empty_network
16
319
16
16
2f45746369c0e6795bf6928c3b9168e5fbfb2701
bigcode/the-stack
train
c9ae84f68fadce787113b6f9
train
function
def create_switch(net, bus, element, et, closed=True, type=None, name=None, index=None): """ Adds a switch in the net["switch"] table. Switches can be either between to buses (bus-bus switch) or at the end of a line or transformer element (bus-elememnt switch). Two buses that are connected through...
def create_switch(net, bus, element, et, closed=True, type=None, name=None, index=None):
""" Adds a switch in the net["switch"] table. Switches can be either between to buses (bus-bus switch) or at the end of a line or transformer element (bus-elememnt switch). Two buses that are connected through a closed bus-bus switches are fused in the power flow if the switch es closed or sep...
"tap_at_star_point" ]] = \ [lv_bus, mv_bus, hv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv, sn_hv_kva, sn_mv_kva, sn_lv_kva, vsc_hv_percent, vsc_mv_percent, vsc_lv_percent, vscr_hv_percent, vscr_mv_percent, vscr_lv_percent, pfe_kw, i0_percent, shift_mv_degree, shift_lv_degree, tp_side...
256
256
926
23
232
mathildebadoual/pandapower
pandapower/create.py
Python
create_switch
create_switch
1,873
1,959
1,873
1,873
784bb27025f83bf19856f6ce87ffa2fc271ea687
bigcode/the-stack
train
e491c6819266a7babd02b1fb
train
function
def create_transformer3w_from_parameters(net, hv_bus, mv_bus, lv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv, sn_hv_kva, sn_mv_kva, sn_lv_kva, vsc_hv_percent, vsc_mv_percent, vsc_lv_percent, vscr_hv_percent, ...
def create_transformer3w_from_parameters(net, hv_bus, mv_bus, lv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv, sn_hv_kva, sn_mv_kva, sn_lv_kva, vsc_hv_percent, vsc_mv_percent, vsc_lv_percent, vscr_hv_percent, ...
"""create_transformer3w_from_parameters(net, hv_bus, mv_bus, lv_bus, vn_hv_kv, vn_mv_kv, vn_lv_kv, \ sn_hv_kva, sn_mv_kva, sn_lv_kva, vsc_hv_percent, \ vsc_mv_percent, vsc_lv_percent, vscr_hv_percent, \ ...
(dd).reindex_axis(net["trafo3w"].columns, axis=1) if not isnan(max_loading_percent): if "max_loading_percent" not in net.trafo3w.columns: net.trafo3w.loc[:, "max_loading_percent"] = pd.Series() net.trafo3w.loc[index, "max_loading_percent"] = float(max_loading_percent) return index...
256
256
1,758
169
86
mathildebadoual/pandapower
pandapower/create.py
Python
create_transformer3w_from_parameters
create_transformer3w_from_parameters
1,726
1,870
1,726
1,734
920e8ad89f927d52a3521ebb40f32ef862500f36
bigcode/the-stack
train
a8353c89eef2de363befed53
train
function
def create_transformer_from_parameters(net, hv_bus, lv_bus, sn_kva, vn_hv_kv, vn_lv_kv, vscr_percent, vsc_percent, pfe_kw, i0_percent, shift_degree=0, tp_side=None, tp_mid=nan, tp_max=nan, tp_min=nan, tp...
def create_transformer_from_parameters(net, hv_bus, lv_bus, sn_kva, vn_hv_kv, vn_lv_kv, vscr_percent, vsc_percent, pfe_kw, i0_percent, shift_degree=0, tp_side=None, tp_mid=nan, tp_max=nan, tp_min=nan, tp...
"""create_transformer_from_parameters(net, hv_bus, lv_bus, sn_kva, vn_hv_kv, vn_lv_kv, \ vscr_percent, vsc_percent, pfe_kw, i0_percent, \ shift_degree=0, tp_side=None, tp_mid=nan, tp_max=nan, \ tp_mi...
fo.dtypes net.trafo.loc[index, list(v.keys())] = list(v.values()) if not isnan(max_loading_percent): if "max_loading_percent" not in net.trafo.columns: net.trafo.loc[:, "max_loading_percent"] = pd.Series() net.trafo.loc[index, "max_loading_percent"] = float(max_loading_percent) ...
256
256
1,443
125
130
mathildebadoual/pandapower
pandapower/create.py
Python
create_transformer_from_parameters
create_transformer_from_parameters
1,480
1,613
1,480
1,486
6989f3fb0abbc23abb67f0490ced67a425c64013
bigcode/the-stack
train
73b2606cc7a9783004eae0c6
train
function
def create_ext_grid(net, bus, vm_pu=1.0, va_degree=0., name=None, in_service=True, s_sc_max_mva=nan, s_sc_min_mva=nan, rx_max=nan, rx_min=nan, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, index=None, **kwargs): """create_ext_grid(net, bus, v...
def create_ext_grid(net, bus, vm_pu=1.0, va_degree=0., name=None, in_service=True, s_sc_max_mva=nan, s_sc_min_mva=nan, rx_max=nan, rx_min=nan, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, index=None, **kwargs):
"""create_ext_grid(net, bus, vm_pu=1.0, va_degree=0., name=None, in_service=True,\ s_sc_max_mva=nan, s_sc_min_mva=nan, rx_max=nan, rx_min=nan,\ max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan,\ index=None) Creates an external grid connection...
.loc[index, "vn_kv"] = float(vn_kv) if not isnan(xdss): if "xdss" not in net.gen.columns: net.gen.loc[:, "xdss"] = pd.Series() net.gen.loc[index, "xdss"] = float(xdss) if not isnan(rdss): if "rdss" not in net.gen.columns: net.gen.loc[:, "rdss"] = pd.Series() ...
256
256
1,227
89
166
mathildebadoual/pandapower
pandapower/create.py
Python
create_ext_grid
create_ext_grid
1,053
1,170
1,053
1,056
c4f127f032a7d520f36cb54d29f2e3a3e8305934
bigcode/the-stack
train
6b9d68ba71abfd583a06a40a
train
function
def create_load(net, bus, p_kw, q_kvar=0, const_z_percent=0, const_i_percent=0, sn_kva=nan, name=None, scaling=1., index=None, in_service=True, type=None, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, controllable=nan): """create_load(net, bus, p_kw, q_k...
def create_load(net, bus, p_kw, q_kvar=0, const_z_percent=0, const_i_percent=0, sn_kva=nan, name=None, scaling=1., index=None, in_service=True, type=None, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, controllable=nan):
"""create_load(net, bus, p_kw, q_kvar=0, const_z_percent=0, const_i_percent=0, sn_kva=nan, \ name=None, scaling=1., index=None, \ in_service=True, type=None, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, \ min_q_kvar=nan, controllable=nan) Adds one load in ...
-tuple or a matching array net.bus_geodata = net.bus_geodata.append(pd.DataFrame(index=index, columns=net.bus_geodata.columns)) net.bus_geodata.loc[index, ["x", "y"]] = geodata if not isnan(min_vm_pu): if "min_vm_pu" not in net.bu...
256
256
1,225
85
170
mathildebadoual/pandapower
pandapower/create.py
Python
create_load
create_load
478
598
478
481
5783e46cc5ae8f3338d3a35bceca925d07849b15
bigcode/the-stack
train
a99bc07a6c8e2407195676f6
train
function
def create_transformer(net, hv_bus, lv_bus, std_type, name=None, tp_pos=nan, in_service=True, index=None, max_loading_percent=nan, parallel=1, df=1.): """create_transformer(net, hv_bus, lv_bus, std_type, name=None, tp_pos=nan, in_service=True, \ index=None, max_loading_...
def create_transformer(net, hv_bus, lv_bus, std_type, name=None, tp_pos=nan, in_service=True, index=None, max_loading_percent=nan, parallel=1, df=1.):
"""create_transformer(net, hv_bus, lv_bus, std_type, name=None, tp_pos=nan, in_service=True, \ index=None, max_loading_percent=nan, parallel=1, df=1.) Creates a two-winding transformer in table net["trafo"]. The trafo parameters are defined through the standard type library. INPU...
m": r_ohm_per_km, "x_ohm_per_km": x_ohm_per_km, "c_nf_per_km": c_nf_per_km, "max_i_ka": max_i_ka, "parallel": parallel, "type": type, "g_us_per_km": g_us_per_km } # store dtypes dtypes = net.line.dtypes net.line.loc[index, list(v.keys())] = list(v.values()) # and preserve dtypes ...
256
256
1,065
46
209
mathildebadoual/pandapower
pandapower/create.py
Python
create_transformer
create_transformer
1,373
1,477
1,373
1,374
bd93edb1ae9842f28fcd95aab246acad82add4d7
bigcode/the-stack
train
5685590ca55665831bd4f8df
train
function
def create_shunt(net, bus, q_kvar, p_kw=0., vn_kv=None, step=1, max_step=1, name=None, in_service=True, index=None): """create_shunt(net, bus, q_kvar, p_kw=0., vn_kv=None, step=1, max_step=nan, name=None, in_service=True, index=None) Creates a shunt element INPUT: ...
def create_shunt(net, bus, q_kvar, p_kw=0., vn_kv=None, step=1, max_step=1, name=None, in_service=True, index=None):
"""create_shunt(net, bus, q_kvar, p_kw=0., vn_kv=None, step=1, max_step=nan, name=None, in_service=True, index=None) Creates a shunt element INPUT: **net** (pandapowerNet) - The pandapower network in which the element is created **bus** - bus number of bus to whom the shun...
raise UserWarning("Unknown element type") if index is None: index = get_free_id(net["switch"]) if index in net["switch"].index: raise UserWarning("A switch with index %s already exists" % index) # store dtypes dtypes = net.switch.dtypes net.switch.loc[index, ["bus", "eleme...
172
172
575
42
129
mathildebadoual/pandapower
pandapower/create.py
Python
create_shunt
create_shunt
1,962
2,019
1,962
1,963
3c9a19fe52339b4a50dd5a3b7e31dd6e483cfc6f
bigcode/the-stack
train
d1f00093f9811d7636ab6ed9
train
function
def create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b", zone=None, in_service=True, max_vm_pu=nan, min_vm_pu=nan, **kwargs): """create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b", \ zone=None, in_service=True, max_vm_pu=nan, min_vm_...
def create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b", zone=None, in_service=True, max_vm_pu=nan, min_vm_pu=nan, **kwargs):
"""create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b", \ zone=None, in_service=True, max_vm_pu=nan, min_vm_pu=nan) Adds one bus in table net["bus"]. Busses are the nodes of the network that all other elements connect to. INPUT: **net** (pandapowerNet) - The ...
8")], # internal "_ppc": None, "_is_elements": None, "_pd2ppc_lookups": {"bus": None, "ext_grid": None, "gen": None}, "version": float(__version__[:3]), "converged": False, "name": name, "f_hz": f_hz...
210
210
702
49
160
mathildebadoual/pandapower
pandapower/create.py
Python
create_bus
create_bus
322
393
322
324
5136bc33eb30acdc100d224565064f117a106874
bigcode/the-stack
train
916aac33a33b70c72f94d890
train
function
def create_sgen(net, bus, p_kw, q_kvar=0, sn_kva=nan, name=None, index=None, scaling=1., type=None, in_service=True, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, controllable=nan, k=nan, rx=nan): """create_sgen(net, bus, p_kw, q_kvar=0, sn_kva=nan, name=None, index=Non...
def create_sgen(net, bus, p_kw, q_kvar=0, sn_kva=nan, name=None, index=None, scaling=1., type=None, in_service=True, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, controllable=nan, k=nan, rx=nan):
"""create_sgen(net, bus, p_kw, q_kvar=0, sn_kva=nan, name=None, index=None, \ scaling=1., type=None, in_service=True, max_p_kw=nan, min_p_kw=nan, \ max_q_kvar=nan, min_q_kvar=nan, controllable=nan, k=nan, rx=nan) Adds one static generator in table net["sgen"]. Static generat...
power factor cos_phi **mode** (str) - "ind" for inductive or "cap" for capacitive behaviour **kwargs are passed on to the create_load function OUTPUT: **index** (int) - The unique ID of the created load All elements are modeled from a consumer point of view. Active power will theref...
256
256
1,345
81
175
mathildebadoual/pandapower
pandapower/create.py
Python
create_sgen
create_sgen
630
762
630
632
9459147100bb146cd04c27a92e6008cb354097c6
bigcode/the-stack
train
cfd2a7fe90a4684d55978784
train
function
def create_xward(net, bus, ps_kw, qs_kvar, pz_kw, qz_kvar, r_ohm, x_ohm, vm_pu, in_service=True, name=None, index=None): """ Creates an extended ward equivalent. A ward equivalent is a combination of an impedance load, a PQ load and as voltage source with an internal impedance. IN...
def create_xward(net, bus, ps_kw, qs_kvar, pz_kw, qz_kvar, r_ohm, x_ohm, vm_pu, in_service=True, name=None, index=None):
""" Creates an extended ward equivalent. A ward equivalent is a combination of an impedance load, a PQ load and as voltage source with an internal impedance. INPUT: **net** - The pandapower net within the impedance should be created **bus** (int) - bus of the ward equivalent ...
, ["bus", "ps_kw", "qs_kvar", "pz_kw", "qz_kvar", "name", "in_service"]] = \ [bus, ps_kw, qs_kvar, pz_kw, qz_kvar, name, in_service] # and preserve dtypes _preserve_dtypes(net.ward, dtypes) return index def create_xward(net, bus, ps_kw, qs_kvar, pz_kw, qz_kvar, r_ohm, x_ohm, vm_pu, in_service=True...
130
130
436
49
80
mathildebadoual/pandapower
pandapower/create.py
Python
create_xward
create_xward
2,174
2,219
2,174
2,175
6c96c311474a561447e7000fd9c6581266bcc9d6
bigcode/the-stack
train
aefb8b3990f8a72ddf22c12e
train
function
def create_series_reactor_as_impedance(net, from_bus, to_bus, r_ohm, x_ohm, sn_kva, name=None, in_service=True, index=None): """ Creates a series reactor as per-unit impedance :param net: (pandapowerNet) - The pandapower network in which the element is created :par...
def create_series_reactor_as_impedance(net, from_bus, to_bus, r_ohm, x_ohm, sn_kva, name=None, in_service=True, index=None):
""" Creates a series reactor as per-unit impedance :param net: (pandapowerNet) - The pandapower network in which the element is created :param from_bus: (int) - starting bus of the series reactor :param to_bus: (int) - ending bus of the series reactor :param r_ohm: (float) - real part of the imp...
edance.loc[index, ["from_bus", "to_bus", "rft_pu", "xft_pu", "rtf_pu", "xtf_pu", "name", "sn_kva", "in_service"]] = \ [from_bus, to_bus, rft_pu, xft_pu, rtf_pu, xtf_pu, name, sn_kva, in_service] # and preserve dtypes _preserve_dtypes(net.impedance, dtypes) return inde...
153
153
512
41
111
mathildebadoual/pandapower
pandapower/create.py
Python
create_series_reactor_as_impedance
create_series_reactor_as_impedance
2,095
2,128
2,095
2,096
2651b7e2dd3b0609a72c34ebc2ac2bdd8831fbaa
bigcode/the-stack
train
59519188f743184d08866202
train
function
def create_line_from_parameters(net, from_bus, to_bus, length_km, r_ohm_per_km, x_ohm_per_km, c_nf_per_km, max_i_ka, name=None, index=None, type=None, geodata=None, in_service=True, df=1., parallel=1, g_us_per_km=0., max_loa...
def create_line_from_parameters(net, from_bus, to_bus, length_km, r_ohm_per_km, x_ohm_per_km, c_nf_per_km, max_i_ka, name=None, index=None, type=None, geodata=None, in_service=True, df=1., parallel=1, g_us_per_km=0., max_loa...
"""create_line_from_parameters(net, from_bus, to_bus, length_km, r_ohm_per_km, x_ohm_per_km, \ c_nf_per_km, max_i_ka, name=None, index=None, type=None, \ geodata=None, in_service=True, df=1., parallel=1, g_us_per_km=0.,\ ...
"g_us_per_km" in lineparam else 0. if "type" in lineparam: v["type"] = lineparam["type"] # store dtypes dtypes = net.line.dtypes net.line.loc[index, list(v.keys())] = list(v.values()) # and preserve dtypes _preserve_dtypes(net.line, dtypes) if geodata is not None: net[...
256
256
1,107
89
166
mathildebadoual/pandapower
pandapower/create.py
Python
create_line_from_parameters
create_line_from_parameters
1,271
1,370
1,271
1,274
bc9f0e7407a14db1c379f6fb8f5f1547c9e83585
bigcode/the-stack
train
a703d7aa02d05a0b2f37ac98
train
function
def create_load_from_cosphi(net, bus, sn_kva, cos_phi, mode, **kwargs): """ Creates a load element from rated power and power factor cos(phi). INPUT: **net** - The net within this static generator should be created **bus** (int) - The bus id to which the load is connected **sn_kva...
def create_load_from_cosphi(net, bus, sn_kva, cos_phi, mode, **kwargs):
""" Creates a load element from rated power and power factor cos(phi). INPUT: **net** - The net within this static generator should be created **bus** (int) - The bus id to which the load is connected **sn_kva** (float) - rated power of the load **cos_phi** (float) - powe...
net.load.loc[:, "controllable"] = pd.Series() net.load.loc[index, "controllable"] = bool(controllable) else: if "controllable" in net.load.columns: net.load.loc[index, "controllable"] = False return index def create_load_from_cosphi(net, bus, sn_kva, cos_phi, mode, **kw...
82
82
275
23
58
mathildebadoual/pandapower
pandapower/create.py
Python
create_load_from_cosphi
create_load_from_cosphi
601
627
601
601
568d6c4c60e92b75eb5775640becd7b59cfb404f
bigcode/the-stack
train
398ad625a4edc924188540aa
train
function
def create_shunt_as_capacitor(net, bus, q_kvar, loss_factor, **kwargs): """ Creates a shunt element representing a capacitor bank. INPUT: **net** (pandapowerNet) - The pandapower network in which the element is created **bus** - bus number of bus to whom the shunt is connected to ...
def create_shunt_as_capacitor(net, bus, q_kvar, loss_factor, **kwargs):
""" Creates a shunt element representing a capacitor bank. INPUT: **net** (pandapowerNet) - The pandapower network in which the element is created **bus** - bus number of bus to whom the shunt is connected to **q_kvar** (float) - reactive power of the capacitor bank at rated volt...
_kw, q_kvar, vn_kv, step, max_step, in_service] # and preserve dtypes _preserve_dtypes(net.shunt, dtypes) return index def create_shunt_as_capacitor(net, bus, q_kvar, loss_factor, **kwargs):
65
65
219
22
42
mathildebadoual/pandapower
pandapower/create.py
Python
create_shunt_as_capacitor
create_shunt_as_capacitor
2,022
2,044
2,022
2,022
c45fbe145f154f3eed006070154504c708bad33c
bigcode/the-stack
train
c01d3b8f09821f53f3a3a6cc
train
function
def create_measurement(net, meas_type, element_type, value, std_dev, bus, element=None, check_existing=True, index=None, name=None): """ Creates a measurement, which is used by the estimation module. Possible types of measurements are: v, p, q, i INPUT: **meas_type** (str...
def create_measurement(net, meas_type, element_type, value, std_dev, bus, element=None, check_existing=True, index=None, name=None):
""" Creates a measurement, which is used by the estimation module. Possible types of measurements are: v, p, q, i INPUT: **meas_type** (string) - Type of measurement. "v", "p", "q", "i" are possible. **element_type** (string) - Clarifies which element is measured. "bus", "line", ...
= get_free_id(net["dcline"]) if index in net["dcline"].index: raise UserWarning("A dcline with the id %s already exists" % index) # store dtypes dtypes = net.dcline.dtypes net.dcline.loc[index, ["name", "from_bus", "to_bus", "p_kw", "loss_percent", "loss_kw", "vm_f...
256
256
1,059
33
222
mathildebadoual/pandapower
pandapower/create.py
Python
create_measurement
create_measurement
2,298
2,398
2,298
2,299
d70e6b4b6c59141578f4d5d6f3e3a0b58354c24a
bigcode/the-stack
train
750d78ef1daeb82411537b0f
train
function
def create_storage(net, bus, p_kw, max_e_kwh, q_kvar=0, sn_kva=nan, soc_percent=nan, min_e_kwh=0.0, name=None, index=None, scaling=1., type=None, in_service=True, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, controllable = nan): """create_storage(net, bus, p_kw, ...
def create_storage(net, bus, p_kw, max_e_kwh, q_kvar=0, sn_kva=nan, soc_percent=nan, min_e_kwh=0.0, name=None, index=None, scaling=1., type=None, in_service=True, max_p_kw=nan, min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, controllable = nan):
"""create_storage(net, bus, p_kw, max_e_kwh, q_kvar=0, sn_kva=nan, soc_percent=nan, min_e_kwh=0.0, \ name=None, index=None, scaling=1., type=None, in_service=True, max_p_kw=nan, \ min_p_kw=nan, max_q_kvar=nan, min_q_kvar=nan, controllable = nan) Adds a storage to the networ...
cos_phi **mode** (str) - "ind" for inductive or "cap" for capacitive behaviour OUTPUT: **index** (int) - The unique ID of the created sgen All elements including generators are modeled from a consumer point of view. Active power will therefore always be negative, reactive power will be n...
256
256
1,377
91
165
mathildebadoual/pandapower
pandapower/create.py
Python
create_storage
create_storage
792
920
792
794
6729bde7ca59a25c840281fa7fd8aa4ee2386336
bigcode/the-stack
train
4cb606c509fcf05003bc4bdf
train
function
def create_dcline(net, from_bus, to_bus, p_kw, loss_percent, loss_kw, vm_from_pu, vm_to_pu, index=None, name=None, max_p_kw=nan, min_q_from_kvar=nan, min_q_to_kvar=nan, max_q_from_kvar=nan, max_q_to_kvar=nan, in_service=True): """create_dcline(net, from_bus, to_...
def create_dcline(net, from_bus, to_bus, p_kw, loss_percent, loss_kw, vm_from_pu, vm_to_pu, index=None, name=None, max_p_kw=nan, min_q_from_kvar=nan, min_q_to_kvar=nan, max_q_from_kvar=nan, max_q_to_kvar=nan, in_service=True):
"""create_dcline(net, from_bus, to_bus, p_kw, loss_percent, loss_kw, vm_from_pu, vm_to_pu, \ index=None, name=None, max_p_kw=nan, min_q_from_kvar=nan, \ min_q_to_kvar=nan, max_q_from_kvar=nan, max_q_to_kvar=nan, \ in_service=True) Creates a dc line. INP...
index = get_free_id(net.xward) if index in net["xward"].index: raise UserWarning("An extended ward equivalent with index %s already exists" % index) # store dtypes dtypes = net.xward.dtypes net.xward.loc[index, ["bus", "ps_kw", "qs_kvar", "pz_kw", "qz_kvar", "r_ohm", "x_ohm", "vm_pu", ...
256
256
855
82
173
mathildebadoual/pandapower
pandapower/create.py
Python
create_dcline
create_dcline
2,222
2,295
2,222
2,225
34e4edbd5dc459ba346dedf23259c0304d7f68cd
bigcode/the-stack
train
736a30ac67156298fba1ac5f
train
function
def create_piecewise_linear_cost(net, element, element_type, data_points, type="p", index=None): """ Creates an entry for piecewise linear costs for an element. The currently supported elements are - Generator - External Grid - Static Generator - Load - Dcline - Storage INPUT:...
def create_piecewise_linear_cost(net, element, element_type, data_points, type="p", index=None):
""" Creates an entry for piecewise linear costs for an element. The currently supported elements are - Generator - External Grid - Static Generator - Load - Dcline - Storage INPUT: **element** (int) - ID of the element in the respective element table **element...
fo"): raise UserWarning("Voltage measurements can only be placed at buses, not at %s" % element_type) if check_existing: if element is None: existing = net.measurement[(net.measurement.type == meas_type) & (net.measurement...
256
256
1,130
23
232
mathildebadoual/pandapower
pandapower/create.py
Python
create_piecewise_linear_cost
create_piecewise_linear_cost
2,401
2,506
2,401
2,401
1a3a03e0080e159d28f653dc8b8c1ca78212e649
bigcode/the-stack
train
698cd822642917a0185346fc
train
function
def create_sgen_from_cosphi(net, bus, sn_kva, cos_phi, mode, **kwargs): """ Creates an sgen element from rated power and power factor cos(phi). INPUT: **net** - The net within this static generator should be created **bus** (int) - The bus id to which the static generator is connected ...
def create_sgen_from_cosphi(net, bus, sn_kva, cos_phi, mode, **kwargs):
""" Creates an sgen element from rated power and power factor cos(phi). INPUT: **net** - The net within this static generator should be created **bus** (int) - The bus id to which the static generator is connected **sn_kva** (float) - rated power of the generator **cos_ph...
"k"] = float(k) if not isnan(rx): if "rx" not in net.sgen.columns: net.sgen.loc[:, "rx"] = pd.Series() net.sgen.loc[index, "rx"] = float(rx) return index def create_sgen_from_cosphi(net, bus, sn_kva, cos_phi, mode, **kwargs):
81
81
270
24
56
mathildebadoual/pandapower
pandapower/create.py
Python
create_sgen_from_cosphi
create_sgen_from_cosphi
765
789
765
765
a8dbcce9b2b6166ffb78758afd79201ee283d7f8
bigcode/the-stack
train
f6359c2ee6d22b639b135186
train
function
def create_buses(net, nr_buses, vn_kv, index=None, name=None, type="b", geodata=None, zone=None, in_service=True, max_vm_pu=nan, min_vm_pu=nan): """create_buses(net, nr_buses, vn_kv, index=None, name=None, type="b", geodata=None, \ zone=None, in_service=True, max_vm_pu=nan, min_...
def create_buses(net, nr_buses, vn_kv, index=None, name=None, type="b", geodata=None, zone=None, in_service=True, max_vm_pu=nan, min_vm_pu=nan):
"""create_buses(net, nr_buses, vn_kv, index=None, name=None, type="b", geodata=None, \ zone=None, in_service=True, max_vm_pu=nan, min_vm_pu=nan) Adds several buses in table net["bus"] at once. Busses are the nodal points of the network that all other elements connect to. Input: ...
dtypes _preserve_dtypes(net.bus, dtypes) if geodata is not None: if len(geodata) != 2: raise UserWarning("geodata must be given as (x, y) tupel") net["bus_geodata"].loc[index, ["x", "y"]] = geodata if not isnan(min_vm_pu): if "min_vm_pu" not in net.bus.columns: ...
243
243
810
50
192
mathildebadoual/pandapower
pandapower/create.py
Python
create_buses
create_buses
396
475
396
397
96908aa463e242a996fdfe62193078c4ec0b3db4
bigcode/the-stack
train
8ac48ecc6b0de5d14d53aebd
train
function
def create_polynomial_cost(net, element, element_type, coefficients, type="p", index=None): """ Creates an entry for polynomial costs for an element. The currently supported elements are - Generator - External Grid - Static Generator - Load - Dcline - Storage INPUT: **...
def create_polynomial_cost(net, element, element_type, coefficients, type="p", index=None):
""" Creates an entry for polynomial costs for an element. The currently supported elements are - Generator - External Grid - Static Generator - Load - Dcline - Storage INPUT: **element** (int) - ID of the element in the respective element table **element_type*...
max_q_from_kvar.at[element] <= max(p) and net[element_type].min_q_to_kvar.at[element] <= min(p) and net[element_type].min_q_from_kvar.at[element] >= min(p)): raise ValueError("Cost function must be defined for whole power range of the " ...
167
167
559
21
145
mathildebadoual/pandapower
pandapower/create.py
Python
create_polynomial_cost
create_polynomial_cost
2,509
2,571
2,509
2,509
f324d0adc73a9f430c159f2baf72c342da18ad5e
bigcode/the-stack
train
14598d3dacc7aab0a2d2ce1a
train
function
def create_ward(net, bus, ps_kw, qs_kvar, pz_kw, qz_kvar, name=None, in_service=True, index=None): """ Creates a ward equivalent. A ward equivalent is a combination of an impedance load and a PQ load. INPUT: **net** (pandapowernet) - The pandapower net within the element should be created ...
def create_ward(net, bus, ps_kw, qs_kvar, pz_kw, qz_kvar, name=None, in_service=True, index=None):
""" Creates a ward equivalent. A ward equivalent is a combination of an impedance load and a PQ load. INPUT: **net** (pandapowernet) - The pandapower net within the element should be created **bus** (int) - bus of the ward equivalent **ps_kw** (float) - active power of the P...
_pu = x_ohm / base_z_ohm index = create_impedance(net, from_bus=from_bus, to_bus=to_bus, rft_pu=rft_pu, xft_pu=xft_pu, sn_kva=sn_kva, name=name, in_service=in_service, index=index) return index def create_ward(net, bus, ps_kw, qs_kvar, pz_kw, qz_kvar, n...
111
111
372
34
76
mathildebadoual/pandapower
pandapower/create.py
Python
create_ward
create_ward
2,131
2,171
2,131
2,131
1a49bdc3a67fabcadff49ee925f0eb8a9b623381
bigcode/the-stack
train
bfbe2fa3d74ce7b2c7636244
train
function
def go_rules_dependencies(): """Declares workspaces the Go rules depend on. Workspaces that use rules_go should call this. See https://github.com/bazelbuild/rules_go/blob/master/go/workspace.rst#overriding-dependencies for information on each dependency. Instructions for updating this file are in ...
def go_rules_dependencies():
"""Declares workspaces the Go rules depend on. Workspaces that use rules_go should call this. See https://github.com/bazelbuild/rules_go/blob/master/go/workspace.rst#overriding-dependencies for information on each dependency. Instructions for updating this file are in https://github.com/bazelb...
(the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # W...
256
256
2,755
5
251
michaelhenkel/rules_go
go/private/repositories.bzl
Python
go_rules_dependencies
go_rules_dependencies
24
236
24
24
fe346212e73a82a5d0b281785c1018d9e50bc578
bigcode/the-stack
train
b51c96e926550239cbd210f4
train
function
def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs)
def _maybe(repo_rule, name, **kwargs):
if name not in native.existing_rules(): repo_rule(name = name, **kwargs)
call that function (they may declare their own @go_sdk and # register their own toolchains). _maybe( go_register_nogo, name = "io_bazel_rules_nogo", nogo = DEFAULT_NOGO, ) def _maybe(repo_rule, name, **kwargs):
64
64
31
11
53
michaelhenkel/rules_go
go/private/repositories.bzl
Python
_maybe
_maybe
238
240
238
238
0b5ba27231c92fd355e9322fe5e0c99dd1c3daca
bigcode/the-stack
train
b83bb261ede8f2aae46a3958
train
class
class TestCRC(unittest.TestCase): def test_first(self): """ Test CRC16 trivial case """ buffer = b'\x01\x02\x03\x04' crc = crc16(buffer) self.assertEqual(crc, 0xc66e) return buffer,crc def test_second(self): """ Test CRC16 residual calculation """ buffer...
class TestCRC(unittest.TestCase):
def test_first(self): """ Test CRC16 trivial case """ buffer = b'\x01\x02\x03\x04' crc = crc16(buffer) self.assertEqual(crc, 0xc66e) return buffer,crc def test_second(self): """ Test CRC16 residual calculation """ buffer,crc = self.test_first() # ...
#!/usr/bin/env python # # Simple test cases for a Python version of the yubikey_crc16() function in ykcrc.c. # import struct import unittest import yubico.yubico_util as yubico_util from yubico.yubico_util import crc16 CRC_OK_RESIDUAL=0xf0b8 class TestCRC(unittest.TestCase):
78
119
399
7
70
Tiboris/python-yubico
test/soft/test_yubico.py
Python
TestCRC
TestCRC
13
46
13
14
908bdaafbf121e3927c0c24a1190a38fb2b192b6
bigcode/the-stack
train
ddef1ebbace564ccf75f4420
train
class
class PublicPrivateNetworkConfig(BaseNetworkConfig): """The public private config that creates one public subnet for head node and one private subnet for compute.""" def __init__(self, availability_zones=None): super(PublicPrivateNetworkConfig, self).__init__( config_type="Head node in a pu...
class PublicPrivateNetworkConfig(BaseNetworkConfig):
"""The public private config that creates one public subnet for head node and one private subnet for compute.""" def __init__(self, availability_zones=None): super(PublicPrivateNetworkConfig, self).__init__( config_type="Head node in a public subnet and compute fleet in a private subnet", ...
_size): public_cidr = get_subnet_cidr( vpc_cidr=vpc_cidr, occupied_cidr=subnet_cidrs, min_subnet_size=compute_subnet_size + HEAD_NODE_SUBNET_IPS ) _validate_cidr(public_cidr) parameters = self.get_cfn_parameters(vpc_id, internet_gateway_id, public_cidr) stack_output =...
129
130
435
9
120
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
PublicPrivateNetworkConfig
PublicPrivateNetworkConfig
117
149
117
117
b11f36c8d60722992200c793d7af2d575a09d3a0
bigcode/the-stack
train
36e11a9c45b1c603c404da48
train
class
class PublicNetworkConfig(BaseNetworkConfig): """The public configuration that creates one public subnet with head node and compute fleet.""" def __init__(self, availability_zones=None): super(PublicNetworkConfig, self).__init__( config_type="Head node and compute fleet in the same public s...
class PublicNetworkConfig(BaseNetworkConfig):
"""The public configuration that creates one public subnet with head node and compute fleet.""" def __init__(self, availability_zones=None): super(PublicNetworkConfig, self).__init__( config_type="Head node and compute fleet in the same public subnet", template_name="public", ...
Config._build_cfn_param("InternetGatewayId", internet_gateway_id), BaseNetworkConfig._build_cfn_param("VpcId", vpc_id), ] def _get_availability_zone(self): if self.availability_zones: # To Do: is the first az in the azs list the optimal option? return self.availa...
92
93
311
8
84
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
PublicNetworkConfig
PublicNetworkConfig
90
114
90
90
5f696e221f2f925cefc2e67e2ffd9866d4fed312
bigcode/the-stack
train
ac8428d76055bbb417da7ff0
train
function
def _validate_vpc(vpc_id): # This function should be further expandend once we decide to allow the user to use his vpcs. For example, we should # also check for the presence of a NAT gateway if not VpcFactory(get_region()).check(vpc_id): logging.error("WARNING: The VPC does not have the correct para...
def _validate_vpc(vpc_id): # This function should be further expandend once we decide to allow the user to use his vpcs. For example, we should # also check for the presence of a NAT gateway
if not VpcFactory(get_region()).check(vpc_id): logging.error("WARNING: The VPC does not have the correct parameters set.")
) return network_configuration.create(vpc_id, compute_subnet_size) def _validate_vpc(vpc_id): # This function should be further expandend once we decide to allow the user to use his vpcs. For example, we should # also check for the presence of a NAT gateway
64
64
80
49
15
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
_validate_vpc
_validate_vpc
246
250
246
248
53fe8e730cc157b2cf6271692bad683554cd3249
bigcode/the-stack
train
a674fe35e4c99af8aca3dac8
train
function
def _create_network_stack(configuration, parameters): LOGGER.info("Creating CloudFormation stack...") LOGGER.info("Do not leave the terminal until the process has finished") stack_name = "parallelclusternetworking-{0}{1}".format(configuration.stack_name_prefix, TIMESTAMP) version = pkg_resources.get_dis...
def _create_network_stack(configuration, parameters):
LOGGER.info("Creating CloudFormation stack...") LOGGER.info("Do not leave the terminal until the process has finished") stack_name = "parallelclusternetworking-{0}{1}".format(configuration.stack_name_prefix, TIMESTAMP) version = pkg_resources.get_distribution("aws-parallelcluster").version try: ...
net_id": get_stack_output_value(stack_output, "PublicSubnetId"), "compute_subnet_id": get_stack_output_value(stack_output, "PrivateSubnetId"), "use_public_ips": "false", } class NetworkConfiguration(Enum): """Contain all possible network configuration.""" # py2.7 compatibility...
107
107
359
9
98
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
_create_network_stack
_create_network_stack
162
197
162
162
04d36adc10d277a38a912c1ebe5805df434d8805
bigcode/the-stack
train
70399e40834608102823a079
train
function
@handle_client_exception def _get_internet_gateway_id(vpc_id): response = boto3.client("ec2").describe_internet_gateways( Filters=[{"Name": "attachment.vpc-id", "Values": [vpc_id]}] ) return response["InternetGateways"][0]["InternetGatewayId"] if response["InternetGateways"] else ""
@handle_client_exception def _get_internet_gateway_id(vpc_id):
response = boto3.client("ec2").describe_internet_gateways( Filters=[{"Name": "attachment.vpc-id", "Values": [vpc_id]}] ) return response["InternetGateways"][0]["InternetGatewayId"] if response["InternetGateways"] else ""
] @handle_client_exception def _get_vpc_cidr(vpc_id): return boto3.client("ec2").describe_vpcs(VpcIds=[vpc_id])["Vpcs"][0]["CidrBlock"] @handle_client_exception def _get_internet_gateway_id(vpc_id):
63
64
78
16
47
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
_get_internet_gateway_id
_get_internet_gateway_id
218
223
218
219
ae787fc22852bbfb0370c2df410179c0d9ccf68f
bigcode/the-stack
train
0a3e0ad6e71133f13edb9248
train
function
@handle_client_exception def _get_vpc_cidr(vpc_id): return boto3.client("ec2").describe_vpcs(VpcIds=[vpc_id])["Vpcs"][0]["CidrBlock"]
@handle_client_exception def _get_vpc_cidr(vpc_id):
return boto3.client("ec2").describe_vpcs(VpcIds=[vpc_id])["Vpcs"][0]["CidrBlock"]
.client("ec2").describe_subnets(Filters=[{"Name": "vpcId", "Values": [vpc_id]}])["Subnets"] return [subnet["CidrBlock"] for subnet in subnets] @handle_client_exception def _get_vpc_cidr(vpc_id):
64
64
46
16
48
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
_get_vpc_cidr
_get_vpc_cidr
213
215
213
214
1af78f32f1614f02a719d0d8f7f393456bddffd0
bigcode/the-stack
train
5540c28c5c99132f68a88683
train
function
@handle_client_exception def get_vpc_subnets(vpc_id): """Return a list of the subnets cidr contained in the vpc.""" subnets = boto3.client("ec2").describe_subnets(Filters=[{"Name": "vpcId", "Values": [vpc_id]}])["Subnets"] return [subnet["CidrBlock"] for subnet in subnets]
@handle_client_exception def get_vpc_subnets(vpc_id):
"""Return a list of the subnets cidr contained in the vpc.""" subnets = boto3.client("ec2").describe_subnets(Filters=[{"Name": "vpcId", "Values": [vpc_id]}])["Subnets"] return [subnet["CidrBlock"] for subnet in subnets]
) sys.exit(1) def _validate_cidr(cidr): if not cidr: LOGGER.error("Unable to create subnet. Please check the number of available IPs in the VPC") sys.exit(1) @handle_client_exception def get_vpc_subnets(vpc_id):
64
64
86
15
49
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
get_vpc_subnets
get_vpc_subnets
206
210
206
207
bdfa6f4aefae23223a77c6de0e7ce0ea4239eb07
bigcode/the-stack
train
b1ea7b76468f6fc307d0b287
train
class
class NetworkConfiguration(Enum): """Contain all possible network configuration.""" # py2.7 compatibility, need to specify the order __order__ = "PUBLIC_PRIVATE PUBLIC" PUBLIC_PRIVATE = PublicPrivateNetworkConfig() PUBLIC = PublicNetworkConfig()
class NetworkConfiguration(Enum):
"""Contain all possible network configuration.""" # py2.7 compatibility, need to specify the order __order__ = "PUBLIC_PRIVATE PUBLIC" PUBLIC_PRIVATE = PublicPrivateNetworkConfig() PUBLIC = PublicNetworkConfig()
create_network_stack(self, parameters) return { "master_subnet_id": get_stack_output_value(stack_output, "PublicSubnetId"), "compute_subnet_id": get_stack_output_value(stack_output, "PrivateSubnetId"), "use_public_ips": "false", } class NetworkConfiguration(Enum):
64
64
53
5
59
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
NetworkConfiguration
NetworkConfiguration
152
159
152
152
01e1649ad3886fffeb5e381c6356bd20126a2466
bigcode/the-stack
train
5206df3c0ebd882b30fcb33a
train
function
@handle_client_exception def automate_subnet_creation(vpc_id, network_configuration, compute_subnet_size): _validate_vpc(vpc_id) return network_configuration.create(vpc_id, compute_subnet_size)
@handle_client_exception def automate_subnet_creation(vpc_id, network_configuration, compute_subnet_size):
_validate_vpc(vpc_id) return network_configuration.create(vpc_id, compute_subnet_size)
vpc_parameters = {"vpc_id": vpc_id} vpc_parameters.update(automate_subnet_creation(vpc_id, network_configuration, compute_subnet_size)) return vpc_parameters @handle_client_exception def automate_subnet_creation(vpc_id, network_configuration, compute_subnet_size):
64
64
45
22
41
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
automate_subnet_creation
automate_subnet_creation
240
243
240
241
e9c5e119c997d3ec60f032e5b2810f46154eb58f
bigcode/the-stack
train
834910d62d70cb3cab752ba9
train
class
class BaseNetworkConfig(ABC): """The abstract base configuration from which all configurations shall inherit.""" def __init__(self, config_type, template_name, stack_name_prefix, availability_zones): self.config_type = config_type self.template_name = template_name self.stack_name_prefi...
class BaseNetworkConfig(ABC):
"""The abstract base configuration from which all configurations shall inherit.""" def __init__(self, config_type, template_name, stack_name_prefix, availability_zones): self.config_type = config_type self.template_name = template_name self.stack_name_prefix = stack_name_prefix ...
cluster.utils import ( get_cli_log_file, get_region, get_stack, get_stack_output_value, get_templates_bucket_path, verify_stack_creation, ) DEFAULT_AWS_REGION_NAME = "us-east-1" LOGGER = logging.getLogger(__name__) TIMESTAMP = "-{:%Y%m%d%H%M%S}".format(datetime.datetime.utcnow()) HEAD_NODE_SUBN...
126
127
426
7
119
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
BaseNetworkConfig
BaseNetworkConfig
44
87
44
44
ffc43bc3fead7a680ed0f7d562057f2316afef7c
bigcode/the-stack
train
d32858215b3cb05a276217c8
train
function
def automate_vpc_with_subnet_creation(network_configuration, compute_subnet_size): print("Beginning VPC creation. Please do not leave the terminal until the creation is finalized") vpc_creator = VpcFactory(get_region()) vpc_id = vpc_creator.create() vpc_creator.setup(vpc_id, name="ParallelClusterVPC" + ...
def automate_vpc_with_subnet_creation(network_configuration, compute_subnet_size):
print("Beginning VPC creation. Please do not leave the terminal until the creation is finalized") vpc_creator = VpcFactory(get_region()) vpc_id = vpc_creator.create() vpc_creator.setup(vpc_id, name="ParallelClusterVPC" + TIMESTAMP) if not vpc_creator.check(vpc_id): logging.critical("Somethin...
( Filters=[{"Name": "attachment.vpc-id", "Values": [vpc_id]}] ) return response["InternetGateways"][0]["InternetGatewayId"] if response["InternetGateways"] else "" def automate_vpc_with_subnet_creation(network_configuration, compute_subnet_size):
63
64
159
16
47
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
automate_vpc_with_subnet_creation
automate_vpc_with_subnet_creation
226
237
226
226
aa46cab91986446d8815e782c5415fc95d358609
bigcode/the-stack
train
eac9881763c81bdebb88fc6c
train
function
def _validate_cidr(cidr): if not cidr: LOGGER.error("Unable to create subnet. Please check the number of available IPs in the VPC") sys.exit(1)
def _validate_cidr(cidr):
if not cidr: LOGGER.error("Unable to create subnet. Please check the number of available IPs in the VPC") sys.exit(1)
() LOGGER.error( "An exception occured while creating the CloudFormation stack: {0}. " "For details please check log file: {1}".format(stack_name, get_cli_log_file()) ) LOGGER.critical(e) sys.exit(1) def _validate_cidr(cidr):
64
64
42
8
56
rsips/cc_net
venv/lib/python3.7/site-packages/pcluster/configure/networking.py
Python
_validate_cidr
_validate_cidr
200
203
200
200
be02ebbf19a075cb8206b7be62ca9bf849458e1b
bigcode/the-stack
train
7e2b942ea988f34090e3b950
train
function
def getAnnotations(args, syn): annotations = syn.getAnnotations(args.id) if args.output is None or args.output == 'STDOUT': print(json.dumps(annotations, sort_keys=True, indent=2)) else: with open(args.output, 'w') as f: f.write(json.dumps(annotations)) f.write('\n')...
def getAnnotations(args, syn):
annotations = syn.getAnnotations(args.id) if args.output is None or args.output == 'STDOUT': print(json.dumps(annotations, sort_keys=True, indent=2)) else: with open(args.output, 'w') as f: f.write(json.dumps(annotations)) f.write('\n')
: annots = newannots else: annots = syn.getAnnotations(entity) annots.update(newannots) syn.setAnnotations(entity, annots) sys.stderr.write('Set annotations on entity %s\n' % (args.id,)) def getAnnotations(args, syn):
63
64
74
7
57
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
getAnnotations
getAnnotations
379
387
379
379
ba6b61154cede67844cfea95e8aa8685c1f12d1e
bigcode/the-stack
train
f7008b08fd21d54b26bb2986
train
function
def create(args, syn): _descriptionFile_arg_check(args) entity = {'name': args.name, 'parentId': args.parentid, 'concreteType': 'org.sagebionetworks.repo.model.%s' % args.type} entity = syn.createEntity(entity) _create_wiki_description_if_necessary(args, entity, syn) p...
def create(args, syn):
_descriptionFile_arg_check(args) entity = {'name': args.name, 'parentId': args.parentid, 'concreteType': 'org.sagebionetworks.repo.model.%s' % args.type} entity = syn.createEntity(entity) _create_wiki_description_if_necessary(args, entity, syn) print('Created entity: %...
syn): if args.version: syn.delete(args.id, args.version) print('Deleted entity %s, version %s' % (args.id, args.version)) else: syn.delete(args.id) print('Deleted entity: %s' % args.id) def create(args, syn):
64
64
100
6
58
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
create
create
288
298
288
288
ad3cfbd38ec2fade51487a056bdfbaf07504f7b1
bigcode/the-stack
train
1628fafe7cde48c6a2b65504
train
function
def perform_main(args, syn): if 'func' in args: try: args.func(args, syn) except Exception as ex: if args.debug: raise else: sys.stderr.write(utils._synapse_error_msg(ex))
def perform_main(args, syn):
if 'func' in args: try: args.func(args, syn) except Exception as ex: if args.debug: raise else: sys.stderr.write(utils._synapse_error_msg(ex))
apse') parser_login.set_defaults(func=login) # test character encoding parser_test_encoding = subparsers.add_parser('test-encoding', help='test character encoding to help diagnose problems') parser_test_encoding.set_defaults(func=test_encoding) retu...
64
64
54
7
56
kdaily/synapsePythonClient
synapseclient/__main__.py
Python
perform_main
perform_main
824
832
824
824
494ea4886e04c99c0bafe8ecdfbbbc2e2e40bbfa
bigcode/the-stack
train