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
b40c6e7072dc30615c377ebd
train
function
def test_add_contact_into_group(db, app): db.check_available_parameters(app) old_data = db.get_data_address_in_groups() # список контактов в группах selected_data = db.get_selected_groups_and_contacts() final_group = selected_data[0] selected_contact = selected_data[1] app.contact.add_contac...
def test_add_contact_into_group(db, app):
db.check_available_parameters(app) old_data = db.get_data_address_in_groups() # список контактов в группах selected_data = db.get_selected_groups_and_contacts() final_group = selected_data[0] selected_contact = selected_data[1] app.contact.add_contact_into_group(selected_contact, final_group)...
import random def test_add_contact_into_group(db, app):
13
64
114
10
2
seredyan/AddressBook
test/test_contacts_in_groups.py
Python
test_add_contact_into_group
test_add_contact_into_group
3
17
3
4
bb1ab6c4f24dcceb2e3fb5f3c0d92005f8063421
bigcode/the-stack
train
26717befb1bc6f1ce14e331c
train
class
class Hlayer0rule6(Himesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule layer0rule6. """ # Flag this instance as compiled now self.is_compiled = True super(Hlayer0rule6, self).__init__(name='Hlayer0rule6', num_nodes=0, edges=[]) # Set the graph attributes self["m...
class Hlayer0rule6(Himesis):
def __init__(self): """ Creates the himesis graph representing the DSLTrans rule layer0rule6. """ # Flag this instance as compiled now self.is_compiled = True super(Hlayer0rule6, self).__init__(name='Hlayer0rule6', num_nodes=0, edges=[]) # Set the graph attributes self["mm__"] = ['HimesisMM'] self[...
from core.himesis import Himesis import uuid class Hlayer0rule6(Himesis):
23
256
854
10
12
levilucio/SyVOLT
mbeddr2C_MM/transformation_from_mps/Hlayer0rule6.py
Python
Hlayer0rule6
Hlayer0rule6
4
76
4
4
f4873c6be02ce399b13e6fb42abab02d32333144
bigcode/the-stack
train
07aaadb151c00bfc13ba5392
train
class
class AppsV1beta1RollingUpdateDeployment(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value ...
class AppsV1beta1RollingUpdateDeployment(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.17 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import si...
101
256
1,554
11
89
carloscastrojumo/python
kubernetes/client/models/apps_v1beta1_rolling_update_deployment.py
Python
AppsV1beta1RollingUpdateDeployment
AppsV1beta1RollingUpdateDeployment
21
150
21
21
7c86c785b62fa1b6e685507d47f9afe0891d2b9d
bigcode/the-stack
train
cd8f36606a8e91cebc5a705e
train
class
class WebsiteScript(Document): def on_update(self): """clear cache""" frappe.clear_cache(user="Guest") from frappe.website.render import clear_cache clear_cache()
class WebsiteScript(Document):
def on_update(self): """clear cache""" frappe.clear_cache(user="Guest") from frappe.website.render import clear_cache clear_cache()
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class WebsiteScript(Document):
61
64
38
5
55
erpnext-tm/frappe
frappe/website/doctype/website_script/website_script.py
Python
WebsiteScript
WebsiteScript
12
19
12
12
aa10a47a39aee705c51b4acd758c649f7ef70fa8
bigcode/the-stack
train
0dfa173164d70fd37961a042
train
class
class _TzStrFactory(_TzFactory): def __init__(cls, *args, **kwargs): cls.__instances = {} def __call__(cls, s, posix_offset=False): key = (s, posix_offset) instance = cls.__instances.get(key, None) if instance is None: instance = cls.__instances.setdefault(key, ...
class _TzStrFactory(_TzFactory):
def __init__(cls, *args, **kwargs): cls.__instances = {} def __call__(cls, s, posix_offset=False): key = (s, posix_offset) instance = cls.__instances.get(key, None) if instance is None: instance = cls.__instances.setdefault(key, cls.instance(s, posix...
, offset.total_seconds()) else: key = (name, offset) instance = cls.__instances.get(key, None) if instance is None: instance = cls.__instances.setdefault(key, cls.instance(name, offset)) return instance class _TzS...
64
64
93
11
52
anthowen/duplify
env/lib/python3.6/site-packages/dateutil/tz/_factories.py
Python
_TzStrFactory
_TzStrFactory
37
48
37
37
f75d1858238db51023aea05e49e8b28088f43aee
bigcode/the-stack
train
f04872935149555d12bbffd8
train
class
class _TzFactory(type): def instance(cls, *args, **kwargs): """Alternate constructor that returns a fresh instance""" return type.__call__(cls, *args, **kwargs)
class _TzFactory(type):
def instance(cls, *args, **kwargs): """Alternate constructor that returns a fresh instance""" return type.__call__(cls, *args, **kwargs)
.__instance = None super(_TzSingleton, cls).__init__(*args, **kwargs) def __call__(cls): if cls.__instance is None: cls.__instance = super(_TzSingleton, cls).__call__() return cls.__instance class _TzFactory(type):
64
64
42
7
56
anthowen/duplify
env/lib/python3.6/site-packages/dateutil/tz/_factories.py
Python
_TzFactory
_TzFactory
14
17
14
14
f2647eb39a48a3162d8ae9904d6f0d91ceb92be0
bigcode/the-stack
train
a6cbaeb21928d45cc7a44d1a
train
class
class _TzOffsetFactory(_TzFactory): def __init__(cls, *args, **kwargs): cls.__instances = {} def __call__(cls, name, offset): if isinstance(offset, timedelta): key = (name, offset.total_seconds()) else: key = (name, offset) instance = cls.__instances.get...
class _TzOffsetFactory(_TzFactory):
def __init__(cls, *args, **kwargs): cls.__instances = {} def __call__(cls, name, offset): if isinstance(offset, timedelta): key = (name, offset.total_seconds()) else: key = (name, offset) instance = cls.__instances.get(key, None) if instance is N...
, cls).__call__() return cls.__instance class _TzFactory(type): def instance(cls, *args, **kwargs): """Alternate constructor that returns a fresh instance""" return type.__call__(cls, *args, **kwargs) class _TzOffsetFactory(_TzFactory):
64
64
106
11
53
anthowen/duplify
env/lib/python3.6/site-packages/dateutil/tz/_factories.py
Python
_TzOffsetFactory
_TzOffsetFactory
20
34
20
20
f97f19715802871b31d6a4369711b6d23373d371
bigcode/the-stack
train
17c70014239a7cd339849164
train
class
class _TzSingleton(type): def __init__(cls, *args, **kwargs): cls.__instance = None super(_TzSingleton, cls).__init__(*args, **kwargs) def __call__(cls): if cls.__instance is None: cls.__instance = super(_TzSingleton, cls).__call__() return cls.__instance
class _TzSingleton(type):
def __init__(cls, *args, **kwargs): cls.__instance = None super(_TzSingleton, cls).__init__(*args, **kwargs) def __call__(cls): if cls.__instance is None: cls.__instance = super(_TzSingleton, cls).__call__() return cls.__instance
from datetime import timedelta class _TzSingleton(type):
12
64
79
7
4
anthowen/duplify
env/lib/python3.6/site-packages/dateutil/tz/_factories.py
Python
_TzSingleton
_TzSingleton
4
12
4
4
44e83c362e2ccc5830ab23288ddfe69fb2071995
bigcode/the-stack
train
fd9604ecf4fc98a979d01327
train
function
def set_box_color(bp, color): plt.setp(bp['boxes'], color=color) plt.setp(bp['whiskers'], color=color) plt.setp(bp['caps'], color=color) plt.setp(bp['medians'], color=color)
def set_box_color(bp, color):
plt.setp(bp['boxes'], color=color) plt.setp(bp['whiskers'], color=color) plt.setp(bp['caps'], color=color) plt.setp(bp['medians'], color=color)
# -*- coding: utf-8 -*- """ Created on Tue May 1 19:35:08 2018 @author: fnord """ import pandas as pd import numpy as np import matplotlib.pyplot as plt def set_box_color(bp, color):
56
64
55
8
47
lauromoraes/CapsNet-promoter
teste_plot2.py
Python
set_box_color
set_box_color
12
16
12
12
28b800eba8807f2a746821bde2f4955b13a3cff2
bigcode/the-stack
train
bd1cbd72dbedc492e149e710
train
class
class Thermal: def __init__(self, fname): with open(fname, "r") as f: config = yaml.load(f)['main'] self.logger = self._setup_logger(config) self.gdrive = GDriveFactory.create(config, fname) self.remo = RemoFactory.create(config, fname) self.interval = config['in...
class Thermal:
def __init__(self, fname): with open(fname, "r") as f: config = yaml.load(f)['main'] self.logger = self._setup_logger(config) self.gdrive = GDriveFactory.create(config, fname) self.remo = RemoFactory.create(config, fname) self.interval = config['interval'] ...
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 included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXP...
256
256
1,096
3
253
t10471/raspi-thermal-py
main.py
Python
Thermal
Thermal
45
155
45
46
2e72c2887b65038d30dac3a1edc358af661b7516
bigcode/the-stack
train
3261bba1cc278b88807f161d
train
function
def find_secure_image(notify, resources, ns_image_path, configured_s_image_filename, image_type): """ Find secure image. """ assert ns_image_path and configured_s_image_filename, 'ns_image_path and configured_s_image_path are mandatory' assert image_type in [FileType.BIN, FileType.HEX], 'image_type must be...
def find_secure_image(notify, resources, ns_image_path, configured_s_image_filename, image_type):
""" Find secure image. """ assert ns_image_path and configured_s_image_filename, 'ns_image_path and configured_s_image_path are mandatory' assert image_type in [FileType.BIN, FileType.HEX], 'image_type must be of type BIN or HEX' image_files = resources.get_file_paths(image_type) assert image_file...
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. from os.path import basename, splitext from tools.resources import FileType def find_secure_image(notify, resources, ns_image_path, configured...
68
68
229
21
46
ntoni92/mbed-os
tools/psa/__init__.py
Python
find_secure_image
find_secure_image
22
43
22
22
3d090319d412a73f9f6c275ac00d5e8521e0ae96
bigcode/the-stack
train
aed2f13d5d612f31eaff8464
train
class
class SepPhotometry(Photometry): """Perform photometry using SEP.""" __module__ = 'pyobs.images.processors.photometry' def __init__(self, threshold: float = 1.5, minarea: int = 5, deblend_nthresh: int = 32, deblend_cont: float = 0.005, clean: bool = True, clean_param: float = 1.0, *args, *...
class SepPhotometry(Photometry):
"""Perform photometry using SEP.""" __module__ = 'pyobs.images.processors.photometry' def __init__(self, threshold: float = 1.5, minarea: int = 5, deblend_nthresh: int = 32, deblend_cont: float = 0.005, clean: bool = True, clean_param: float = 1.0, *args, **kwargs): """Initializes ...
from astropy.table import Table import logging import numpy as np from .photometry import Photometry from pyobs.images import Image log = logging.getLogger(__name__) class SepPhotometry(Photometry):
46
256
1,308
8
38
pyobs/pyobs-core
pyobs/images/processors/photometry/sep.py
Python
SepPhotometry
SepPhotometry
11
131
11
11
bf6ff67897298e80f9600f75081bf356d5f2ce87
bigcode/the-stack
train
00753137ed8d37410d3214cc
train
function
def runtests(*test_args): from django.test.runner import DiscoverRunner parent = dirname(abspath(__file__)) sys.path.insert(0, parent) test_runner = DiscoverRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(test_args) sys.exit(failures)
def runtests(*test_args):
from django.test.runner import DiscoverRunner parent = dirname(abspath(__file__)) sys.path.insert(0, parent) test_runner = DiscoverRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(test_args) sys.exit(failures)
django.template.context_processors.request', ], }, }], 'DEFAULT_AUTO_FIELD': 'django.db.models.AutoField', 'SECRET_KEY': 'arandomstring', 'LINKCHECK_CONNECTION_ATTEMPT_TIMEOUT': 1, } settings.configure(**test_settings) def runtests(*test_args):
64
64
65
7
57
melegiul/django-linkcheck
runtests.py
Python
runtests
runtests
48
55
48
48
3ee86aaec0ef9a85bf2869ce8cca477d072b00c8
bigcode/the-stack
train
bab80fc6c76fde9202550c6d
train
class
class MetricRecords(object): """ Records of a single metric across different executions. """ def __init__(self, direction="min"): if direction not in {"min", "max"}: raise ValueError( "direction should be one of {min, max}, but got: {}.".format( d...
class MetricRecords(object):
""" Records of a single metric across different executions. """ def __init__(self, direction="min"): if direction not in {"min", "max"}: raise ValueError( "direction should be one of {min, max}, but got: {}.".format( direction)) self._dire...
= value @property def step(self): return self._step @step.setter def step(self, step): self._step = step def mean(self): return np.mean(self.value) def get_state(self): return {"value": self.value, "step": self.step} @classmethod def from_state(cls, ...
153
153
511
5
148
L-Net-1992/Paddle
python/paddle/distributed/auto_parallel/tuner/recorder.py
Python
MetricRecords
MetricRecords
65
141
65
65
9980321b0f1e1022411858469279da9a5d2b61fd
bigcode/the-stack
train
b43244d4a16c1266d6d4fe81
train
class
class MetricRecord(object): """ One record for a single metric at a given execution step. """ def __init__(self, value, step): self._value = value self._step = step @property def value(self): return self._value @value.setter def value(self, value): self...
class MetricRecord(object):
""" One record for a single metric at a given execution step. """ def __init__(self, value, step): self._value = value self._step = step @property def value(self): return self._value @value.setter def value(self, value): self._value = value @proper...
language governing permissions and # limitations under the License. # Notice that the following codes are modified from KerasTuner for a different purpose. # Please refer to https://github.com/keras-team/keras-tuner/blob/master/keras_tuner/engine/metrics_tracking.py. import numpy as np class MetricRecord(object):
67
67
226
5
61
L-Net-1992/Paddle
python/paddle/distributed/auto_parallel/tuner/recorder.py
Python
MetricRecord
MetricRecord
21
62
21
21
53045e4012e9f71e17d78920a664d4585ecc9b75
bigcode/the-stack
train
a6cad4a5df493b3f1811c851
train
class
class MetricsRecorder(object): """ Record the values for all metrics. """ def __init__(self, metrics=None): self._records = {} self.register_metrics(metrics) @property def records(self): return self._records def exists(self, name): return name in self._reco...
class MetricsRecorder(object):
""" Record the values for all metrics. """ def __init__(self, metrics=None): self._records = {} self.register_metrics(metrics) @property def records(self): return self._records def exists(self, name): return name in self._records def register_metrics(s...
mean(records_values)), "median": float(np.nanmedian(records_values)), "var": float(np.nanvar(records_values)), "std": float(np.nanstd(records_values)), } def get_state(self): state = {} state["direction"] = self._direction state["records"] = [r.ge...
128
128
429
5
122
L-Net-1992/Paddle
python/paddle/distributed/auto_parallel/tuner/recorder.py
Python
MetricsRecorder
MetricsRecorder
144
216
144
144
73a9eb5de8f558809b58f5c6b352703f17688413
bigcode/the-stack
train
af31ef2ea57cf620fe8d69d5
train
class
class Command(BaseCommand): def handle(self, *args, **options): # Print tasks that are due on the next 3 days tasks = Task.objects.filter(completed=False, notified_due_date=False) for task in tasks: if task.due_date is None: continue notification_due...
class Command(BaseCommand):
def handle(self, *args, **options): # Print tasks that are due on the next 3 days tasks = Task.objects.filter(completed=False, notified_due_date=False) for task in tasks: if task.due_date is None: continue notification_due_date = task.due_date - datet...
django.core.management.base import BaseCommand, CommandError from django.contrib.sites.models import Site from django.template.loader import render_to_string from django.utils import timezone from django.core.mail import send_mail import datetime from todo.models import Editor, Book, UserInfo, Task class Command(BaseC...
64
64
183
5
58
josalhor/WebModels
todo/management/commands/mail_notifier.py
Python
Command
Command
10
38
10
11
42569159dfe6a5341c686ef32ed25612fde7da4d
bigcode/the-stack
train
e79cbbc195f6fd1da7fb8663
train
function
def get_logger(name=__name__): logger = getLogger(name) logging.basicConfig(format=FORMAT) handler = StreamHandler() logger.setLevel(LOG_LEVEL) logger.addHandler(handler) logger.propagate = False return logger
def get_logger(name=__name__):
logger = getLogger(name) logging.basicConfig(format=FORMAT) handler = StreamHandler() logger.setLevel(LOG_LEVEL) logger.addHandler(handler) logger.propagate = False return logger
permissions and # limitations under the License. import os import logging from logging import getLogger, StreamHandler FORMAT = '%(asctime)-15s Experiment %(experiment_name)s %(message)s' LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO") def get_logger(name=__name__):
64
64
55
9
55
oneconvergence/katib
pkg/suggestion/v1beta1/bayesianoptimization/utils.py
Python
get_logger
get_logger
24
31
24
24
24697872db1d34bc843afb39d0290c1e0f8d5688
bigcode/the-stack
train
648ee30d83a675eba38a60eb
train
function
def set_open_files_limit(): """Detect maximum supported number of open file and set it""" max_files = getrlimit(RLIMIT_NOFILE)[0] while True: try: setrlimit(RLIMIT_NOFILE, (max_files, max_files)) max_files += 1 except ValueError: break LOG.debug("Setti...
def set_open_files_limit():
"""Detect maximum supported number of open file and set it""" max_files = getrlimit(RLIMIT_NOFILE)[0] while True: try: setrlimit(RLIMIT_NOFILE, (max_files, max_files)) max_files += 1 except ValueError: break LOG.debug("Setting max files limit to %d", m...
binlogs.append(binlog) return binlogs[:-1] except InternalError as err: if err.args and err.args[0] == 1381: # ER_NO_BINARY_LOGGING return binlogs else: raise OperationError(err) def set_open_files_limit():
64
64
86
6
58
RyanCPeters/backup
twindb_backup/backup.py
Python
set_open_files_limit
set_open_files_limit
290
299
290
290
3365717ba149f4cc80b4b5729a6014fccee96859
bigcode/the-stack
train
14df7770445bc8b6dd8656d8
train
function
def backup_files(run_type, config): """Backup local directories :param run_type: Run type :type run_type: str :param config: Configuration :type config: TwinDBBackupConfig """ backup_start = time.time() try: for directory in config.backup_dirs: LOG.debug("copying %s"...
def backup_files(run_type, config):
"""Backup local directories :param run_type: Run type :type run_type: str :param config: Configuration :type config: TwinDBBackupConfig """ backup_start = time.time() try: for directory in config.backup_dirs: LOG.debug("copying %s", directory) src = FileS...
modifier if config.gpg: gpg_modifier = Gpg(stream, config.gpg.recipient, config.gpg.keyring) stream = gpg_modifier.get_stream() src.suffix += ".gpg" dst.save(stream, src.get_name()) def backup_files(run_type, config):
64
64
177
8
56
RyanCPeters/backup
twindb_backup/backup.py
Python
backup_files
backup_files
96
119
96
96
5e8a804bcc85e0bff827269f80f3706ae08a1a99
bigcode/the-stack
train
505b9ade0efc381356f2c24d
train
function
def backup_binlogs(run_type, config): # pylint: disable=too-many-locals """Copy MySQL binlog files to the backup destination. :param run_type: Run type :type run_type: str :param config: Tool configuration :type config: TwinDBBackupConfig """ if config.mysql is None: LOG.debug("No ...
def backup_binlogs(run_type, config): # pylint: disable=too-many-locals
"""Copy MySQL binlog files to the backup destination. :param run_type: Run type :type run_type: str :param config: Tool configuration :type config: TwinDBBackupConfig """ if config.mysql is None: LOG.debug("No MySQL config, not copying binlogs") return dst = config.dest...
, **kwargs) status.add(backup_copy) status = src.apply_retention_policy(dst, config, run_type, status) LOG.debug("status after apply_retention_policy():\n%s", status) backup_duration = backup_copy.duration export_info( config, data=backup_duration, category=ExportCategory.m...
139
139
465
21
118
RyanCPeters/backup
twindb_backup/backup.py
Python
backup_binlogs
backup_binlogs
199
259
199
199
e5f96628bf52e0c1ec57ea13c07a00c78033c83b
bigcode/the-stack
train
6f597d39fff61cd1868c84fe
train
function
def binlogs_to_backup(cursor, last_binlog=None): """ Finds list of binlogs to copy. It will return the binlogs from the last to the current one (excluding it). If binlog are not enabled in the server the function will return empty list. :param cursor: MySQL cursor :param last_binlog: Name o...
def binlogs_to_backup(cursor, last_binlog=None):
""" Finds list of binlogs to copy. It will return the binlogs from the last to the current one (excluding it). If binlog are not enabled in the server the function will return empty list. :param cursor: MySQL cursor :param last_binlog: Name of the last copied binlog. :return: list of bi...
24 * 3600: LOG.debug( "Deleting copy that was taken %d seconds ago", now - copy.created_at, ) dst.delete(copy.key + ".gz") status.remove(copy.key) status.save(dst) def binlogs_to_backup(cursor, last_binlog=None):
64
64
210
12
52
RyanCPeters/backup
twindb_backup/backup.py
Python
binlogs_to_backup
binlogs_to_backup
262
287
262
262
90d05a0538f41a79747d1ed5028be3cbab586368
bigcode/the-stack
train
9b982db5b4d052a2dbb967f0
train
function
def run_backup_job( twindb_config, run_type, lock_file=LOCK_FILE, binlogs_only=False ): """ Grab a lock waiting up to allowed timeout and start backup jobs :param twindb_config: Tool configuration :type twindb_config: TwinDBBackupConfig :param run_type: Run type: [ hourly | daily | weekly | mon...
def run_backup_job( twindb_config, run_type, lock_file=LOCK_FILE, binlogs_only=False ):
""" Grab a lock waiting up to allowed timeout and start backup jobs :param twindb_config: Tool configuration :type twindb_config: TwinDBBackupConfig :param run_type: Run type: [ hourly | daily | weekly | monthly | yearly ] :type run_type: str :param lock_file: File used as a lock :type ...
"""Function to call on a timeout event""" if signum or frame: pass original_handler = signal.signal(signal.SIGALRM, timeout_handler) try: signal.alarm(seconds) yield finally: signal.alarm(0) signal.signal(signal.SIGALRM, original_handler) def run_backup...
94
94
314
26
68
RyanCPeters/backup
twindb_backup/backup.py
Python
run_backup_job
run_backup_job
355
389
355
357
760efdfabb41fef012246473c6dabbc14a68cd94
bigcode/the-stack
train
7e91df0fe4d638e95c142432
train
function
def backup_mysql(run_type:str, config:TwinDBBackupConfig): """Take backup of local MySQL instance :param run_type: Run type :type run_type: str :param config: Tool configuration :type config: TwinDBBackupConfig """ if config.backup_mysql is False: LOG.debug("Not backing up MySQL") ...
def backup_mysql(run_type:str, config:TwinDBBackupConfig):
"""Take backup of local MySQL instance :param run_type: Run type :type run_type: str :param config: Tool configuration :type config: TwinDBBackupConfig """ if config.backup_mysql is False: LOG.debug("Not backing up MySQL") return dst: BaseDestination = config.destinatio...
:param config: Configuration :type config: TwinDBBackupConfig """ backup_start = time.time() try: for directory in config.backup_dirs: LOG.debug("copying %s", directory) src = FileSource(directory, run_type) dst = config.destination() _backup_stre...
159
159
533
14
145
RyanCPeters/backup
twindb_backup/backup.py
Python
backup_mysql
backup_mysql
122
196
122
122
bd52eda1386278c0a7430377fc5eaf407f65ba7e
bigcode/the-stack
train
673d02162c1c3acfda6b6a13
train
function
@contextmanager def timeout(seconds): """ Implement timeout :param seconds: timeout in seconds :type seconds: int """ def timeout_handler(signum, frame): """Function to call on a timeout event""" if signum or frame: pass original_handler = signal.signal(signal....
@contextmanager def timeout(seconds):
""" Implement timeout :param seconds: timeout in seconds :type seconds: int """ def timeout_handler(signum, frame): """Function to call on a timeout event""" if signum or frame: pass original_handler = signal.signal(signal.SIGALRM, timeout_handler) try: ...
time.time() save_measures(backup_start, end) else: backup_binlogs(run_type, twindb_config) except configparser.NoSectionError as err: LOG.debug(traceback.format_exc()) LOG.error(err) exit(1) @contextmanager def timeout(seconds):
64
64
110
8
56
RyanCPeters/backup
twindb_backup/backup.py
Python
timeout
timeout
331
352
331
332
af2832d671eda04bb3ad10d2e9fd70018467f572
bigcode/the-stack
train
e340bf5b543ac5adad30eeaf
train
function
def backup_everything(run_type, twindb_config, binlogs_only=False): """ Run backup job :param run_type: hourly, daily, etc :type run_type: str :param twindb_config: ConfigParser instance :type twindb_config: TwinDBBackupConfig :param binlogs_only: If True copy only MySQL binary logs. :t...
def backup_everything(run_type, twindb_config, binlogs_only=False):
""" Run backup job :param run_type: hourly, daily, etc :type run_type: str :param twindb_config: ConfigParser instance :type twindb_config: TwinDBBackupConfig :param binlogs_only: If True copy only MySQL binary logs. :type binlogs_only: bool """ set_open_files_limit() try: ...
: setrlimit(RLIMIT_NOFILE, (max_files, max_files)) max_files += 1 except ValueError: break LOG.debug("Setting max files limit to %d", max_files) def backup_everything(run_type, twindb_config, binlogs_only=False):
64
64
212
17
47
RyanCPeters/backup
twindb_backup/backup.py
Python
backup_everything
backup_everything
302
328
302
302
9911ccb6c1ebe56e9117deb2b67938555e7e00b6
bigcode/the-stack
train
f2ccee629743f7cd086fdb9b
train
function
def _backup_stream(config:TwinDBBackupConfig, src:BaseSource, dst:BaseDestination, callbacks=None): """ :param config: Tool config :type config: TwinDBBackupConfig :param src: :param dst: :param callbacks: :return: """ # stream is a pointer to a context manager function stream =...
def _backup_stream(config:TwinDBBackupConfig, src:BaseSource, dst:BaseDestination, callbacks=None):
""" :param config: Tool config :type config: TwinDBBackupConfig :param src: :param dst: :param callbacks: :return: """ # stream is a pointer to a context manager function stream = src.get_stream() # Compression modifier cmp_modifier = config.compression.get_modifier(stre...
indb_backup.util import my_cnfs from twindb_backup.configuration import TwinDBBackupConfig from twindb_backup.source.base_source import BaseSource from twindb_backup.destination.base_destination import BaseDestination from twindb_backup import get_basic_logger#LOG LOG = get_basic_logger(__file__) def _backup_stream(c...
89
89
297
24
65
RyanCPeters/backup
twindb_backup/backup.py
Python
_backup_stream
_backup_stream
56
93
56
56
4fb87908a5c87a78458da3da456dfb590c804d5e
bigcode/the-stack
train
3f2dc542e1733ef71316519b
train
class
class BaseTrainer: """ ``BaseTrainer`` takes charge of training. ``storage`` holds all the intermediate variables such as ``data``, ``embeddings``, etc. All other modules, such as ``collectors``, ``selectors``, etc, access thier own parameter list to get the corresponding parameters. ``loss_handler`` ...
class BaseTrainer:
""" ``BaseTrainer`` takes charge of training. ``storage`` holds all the intermediate variables such as ``data``, ``embeddings``, etc. All other modules, such as ``collectors``, ``selectors``, etc, access thier own parameter list to get the corresponding parameters. ``loss_handler`` will compute weight...
import torch import torch.distributed as dist from torchdistlog import logging from torchdistlog.tqdm import tqdm from torch.utils.data import DataLoader from ..misc import utils, Storage from .loss_handler import LossHandler from ...config.setting.recorder_setting import ( TO_RECORD_LIST, TO_SAVE_LIST ) class...
75
256
2,368
4
71
zbr17/GeDML
src/gedml/launcher/trainers/base_trainer.py
Python
BaseTrainer
BaseTrainer
14
368
14
14
1fe8174daa27021ccf6d351b23be87d48a4fc489
bigcode/the-stack
train
d92f69b5add697e8d6f9aa5d
train
function
def init_model(problem, instance_name, image_size, nb_labels, dropout, network): """Initialize a convolutional neural network with Keras API starting from a set of parameters Parameters ---------- problem : str Type of solved problem, either `feature_detection` or `semantic_segmentation` in...
def init_model(problem, instance_name, image_size, nb_labels, dropout, network):
"""Initialize a convolutional neural network with Keras API starting from a set of parameters Parameters ---------- problem : str Type of solved problem, either `feature_detection` or `semantic_segmentation` instance_name : str Name of the instance, for identification purpose im...
', default=None, help=("Neural network size, either 'simple', 'vgg' or " "'inception' ('simple' refers to 3 conv/pool " "blocks and 1 fully-connected layer; the others " "refer to st...
85
85
284
18
66
shadofren/deeposlandia
deeposlandia/inference.py
Python
init_model
init_model
116
156
116
116
56342f6f691e4ba9f618ef657d986a844c1d563f
bigcode/the-stack
train
5fba1ac8b4f3fced05f5f3eb
train
function
def add_instance_arguments(parser): """Add instance-specific arguments from the command line Parameters ---------- parser : argparse.ArgumentParser Input parser Returns ------- argparse.ArgumentParser Modified parser, with additional arguments """ parser.add_argumen...
def add_instance_arguments(parser):
"""Add instance-specific arguments from the command line Parameters ---------- parser : argparse.ArgumentParser Input parser Returns ------- argparse.ArgumentParser Modified parser, with additional arguments """ parser.add_argument('-a', '--aggregate-label', action=...
=True, nargs='+', help="Path of the image on the file system") parser.add_argument('-M', '--model', default="feature_detection", help=("Type of model to train, either " "'feature_detection' ...
93
93
313
6
86
shadofren/deeposlandia
deeposlandia/inference.py
Python
add_instance_arguments
add_instance_arguments
72
114
72
72
966213af903c3689750b16526c46f76e89c89c49
bigcode/the-stack
train
8086b7241ebefd8bf11f2abb
train
function
def predict(filenames, dataset, problem, datapath="./data", aggregate=False, name=None, network=None, batch_size=None, dropout=None, learning_rate=None, learning_rate_decay=None, output_dir="/tmp/deeposlandia/predicted"): """Make label prediction on image indicated by ̀filename`,...
def predict(filenames, dataset, problem, datapath="./data", aggregate=False, name=None, network=None, batch_size=None, dropout=None, learning_rate=None, learning_rate_decay=None, output_dir="/tmp/deeposlandia/predicted"):
"""Make label prediction on image indicated by ̀filename`, according to considered `problem` Parameters ---------- filenames : str Name of the image files on the file system dataset : str Name of the dataset problem : str Name of the considered model, either `feature...
: int Image size, in pixels (height=width) nb_labels : int Number of output labels dropout : float Dropout rate network : str Network architecture Returns ------- keras.models.Model Convolutional neural network """ K.clear_session() if proble...
256
256
1,391
55
201
shadofren/deeposlandia
deeposlandia/inference.py
Python
predict
predict
158
309
158
161
75c1889b40158ef254ded35fa11818c94fa1b336
bigcode/the-stack
train
4db14804bb00eb1a76b56c07
train
function
def summarize_config(config): """Extract and reshape dataset configuration information in a HTML-printing context Parameters ---------- config : dict Dataset label configuration Returns ------- dict Simplified dataset configuration for HTML-printing purpose """ ...
def summarize_config(config):
"""Extract and reshape dataset configuration information in a HTML-printing context Parameters ---------- config : dict Dataset label configuration Returns ------- dict Simplified dataset configuration for HTML-printing purpose """ return [(c['category'], utils....
filename] = os.path.basename(filename) return {'labels': summarize_config(meaningful_labels), 'label_images': result} else: logger.error(("Unknown model argument. Please use " "'feature_detection' or 'semantic_segmentation'.")) sys.exit(1) def summarize_...
64
64
78
5
59
shadofren/deeposlandia
deeposlandia/inference.py
Python
summarize_config
summarize_config
311
325
311
311
2260a869d3a603882fa1c3795093ce9d352fcdde
bigcode/the-stack
train
0446b4d1739f80f9af2bf8b4
train
function
def extract_images(image_paths): """Convert a list of image filenames into a numpy array that contains the image data Parameters ---------- image_paths : str Name of the image files onto the file system Returns ------- np.array Data that is contained into the image ...
def extract_images(image_paths):
"""Convert a list of image filenames into a numpy array that contains the image data Parameters ---------- image_paths : str Name of the image files onto the file system Returns ------- np.array Data that is contained into the image """ x_test = [] for image...
context Parameters ---------- config : dict Dataset label configuration Returns ------- dict Simplified dataset configuration for HTML-printing purpose """ return [(c['category'], utils.GetHTMLColor(c['color'])) for c in config] def extract_images(image_paths):
64
64
142
6
58
shadofren/deeposlandia
deeposlandia/inference.py
Python
extract_images
extract_images
327
349
327
327
e76c11bf0e208a7b6aeb1c9610da5f1a8d28910a
bigcode/the-stack
train
2ffc7e3519504db669b78797
train
function
def add_program_arguments(parser): """Add instance-specific arguments from the command line Parameters ---------- parser : argparse.ArgumentParser Input parser Returns ------- argparse.ArgumentParser Modified parser, with additional arguments """ parser.add_argument...
def add_program_arguments(parser):
"""Add instance-specific arguments from the command line Parameters ---------- parser : argparse.ArgumentParser Input parser Returns ------- argparse.ArgumentParser Modified parser, with additional arguments """ parser.add_argument('-D', '--dataset', ...
as K from deeposlandia import utils from deeposlandia.datasets import AVAILABLE_DATASETS from deeposlandia.feature_detection import FeatureDetectionNetwork from deeposlandia.semantic_segmentation import SemanticSegmentationNetwork logger = daiquiri.getLogger(__name__) def add_program_arguments(parser):
64
64
191
6
58
shadofren/deeposlandia
deeposlandia/inference.py
Python
add_program_arguments
add_program_arguments
42
70
42
42
370b478c749e0186ec162f15f83b8bb6e1ed339c
bigcode/the-stack
train
994a0a4ea25e663ed1f0ed8d
train
class
class account_statement_from_invoice_lines(osv.osv_memory): """ Generate Entries by Statement from Invoices """ _name = "account.statement.from.invoice.lines" _description = "Entries by Statement from Invoices" _columns = { 'line_ids': fields.many2many('account.move.line', 'account_move_...
class account_statement_from_invoice_lines(osv.osv_memory):
""" Generate Entries by Statement from Invoices """ _name = "account.statement.from.invoice.lines" _description = "Entries by Statement from Invoices" _columns = { 'line_ids': fields.many2many('account.move.line', 'account_move_line_relation', 'move_id', 'line_id', 'Invoices'), } ...
the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTA...
158
158
528
12
145
diogocs1/comps
web/addons/account/wizard/account_statement_from_invoice.py
Python
account_statement_from_invoice_lines
account_statement_from_invoice_lines
26
83
26
26
b85a21013aa145a58e254512b59daf36d60aacc1
bigcode/the-stack
train
6af1b37327501e1139f26ed4
train
class
class ModelCheckpoint(keras.callbacks.Callback): def __init__(self): self.loss = 1e6 """自动保存最新模型 """ def on_epoch_end(self, epoch, logs=None): if logs['loss'] < self.loss: self.loss = logs['loss'] bert.save_weights_as_checkpoint(model_saved_path) test_d...
class ModelCheckpoint(keras.callbacks.Callback):
def __init__(self): self.loss = 1e6 """自动保存最新模型 """ def on_epoch_end(self, epoch, logs=None): if logs['loss'] < self.loss: self.loss = logs['loss'] bert.save_weights_as_checkpoint(model_saved_path) test_data = all_data[0][0] token_ids, segment_i...
如果传入权重,则加载。注:须在此处加载,才保证不报错。 if checkpoint_path is not None: bert.load_weights_from_checkpoint(checkpoint_path) train_model.summary() model_saved_path = './bert-wwm-model.ckpt' class ModelCheckpoint(keras.callbacks.Callback):
64
64
159
8
56
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
ModelCheckpoint
ModelCheckpoint
250
267
250
250
62793d9ce788e542ef080278e22d90aabbd906ac
bigcode/the-stack
train
624add86f09a81477434d0ee
train
function
def build_transformer_model_with_mlm(): """带mlm的bert模型 """ bert = build_transformer_model( config_path, with_mlm='linear', # with_nsp=True, model='bert', return_keras_model=False, # keep_tokens=keep_tokens ) proba = bert.model.output ...
def build_transformer_model_with_mlm():
"""带mlm的bert模型 """ bert = build_transformer_model( config_path, with_mlm='linear', # with_nsp=True, model='bert', return_keras_model=False, # keep_tokens=keep_tokens ) proba = bert.model.output # print(proba) # 辅助输入 toke...
) batch_segment_ids.append(segment_ids) batch_target_ids.append(target_tokens) batch_is_masked.append(is_masked) # batch_nsp.append([label]) if is_end or len(batch_token_ids) == self.batch_size: batch_token_ids = pad_sequences(batc...
223
223
744
9
214
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
build_transformer_model_with_mlm
build_transformer_model_with_mlm
146
223
146
146
9b7226eee4ab0a45a0dadbbd95c1bb77c6a79ea0
bigcode/the-stack
train
52113e68eba8bcd1329779de
train
function
def random_masking(lines): """对输入进行随机mask, 支持多行 """ if type(lines[0]) != list: lines = [lines] sources, targets = [tokenizer._token_start_id], [0] segments = [0] for i, sent in enumerate(lines): source, target = [], [] segment = [] rands = np.random.random(len(s...
def random_masking(lines):
"""对输入进行随机mask, 支持多行 """ if type(lines[0]) != list: lines = [lines] sources, targets = [tokenizer._token_start_id], [0] segments = [0] for i, sent in enumerate(lines): source, target = [], [] segment = [] rands = np.random.random(len(sent)) for r, word i...
load_data( '/home/mingming.xu/datasets/NLP/CLUE/tnews_public/dev.json' ) # tokenizer tokenizer = Tokenizer(dict_path, do_lower_case=True) all_data = train_data + valid_data pretrain_data = [d[0] for d in all_data] # whole word mask pretrain_data = [jieba.lcut(d) for d in pretrain_data] def random_masking(lines)...
94
94
316
6
88
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
random_masking
random_masking
69
111
69
69
5e5b93bd322cefe5417eb364fbcd72f959de321f
bigcode/the-stack
train
8bb3b90b97297894f87dbdae
train
class
class Evaluator(keras.callbacks.Callback): def __init__(self): self.best_acc = 0. def on_epoch_end(self, epoch, logs=None): acc = evaluate(val_generator) if acc > self.best_acc: self.best_acc = acc self.model.save_weights('best_baseline.weights') print('a...
class Evaluator(keras.callbacks.Callback):
def __init__(self): self.best_acc = 0. def on_epoch_end(self, epoch, logs=None): acc = evaluate(val_generator) if acc > self.best_acc: self.best_acc = acc self.model.save_weights('best_baseline.weights') print('acc: {}, best acc: {}'.format(acc, self.best...
y_true in tqdm(data): y_pred = model.predict(x_true).argmax(axis=1) y_true = y_true[:, 0] total += len(y_true) right += (y_true == y_pred).sum() return right / total class Evaluator(keras.callbacks.Callback):
64
64
85
8
55
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
Evaluator
Evaluator
305
314
305
305
e5d7f6944827cc3349b4f60bf1becfc4f6d3b672
bigcode/the-stack
train
577d581ca67f186e27e656af
train
function
def load_data(filename): D = [] with open(filename) as f: for i, l in enumerate(f): l = json.loads(l) text, label, label_des = l['sentence'], l['label'], l['label_desc'] label = int(label) - 100 if int(label) < 105 else int(label) - 101 D.append((text, int...
def load_data(filename):
D = [] with open(filename) as f: for i, l in enumerate(f): l = json.loads(l) text, label, label_des = l['sentence'], l['label'], l['label_desc'] label = int(label) - 100 if int(label) < 105 else int(label) - 101 D.append((text, int(label), label_des)) ...
_path = '/home/mingming.xu/pretrain/NLP/chinese_L-12_H-768_A-12/bert_model.ckpt' dict_path = '/home/mingming.xu/pretrain/NLP/chinese_L-12_H-768_A-12/vocab.txt' def load_data(filename):
64
64
94
5
59
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
load_data
load_data
40
48
40
40
e1f49d82d1d731ea259fb73ea7e66ffc8ba9fac8
bigcode/the-stack
train
521cbeffeba8d6617f1a4529
train
class
class data_generator(DataGenerator): def __iter__(self, shuffle=False): batch_token_ids, batch_segment_ids, batch_labels = [], [], [] for is_end, (text, label, label_desc) in self.get_sample(shuffle): token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen) batch_token_...
class data_generator(DataGenerator):
def __iter__(self, shuffle=False): batch_token_ids, batch_segment_ids, batch_labels = [], [], [] for is_end, (text, label, label_desc) in self.get_sample(shuffle): token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen) batch_token_ids.append(token_ids) bat...
= tokenizer._token_mask_id probs = bert.model.predict([np.array([token_ids]), np.array([segment_ids])]) print(tokenizer.decode(probs[0, 9:11].argmax(axis=1)), test_data) # fine-tune data generator class data_generator(DataGenerator):
64
64
166
6
57
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
data_generator
data_generator
271
287
271
271
5a6935c7ceca13fe57812e46fec52e051a46c9e6
bigcode/the-stack
train
62b15925643be89f080a799a
train
class
class pretrain_data_generator(DataGenerator): def __iter__(self, shuffle=False): batch_token_ids, batch_segment_ids, batch_target_ids, batch_is_masked, = [], [], [], [] for is_end, item in self.get_sample(shuffle): source_tokens, target_tokens, segment_ids = random_masking(item) ...
class pretrain_data_generator(DataGenerator):
def __iter__(self, shuffle=False): batch_token_ids, batch_segment_ids, batch_target_ids, batch_is_masked, = [], [], [], [] for is_end, item in self.get_sample(shuffle): source_tokens, target_tokens, segment_ids = random_masking(item) is_masked = [0 if i == 0 else 1 for i in...
.append(tokenizer._token_end_id) target.append(0) if i == 0: segment = [0] * len(source) else: segment = [1] * len(source) sources.extend(source) targets.extend(target) segments.extend(segment) return sources, targets, segments class pretrai...
75
75
252
8
66
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
pretrain_data_generator
pretrain_data_generator
114
137
114
114
ce69a7ca0a188d28320dd594d6b83ceb88c6313b
bigcode/the-stack
train
c0e3b45ad6f9838e07b2fdff
train
function
def evaluate(data): total, right = 0., 0. for x_true, y_true in tqdm(data): y_pred = model.predict(x_true).argmax(axis=1) y_true = y_true[:, 0] total += len(y_true) right += (y_true == y_pred).sum() return right / total
def evaluate(data):
total, right = 0., 0. for x_true, y_true in tqdm(data): y_pred = model.predict(x_true).argmax(axis=1) y_true = y_true[:, 0] total += len(y_true) right += (y_true == y_pred).sum() return right / total
pad_sequences(batch_labels) yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels = [], [], [] train_generator = data_generator(data=train_data, batch_size=batch_size) val_generator = data_generator(valid_data, batch_size) def eval...
64
64
76
4
60
xv44586/toolkit4nlp
examples/classification_tnews_pretrain_before_finetuning.py
Python
evaluate
evaluate
294
302
294
294
0694449f4d66aa59453f6afedd19c123ccd3bd65
bigcode/the-stack
train
cf60a9a12fb4aec2639c2be1
train
class
class AuthRequiredEvent(BaseEvent): js_name = 'Fetch.authRequired' hashable = ['frameId', 'requestId'] is_hashable = True def __init__(self, requestId: Union['RequestId', dict], request: Union['Network.Request', dict], frameId: Union['Page.FrameId', d...
class AuthRequiredEvent(BaseEvent):
js_name = 'Fetch.authRequired' hashable = ['frameId', 'requestId'] is_hashable = True def __init__(self, requestId: Union['RequestId', dict], request: Union['Network.Request', dict], frameId: Union['Page.FrameId', dict], resourceType: ...
@classmethod def build_hash(cls, networkId, frameId, requestId): kwargs = locals() kwargs.pop('cls') serialized_id_params = ','.join(['='.join([p, str(v)]) for p, v in kwargs.items()]) h = '{}:{}'.format(cls.js_name, serialized_id_params) log.debug('generated hash = %s' % h)...
93
93
311
7
85
spinda/chromewhip
chromewhip/protocol/fetch.py
Python
AuthRequiredEvent
AuthRequiredEvent
332
368
332
333
7b99add732703d678d1e599417755e0ccbeb098d
bigcode/the-stack
train
765b04a339cdc74663014d22
train
class
class Fetch(PayloadMixin): """ A domain for letting clients substitute browser's network layer with client code. """ @classmethod def disable(cls): """Disables the fetch domain. """ return ( cls.build_send_payload("disable", { }), None ...
class Fetch(PayloadMixin):
""" A domain for letting clients substitute browser's network layer with client code. """ @classmethod def disable(cls): """Disables the fetch domain. """ return ( cls.build_send_payload("disable", { }), None ) @classmethod def...
RequestStage'] = None, ): self.urlPattern = urlPattern self.resourceType = resourceType self.requestStage = requestStage # HeaderEntry: Response HTTP header entry class HeaderEntry(ChromeTypeBase): def __init__(self, name: Union['str'], v...
256
256
1,517
6
249
spinda/chromewhip
chromewhip/protocol/fetch.py
Python
Fetch
Fetch
77
277
77
77
ec673a2a30037ff4a7066f91f727708f405ce730
bigcode/the-stack
train
e78afdf74fab7fc05b8c18fc
train
class
class HeaderEntry(ChromeTypeBase): def __init__(self, name: Union['str'], value: Union['str'], ): self.name = name self.value = value
class HeaderEntry(ChromeTypeBase):
def __init__(self, name: Union['str'], value: Union['str'], ): self.name = name self.value = value
['Network.ResourceType'] = None, requestStage: Optional['RequestStage'] = None, ): self.urlPattern = urlPattern self.resourceType = resourceType self.requestStage = requestStage # HeaderEntry: Response HTTP header entry class HeaderEntry(ChromeTypeBase):
64
64
44
8
55
spinda/chromewhip
chromewhip/protocol/fetch.py
Python
HeaderEntry
HeaderEntry
39
46
39
39
bd3010e7783f78a936e8dda9278a816af05c81f4
bigcode/the-stack
train
2301e5cc45476246f2dbb3f0
train
class
class RequestPattern(ChromeTypeBase): def __init__(self, urlPattern: Optional['str'] = None, resourceType: Optional['Network.ResourceType'] = None, requestStage: Optional['RequestStage'] = None, ): self.urlPattern = urlPattern self...
class RequestPattern(ChromeTypeBase):
def __init__(self, urlPattern: Optional['str'] = None, resourceType: Optional['Network.ResourceType'] = None, requestStage: Optional['RequestStage'] = None, ): self.urlPattern = urlPattern self.resourceType = resourceType s...
Unique request identifier. RequestId = str # RequestStage: Stages of the request to handle. Request will intercept before the request issent. Response will intercept after the response is received (but before responsebody is received. RequestStage = str # RequestPattern: class RequestPattern(ChromeTypeBase):
63
64
78
8
55
spinda/chromewhip
chromewhip/protocol/fetch.py
Python
RequestPattern
RequestPattern
26
35
26
26
de744bf5d6442829a2af65a045e8fa86055a1a45
bigcode/the-stack
train
e9df0a48e0504754407c07f7
train
class
class RequestPausedEvent(BaseEvent): js_name = 'Fetch.requestPaused' hashable = ['networkId', 'frameId', 'requestId'] is_hashable = True def __init__(self, requestId: Union['RequestId', dict], request: Union['Network.Request', dict], frameId: Union['P...
class RequestPausedEvent(BaseEvent):
js_name = 'Fetch.requestPaused' hashable = ['networkId', 'frameId', 'requestId'] is_hashable = True def __init__(self, requestId: Union['RequestId', dict], request: Union['Network.Request', dict], frameId: Union['Page.FrameId', dict], ...
to provide the response body. The stream only supports sequential read, IO.read will fail if the position is specified. This method is mutually exclusive with getResponseBody. Calling other methods that affect the request or disabling fetch domain before body is received results in an undefined behavior. :para...
138
139
464
7
131
spinda/chromewhip
chromewhip/protocol/fetch.py
Python
RequestPausedEvent
RequestPausedEvent
281
329
281
282
f327e5b241816e4726d0ad384a2438fc356d1f10
bigcode/the-stack
train
cd67f4fad02c56a7292580be
train
class
class AuthChallengeResponse(ChromeTypeBase): def __init__(self, response: Union['str'], username: Optional['str'] = None, password: Optional['str'] = None, ): self.response = response self.username = username self.password ...
class AuthChallengeResponse(ChromeTypeBase):
def __init__(self, response: Union['str'], username: Optional['str'] = None, password: Optional['str'] = None, ): self.response = response self.username = username self.password = password
realm: Union['str'], source: Optional['str'] = None, ): self.source = source self.origin = origin self.scheme = scheme self.realm = realm # AuthChallengeResponse: Response to an AuthChallenge. class AuthChallengeResponse(ChromeTypeBas...
64
64
64
9
55
spinda/chromewhip
chromewhip/protocol/fetch.py
Python
AuthChallengeResponse
AuthChallengeResponse
65
74
65
65
d682e5c4c1e5430957e217f3f61a7b44960072b9
bigcode/the-stack
train
e4042cc870b24feb68b11cd3
train
class
class AuthChallenge(ChromeTypeBase): def __init__(self, origin: Union['str'], scheme: Union['str'], realm: Union['str'], source: Optional['str'] = None, ): self.source = source self.origin = origin self.sch...
class AuthChallenge(ChromeTypeBase):
def __init__(self, origin: Union['str'], scheme: Union['str'], realm: Union['str'], source: Optional['str'] = None, ): self.source = source self.origin = origin self.scheme = scheme self.realm = rea...
ChromeTypeBase): def __init__(self, name: Union['str'], value: Union['str'], ): self.name = name self.value = value # AuthChallenge: Authorization challenge for HTTP status code 401 or 407. class AuthChallenge(ChromeTypeBase):
64
64
73
8
56
spinda/chromewhip
chromewhip/protocol/fetch.py
Python
AuthChallenge
AuthChallenge
50
61
50
50
6de9a8b2f308535099d2fed4c7ef5c4c3e728f56
bigcode/the-stack
train
4aec8498fb90c2b9ced5f800
train
class
class ModularSymbolsAmbient_wtk_gamma_h(ModularSymbolsAmbient): def __init__(self, group, weight, sign, F, custom_init=None, category=None): r""" Initialize a space of modular symbols for `\Gamma_H(N)`. INPUT: - ``group`` - a congruence subgroup `\Gamma_H(N)`. ...
class ModularSymbolsAmbient_wtk_gamma_h(ModularSymbolsAmbient):
def __init__(self, group, weight, sign, F, custom_init=None, category=None): r""" Initialize a space of modular symbols for `\Gamma_H(N)`. INPUT: - ``group`` - a congruence subgroup `\Gamma_H(N)`. - ``weight`` - int, the weight = 2 - ``sign`` - int,...
parameters as this space except with level `N`. INPUT: - ``N`` (int) -- a positive integer. OUTPUT: (Modular Symbol space) A space of modular symbols with the same defining properties (weight, sign, etc.) as this space except with level `N`. For exam...
256
256
1,642
13
243
fredstro/sage
src/sage/modular/modsym/ambient.py
Python
ModularSymbolsAmbient_wtk_gamma_h
ModularSymbolsAmbient_wtk_gamma_h
3,247
3,426
3,247
3,247
c5c284b13c6cad04c1ac81ff4238087c2a145311
bigcode/the-stack
train
e7f241510edda31b6d9b7b19
train
class
class ModularSymbolsAmbient_wtk_g0(ModularSymbolsAmbient): r""" Modular symbols for `\Gamma_0(N)` of integer weight `k > 2` over the field `F`. For weight `2`, it is faster to use ``ModularSymbols_wt2_g0``. INPUT: - ``N`` - int, the level - ``k`` - integer weight = 2. - ``sign``...
class ModularSymbolsAmbient_wtk_g0(ModularSymbolsAmbient):
r""" Modular symbols for `\Gamma_0(N)` of integer weight `k > 2` over the field `F`. For weight `2`, it is faster to use ``ModularSymbols_wt2_g0``. INPUT: - ``N`` - int, the level - ``k`` - integer weight = 2. - ``sign`` - int, either -1, 0, or 1 - ``F`` - field EXAM...
i works, i.e., ith row of every element of B is nonzero. bad = False for C in B: if C.row(i) == 0: # i is bad. bad = True continue if bad: continue # It turns out that i is not bad. n...
256
256
3,074
13
242
fredstro/sage
src/sage/modular/modsym/ambient.py
Python
ModularSymbolsAmbient_wtk_g0
ModularSymbolsAmbient_wtk_g0
2,351
2,699
2,351
2,351
001b3bbd5a5055957ee6b21c27ac3436f0ed7b5e
bigcode/the-stack
train
cc4c0ed3c304e55317f34780
train
class
class ModularSymbolsAmbient_wt2_g0(ModularSymbolsAmbient_wtk_g0): r""" Modular symbols for `\Gamma_0(N)` of integer weight `2` over the field `F`. INPUT: - ``N`` - int, the level - ``sign`` - int, either -1, 0, or 1 OUTPUT: The space of modular symbols of weight `2`, trivial char...
class ModularSymbolsAmbient_wt2_g0(ModularSymbolsAmbient_wtk_g0):
r""" Modular symbols for `\Gamma_0(N)` of integer weight `2` over the field `F`. INPUT: - ``N`` - int, the level - ``sign`` - int, either -1, 0, or 1 OUTPUT: The space of modular symbols of weight `2`, trivial character, level `N` and given sign. EXAMPLES:: sage...
M.T(2)(M.0).element() (8, 1, -1, -2, 2, 2, -3, 1, -2, 3, -1, 0) sage: M.T(3)(M.0).element() (27, 4, -4, -8, 8, 10, -14, 4, -9, 14, -5, 0) sage: M.T(4)(M.0).element() (64, 10, -10, -20, 20, 26, -36, 10, -24, 38, -14, 0) """ # Find basis vector ...
256
256
2,267
18
238
fredstro/sage
src/sage/modular/modsym/ambient.py
Python
ModularSymbolsAmbient_wt2_g0
ModularSymbolsAmbient_wt2_g0
2,701
2,969
2,701
2,701
729e41c1961d8aec1d98b3667cb4b112a880c800
bigcode/the-stack
train
4f9b8b92b12f6421ae920d64
train
class
class ModularSymbolsAmbient_wtk_eps(ModularSymbolsAmbient): def __init__(self, eps, weight, sign, base_ring, custom_init=None, category=None): """ Space of modular symbols with given weight, character, base ring and sign. INPUT: - ``eps`` - dirichlet.DirichletCharacter, t...
class ModularSymbolsAmbient_wtk_eps(ModularSymbolsAmbient):
def __init__(self, eps, weight, sign, base_ring, custom_init=None, category=None): """ Space of modular symbols with given weight, character, base ring and sign. INPUT: - ``eps`` - dirichlet.DirichletCharacter, the "Nebentypus" character. - ``weight``...
_symbols_of_level(5) Modular Symbols space of dimension 4 for Gamma_0(5) of weight 6 with sign 0 over Rational Field sage: M.modular_symbols_of_level(30) Traceback (most recent call last): ... ValueError: N (=30) should be a factor of the level of this space (...
255
256
3,750
12
243
fredstro/sage
src/sage/modular/modsym/ambient.py
Python
ModularSymbolsAmbient_wtk_eps
ModularSymbolsAmbient_wtk_eps
3,429
3,839
3,429
3,429
66431e4596f7f2bfdc4620bfddedaffba1afdf37
bigcode/the-stack
train
f4da990c71cb26f16d96b61b
train
class
class ModularSymbolsAmbient(space.ModularSymbolsSpace, hecke.AmbientHeckeModule): r""" An ambient space of modular symbols for a congruence subgroup of `SL_2(\ZZ)`. This class is an abstract base class, so only derived classes should be instantiated. INPUT: - ``weight`` - an integer -...
class ModularSymbolsAmbient(space.ModularSymbolsSpace, hecke.AmbientHeckeModule):
r""" An ambient space of modular symbols for a congruence subgroup of `SL_2(\ZZ)`. This class is an abstract base class, so only derived classes should be instantiated. INPUT: - ``weight`` - an integer - ``group`` - a congruence subgroup. - ``sign`` - an integer, either -1, 0, or ...
import sage.modular.arithgroup.all as arithgroup import sage.modular.dirichlet as dirichlet import sage.modular.hecke.all as hecke import sage.rings.rational_field as rational_field import sage.rings.integer_ring as integer_ring import sage.rings.all as rings import sage.arith.all as arith import sage.rings.polynomial....
256
256
21,542
19
236
fredstro/sage
src/sage/modular/modsym/ambient.py
Python
ModularSymbolsAmbient
ModularSymbolsAmbient
118
2,348
118
118
52568c96e6f1ce7a98ef8aa09210036865b19d8f
bigcode/the-stack
train
4d1b1360d0b75e4fbd92b165
train
class
class ModularSymbolsAmbient_wtk_g1(ModularSymbolsAmbient): r""" INPUT: - ``level`` - int, the level - ``weight`` - int, the weight = 2 - ``sign`` - int, either -1, 0, or 1 - ``F`` - field EXAMPLES:: sage: ModularSymbols(Gamma1(17),2) Modular Symbols space of dimen...
class ModularSymbolsAmbient_wtk_g1(ModularSymbolsAmbient):
r""" INPUT: - ``level`` - int, the level - ``weight`` - int, the weight = 2 - ``sign`` - int, either -1, 0, or 1 - ``F`` - field EXAMPLES:: sage: ModularSymbols(Gamma1(17),2) Modular Symbols space of dimension 25 for Gamma_1(17) of weight 2 with sign 0 and over Ra...
0 0 1] [ 0 -2 2 -2 0] [-5 3 -1 1 0] sage: v = M.basis()[1] sage: M.T(3)(v).element() (0, 1, -2, 2, 0) sage: M.T(4)(v).element() (2, -3, 0, 0, 1) sage: M.T(5)(v).element() (0, -2, 2, -2, 0) sa...
256
256
2,236
13
243
fredstro/sage
src/sage/modular/modsym/ambient.py
Python
ModularSymbolsAmbient_wtk_g1
ModularSymbolsAmbient_wtk_g1
2,972
3,245
2,972
2,972
e8b20940a7bc2ebab49acacaa6ce6e81ddb9ffb8
bigcode/the-stack
train
712c3bc1509692cef1b04502
train
function
def bubble_sort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-1-i): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j]
def bubble_sort(arr):
n = len(arr) for i in range(n-1): for j in range(0, n-1-i): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j]
''' * Sắp xếp nổi bọt ''' def bubble_sort(arr):
16
64
62
5
11
hainvit/dev
python_data_structures_and_algorithms/sort/bubble_sort.py
Python
bubble_sort
bubble_sort
6
11
6
6
b3510101928bc4f5c265d9fb4f623a6748a8066d
bigcode/the-stack
train
09323cf61f237c7371c8c5b0
train
class
class DroneSTC(BaseUlAlgorithm): """ Spatial and Temporal Contrastive Pretraining with ConvGru features """ opt_info_fields = tuple(f for f in OptInfo._fields) # copy def __init__( self, batch_T=32, # the default length of extracted batch batch_B=16, # batch ...
class DroneSTC(BaseUlAlgorithm):
""" Spatial and Temporal Contrastive Pretraining with ConvGru features """ opt_info_fields = tuple(f for f in OptInfo._fields) # copy def __init__( self, batch_T=32, # the default length of extracted batch batch_B=16, # batch B is the sampled batch size for e...
import torch from collections import namedtuple import copy from rlpyt.utils.tensor import valid_mean from rlpyt.ul.algos.ul_for_rl.base import BaseUlAlgorithm from rlpyt.utils.quick_args import save__init__args from rlpyt.utils.logging import logger from rlpyt.ul.replays.offline_ul_replay import OfflineUlReplayBuffer ...
252
256
2,811
8
244
Slienteagle-wyb/rlpyt
rlpyt/ul/algos/ul_for_rl/stc.py
Python
DroneSTC
DroneSTC
22
297
22
22
7b63689306a9dfc50d5e4a36b32f33604226317c
bigcode/the-stack
train
d1ee8d271635c4ca235a60b6
train
class
class Trainer: def __init__(self, total_cls, paradigm, run,dataset): self.total_cls = total_cls self.seen_cls = 0 #self.dataset = Cifar100() if dataset == "core50": self.dataset = Core50(paradigm, run) if dataset == 'toybox': self.dataset = Toybox(para...
class Trainer:
def __init__(self, total_cls, paradigm, run,dataset): self.total_cls = total_cls self.seen_cls = 0 #self.dataset = Cifar100() if dataset == "core50": self.dataset = Core50(paradigm, run) if dataset == 'toybox': self.dataset = Toybox(paradigm, run) ...
import torch import torchvision from torchvision.models import vgg16 from torchvision import transforms from torch.utils.data import DataLoader from torch.optim import Adam import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision.transforms import Compose, CenterCrop, Normalize...
189
256
5,190
3
185
kreimanlab/AugMem
other_models/BIC/trainer.py
Python
Trainer
Trainer
32
553
32
32
2ab22bd3f771faa054b70b9138b32b97d1087fe9
bigcode/the-stack
train
6a2506f2d5545b42520e65e0
train
class
class PipelineCreate(object): """Creates a nf-core pipeline a la carte from the nf-core best-practice template. Args: name (str): Name for the pipeline. description (str): Description for the pipeline. author (str): Authors name of the pipeline. version (str): Version flag. Sema...
class PipelineCreate(object):
"""Creates a nf-core pipeline a la carte from the nf-core best-practice template. Args: name (str): Name for the pipeline. description (str): Description for the pipeline. author (str): Authors name of the pipeline. version (str): Version flag. Semantic versioning only. Defaults...
#!/usr/bin/env python """Creates a nf-core pipeline matching the current organization's specification based on a template. """ from genericpath import exists import git import jinja2 import logging import os import pathlib import requests import shutil import sys import nf_core log = logging.getLogger(__name__) class...
74
256
1,655
5
69
matrulda/tools
nf_core/create.py
Python
PipelineCreate
PipelineCreate
20
181
20
20
987e59dbd9837dadfda4dea6d94b57920a7403ba
bigcode/the-stack
train
c0e15a7c2bfbf708405381a6
train
class
class HttpDownload(Step): def __init__(self, url: str, headers: dict): super().__init__() self._url = url self._headers = headers def perform(self, data: str) -> str: logger.info(f"Downloading {self._url} with headers {self._headers}") return requests.get(self._url, head...
class HttpDownload(Step):
def __init__(self, url: str, headers: dict): super().__init__() self._url = url self._headers = headers def perform(self, data: str) -> str: logger.info(f"Downloading {self._url} with headers {self._headers}") return requests.get(self._url, headers=self._headers).content...
import logging import requests from pipeliner.steps.step import Step logger = logging.getLogger(__name__) class HttpDownload(Step):
29
64
85
6
23
stefan-misik/pipeliner
pipeliner/steps/http_download.py
Python
HttpDownload
HttpDownload
10
18
10
10
e1f1f2dcaef2bdcb020ae11c291785e14cf7f32b
bigcode/the-stack
train
0e33100be79f32cced35ab5d
train
class
class PySCFDriver(ElectronicStructureDriver): """A Second-Quantization driver for Qiskit Nature using the PySCF library. References: https://pyscf.org/ """ def __init__( self, atom: Union[str, List[str]] = "H 0.0 0.0 0.0; H 0.0 0.0 0.735", unit: UnitsType = UnitsType.AN...
class PySCFDriver(ElectronicStructureDriver):
"""A Second-Quantization driver for Qiskit Nature using the PySCF library. References: https://pyscf.org/ """ def __init__( self, atom: Union[str, List[str]] = "H 0.0 0.0 0.0; H 0.0 0.0 0.735", unit: UnitsType = UnitsType.ANGSTROM, charge: int = 0, spin:...
Basis, ElectronicBasisTransform, ) from qiskit_nature.properties.second_quantization.electronic.integrals import ( OneBodyElectronicIntegrals, TwoBodyElectronicIntegrals, ) from ....exceptions import QiskitNatureError from ..electronic_structure_driver import ElectronicStructureDriver, MethodType from ...m...
256
256
6,218
11
245
mrossinek/qiskit-nature
qiskit_nature/drivers/second_quantization/pyscfd/pyscfdriver.py
Python
PySCFDriver
PySCFDriver
75
759
75
75
248ab9eedb5925cbd66625a2bb6af1a09a6b415e
bigcode/the-stack
train
10122d85cf779b094eef2694
train
class
class InitialGuess(Enum): """Initial Guess Enum""" MINAO = "minao" HCORE = "1e" ONE_E = "1e" ATOM = "atom"
class InitialGuess(Enum):
"""Initial Guess Enum""" MINAO = "minao" HCORE = "1e" ONE_E = "1e" ATOM = "atom"
cf.lib import param from pyscf.tools import dump_mat warnings.filterwarnings("ignore", category=DeprecationWarning, module="pyscf") except ImportError: logger.info("PySCF is not installed. See https://pyscf.org/install.html") class InitialGuess(Enum):
64
64
42
5
59
mrossinek/qiskit-nature
qiskit_nature/drivers/second_quantization/pyscfd/pyscfdriver.py
Python
InitialGuess
InitialGuess
66
72
66
66
d3a3eba074449c055609ac1658f5fa8e2b61bb73
bigcode/the-stack
train
75b3185cef3d8272014fd04d
train
class
class UserEmailConfirmationForm(forms.Form): email = forms.EmailField() secret = forms.CharField(min_length=32, max_length=32) user_id = forms.IntegerField() def __init__(self, user, *args, **kwargs): self.user = user super(UserEmailConfirmationForm, self).__init__(*args, **kwargs) ...
class UserEmailConfirmationForm(forms.Form):
email = forms.EmailField() secret = forms.CharField(min_length=32, max_length=32) user_id = forms.IntegerField() def __init__(self, user, *args, **kwargs): self.user = user super(UserEmailConfirmationForm, self).__init__(*args, **kwargs) def clean_user_id(self): user_id = s...
_('Another user with that email address already exists!') ) return email def save(self): self.user.address = self.cleaned_data['address'] if HAVE_NEWSLETTER(): self.user.newsletter = self.cleaned_data['newsletter'] self.user.save() class UserEmailConfirmati...
64
64
209
8
56
okko/tietopyynto
froide/account/forms.py
Python
UserEmailConfirmationForm
UserEmailConfirmationForm
202
232
202
202
973732692bc04a334588a5845859268e0035f83a
bigcode/the-stack
train
50274e06f647ea6b90682a70
train
class
class UserChangeForm(forms.Form): email = forms.EmailField(required=False, widget=forms.EmailInput( attrs={ 'placeholder': _('mail@ddress.net'), 'class': 'form-control' }), label=_('Your email address')) address = forms.CharField(max_length=300, label...
class UserChangeForm(forms.Form):
email = forms.EmailField(required=False, widget=forms.EmailInput( attrs={ 'placeholder': _('mail@ddress.net'), 'class': 'form-control' }), label=_('Your email address')) address = forms.CharField(max_length=300, label=_('Your mailing address'), ...
}), label=_('Email address')) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control' }), label=_('Password')) class PasswordResetForm(auth.forms.PasswordResetForm): email = forms.EmailField(widget=forms.EmailInput( att...
99
100
334
7
92
okko/tietopyynto
froide/account/forms.py
Python
UserChangeForm
UserChangeForm
158
199
158
158
ce2fa1ea7438e6fea5684be2037d1f223b61a44e
bigcode/the-stack
train
ce703e4d1a44cd239dae227d
train
class
class PasswordResetForm(auth.forms.PasswordResetForm): email = forms.EmailField(widget=forms.EmailInput( attrs={ 'placeholder': _('mail@ddress.net'), 'class': 'form-control' }), label=_('Email address'))
class PasswordResetForm(auth.forms.PasswordResetForm):
email = forms.EmailField(widget=forms.EmailInput( attrs={ 'placeholder': _('mail@ddress.net'), 'class': 'form-control' }), label=_('Email address'))
mail@ddress.net'), 'class': 'form-control' }), label=_('Email address')) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control' }), label=_('Password')) class PasswordResetForm(auth.forms.PasswordResetForm):
63
64
52
10
53
okko/tietopyynto
froide/account/forms.py
Python
PasswordResetForm
PasswordResetForm
149
155
149
149
cac722dad376b255ea8196e17f22bd0151930433
bigcode/the-stack
train
01b3fec83d0f213b9e629e98
train
class
class NewUserForm(TermsForm, NewUserBaseForm): pass
class NewUserForm(TermsForm, NewUserBaseForm):
pass
, label=_("Check if you want to receive our newsletter.")) def save(self, user): user.terms = True if HAVE_NEWSLETTER(): user.newsletter = self.cleaned_data['newsletter'] user.save() class NewUserForm(TermsForm, NewUserBaseForm):
64
64
16
13
51
okko/tietopyynto
froide/account/forms.py
Python
NewUserForm
NewUserForm
118
119
118
118
f9913162b9c2e85a57281b77f955fe5869a85f5e
bigcode/the-stack
train
4e7e9a255e0801687a2953c2
train
class
class UserLoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput( attrs={ 'placeholder': _('mail@ddress.net'), 'class': 'form-control' }), label=_('Email address')) password = forms.CharField(widget=forms.PasswordInput( attrs={ ...
class UserLoginForm(forms.Form):
email = forms.EmailField(widget=forms.EmailInput( attrs={ 'placeholder': _('mail@ddress.net'), 'class': 'form-control' }), label=_('Email address')) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control' ...
, label=_('Password (repeat)')) def clean(self): cleaned = super(NewUserWithPasswordForm, self).clean() if cleaned['password'] != cleaned['password2']: raise forms.ValidationError(_("Passwords do not match!")) return cleaned class UserLoginForm(forms.Form):
64
64
79
7
56
okko/tietopyynto
froide/account/forms.py
Python
UserLoginForm
UserLoginForm
135
146
135
135
8c383aeb16749b4f5f009f6ae253cb34b6c980d2
bigcode/the-stack
train
a46f6f385ab6f5c9a4720ae9
train
class
class UserDeleteForm(forms.Form): CONFIRMATION_PHRASE = str(_('Freedom of Information Act')) password = forms.CharField( widget=forms.PasswordInput(), label=_('Password'), help_text=_('Please type your password to confirm.') ) confirmation = forms.CharField( widget=Confi...
class UserDeleteForm(forms.Form):
CONFIRMATION_PHRASE = str(_('Freedom of Information Act')) password = forms.CharField( widget=forms.PasswordInput(), label=_('Password'), help_text=_('Please type your password to confirm.') ) confirmation = forms.CharField( widget=ConfirmationWidget( {'place...
( self.cleaned_data['secret'], self.cleaned_data['email'], ) if not check: raise forms.ValidationError( _('Link is invalid or has expired!') ) return self.cleaned_data def save(self): self.user.email = self.cleaned_data...
73
73
246
7
66
okko/tietopyynto
froide/account/forms.py
Python
UserDeleteForm
UserDeleteForm
235
272
235
235
d2bfd874a76e68567af4647c808957f713e6b486
bigcode/the-stack
train
49c7668b0d92072d6cd5553d
train
class
class NewUserWithPasswordForm(NewUserForm): password = forms.CharField(widget=forms.PasswordInput, label=_('Password')) password2 = forms.CharField(widget=forms.PasswordInput, label=_('Password (repeat)')) def clean(self): cleaned = super(NewUserWithPasswordForm, self).clean...
class NewUserWithPasswordForm(NewUserForm):
password = forms.CharField(widget=forms.PasswordInput, label=_('Password')) password2 = forms.CharField(widget=forms.PasswordInput, label=_('Password (repeat)')) def clean(self): cleaned = super(NewUserWithPasswordForm, self).clean() if cleaned['password'] != cleaned...
.")) def save(self, user): user.terms = True if HAVE_NEWSLETTER(): user.newsletter = self.cleaned_data['newsletter'] user.save() class NewUserForm(TermsForm, NewUserBaseForm): pass class NewUserWithPasswordForm(NewUserForm):
64
64
95
10
53
okko/tietopyynto
froide/account/forms.py
Python
NewUserWithPasswordForm
NewUserWithPasswordForm
122
132
122
122
fdcf5926f3a8d424d1a9823c748ddc259f742a1d
bigcode/the-stack
train
fcb17d9318f3021e07b998d5
train
class
class TermsForm(forms.Form): terms = forms.BooleanField( label=mark_safe(_("Terms and Conditions and Privacy Statement")), error_messages={'required': _('You need to accept our Terms and Conditions and Priavcy Statement.')}, widget=AgreeCheckboxInput( agree_to=_(u'You...
class TermsForm(forms.Form):
terms = forms.BooleanField( label=mark_safe(_("Terms and Conditions and Privacy Statement")), error_messages={'required': _('You need to accept our Terms and Conditions and Priavcy Statement.')}, widget=AgreeCheckboxInput( agree_to=_(u'You agree to our <a href="%(url_...
a>') % { 'url': reverse("account-login"), 'email': email })) else: raise forms.ValidationError( _('This email address is already registered, but not yet confirmed! Please click on the confirmation...
69
69
230
6
62
okko/tietopyynto
froide/account/forms.py
Python
TermsForm
TermsForm
96
115
96
96
e15e6f28a4213a3d2ad2dabaae9e060416224a33
bigcode/the-stack
train
b318a1b72544ca164c809103
train
class
class NewUserBaseForm(forms.Form): first_name = forms.CharField(max_length=30, label=_('First name'), widget=forms.TextInput(attrs={'placeholder': _('First Name'), 'class': 'form-control'})) last_name = forms.CharField(max_length=30, label=_('Last name'), ...
class NewUserBaseForm(forms.Form):
first_name = forms.CharField(max_length=30, label=_('First name'), widget=forms.TextInput(attrs={'placeholder': _('First Name'), 'class': 'form-control'})) last_name = forms.CharField(max_length=30, label=_('Last name'), widget=forms.TextInput(attr...
import floppyforms as forms from django.utils.six import text_type as str from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from django.contrib import auth from django.contrib.auth import get_user_model from django.conf im...
180
207
692
8
172
okko/tietopyynto
froide/account/forms.py
Python
NewUserBaseForm
NewUserBaseForm
22
93
22
22
2d6ba66df8872230bda02214598052475c6019e6
bigcode/the-stack
train
b63fa031d0d74cc668d54263
train
class
class Migration(migrations.Migration): dependencies = [ ('project', '0007_auto_20170905_0457'), ] operations = [ migrations.AddField( model_name='eoi', name='justification_for_direct_selection', field=models.CharField(blank=True, choices=[('Kno', 'Known ...
class Migration(migrations.Migration):
dependencies = [ ('project', '0007_auto_20170905_0457'), ] operations = [ migrations.AddField( model_name='eoi', name='justification_for_direct_selection', field=models.CharField(blank=True, choices=[('Kno', 'Known expertise'), ('Loc', 'Local presence'), ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-05 05:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
54
64
165
7
46
unicef/un-partner-portal
backend/unpp_api/apps/project/migrations/0008_auto_20170905_0520.py
Python
Migration
Migration
8
25
8
9
10de9e5c4fcb8c924867de34eb7d3d3f49aa26c1
bigcode/the-stack
train
7e1e14e5bd43ced04681053d
train
class
class ImageArea: def __init__(self, width, height): self.width = width self.height = height self.area = self.get_area() def get_area(self): return self.width * self.height def __lt__(self, other): return self.area < other.area def __le__(self, other): r...
class ImageArea:
def __init__(self, width, height): self.width = width self.height = height self.area = self.get_area() def get_area(self): return self.width * self.height def __lt__(self, other): return self.area < other.area def __le__(self, other): return self.area <...
class ImageArea:
4
64
134
4
0
Veselin-Stoilov/software-university-OOP
polymorphism_and_abstraction/image_area.py
Python
ImageArea
ImageArea
1
23
1
1
55b11f543988f976175bd33f1d7dc94031b8b4a3
bigcode/the-stack
train
35f8eaee7d35d27d16c9e46d
train
function
def _maximize_1d(g, s1, s2, g1): PHI = (1.0 + _np.sqrt(5.0)) / 2 # golden ratio TOL = 1e-10; FRAC_TOL = 1e-6 # Note (s1,g1) and s2 are given. Start with bracket (s1,s2,s3) #s3 = s2*(1.0+PHI); g2 = g(s2); g3 = g(s3) s3 = s2 + PHI * (s2 - s1); g2 = g(s2); g3 = g(s3) # s4,g4 = None,None s1_...
def _maximize_1d(g, s1, s2, g1):
PHI = (1.0 + _np.sqrt(5.0)) / 2 # golden ratio TOL = 1e-10; FRAC_TOL = 1e-6 # Note (s1,g1) and s2 are given. Start with bracket (s1,s2,s3) #s3 = s2*(1.0+PHI); g2 = g(s2); g3 = g(s3) s3 = s2 + PHI * (s2 - s1); g2 = g(s2); g3 = g(s3) # s4,g4 = None,None s1_on_bd = s3_on_bd = False #pri...
not None else "--", ", chg_dot=", _np.dot(change, lastchange) / (_np.linalg.norm(change) * _np.linalg.norm(lastchange) + 1e-6)) if abs(difference) < tol: break # Convergence condition lastchange = change last_fx = fx last_x = x.copy() step += 1 ...
236
236
787
17
218
colibri-coruscans/pyGSTi
pygsti/optimize/customcg.py
Python
_maximize_1d
_maximize_1d
143
191
143
144
5d9192d8bbd4721127e888523248eec5dbe01a2d
bigcode/the-stack
train
0662ac6cfcb4b02164c5ad84
train
function
def fmax_cg(f, x0, maxiters=100, tol=1e-8, dfdx_and_bdflag=None, xopt=None): """ Custom conjugate-gradient (CG) routine for maximizing a function. This function runs slower than scipy.optimize's 'CG' method, but doesn't give up or get stuck as easily, and so sometimes can be a better option. Param...
def fmax_cg(f, x0, maxiters=100, tol=1e-8, dfdx_and_bdflag=None, xopt=None):
""" Custom conjugate-gradient (CG) routine for maximizing a function. This function runs slower than scipy.optimize's 'CG' method, but doesn't give up or get stuck as easily, and so sometimes can be a better option. Parameters ---------- f : function The function to optimize x...
""" A custom conjugate gradient descent algorithm """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government...
216
256
1,250
34
181
colibri-coruscans/pyGSTi
pygsti/optimize/customcg.py
Python
fmax_cg
fmax_cg
21
139
21
21
a250aca1def654dc27767d42fd713bdf1d8b51ad
bigcode/the-stack
train
98b74e77208735c7b1fe24c8
train
function
def _find_boundary(g, s1, s2): #print "DEBUG: finding bd fn" TOL = 1e-6 while(abs(s1 - s2) > TOL): # just do binary search m = (s1 + s2) / 2.0; gm = g(m) if gm is None: s2 = m else: s1 = m return s1, g(s1)
def _find_boundary(g, s1, s2): #print "DEBUG: finding bd fn"
TOL = 1e-6 while(abs(s1 - s2) > TOL): # just do binary search m = (s1 + s2) / 2.0; gm = g(m) if gm is None: s2 = m else: s1 = m return s1, g(s1)
#find boundary of g (i.e. at the edge of where it is defined) # g(s1) must be defined (not None) and g(s2) must == None (function undefined) def _find_boundary(g, s1, s2): #print "DEBUG: finding bd fn"
64
64
101
22
42
colibri-coruscans/pyGSTi
pygsti/optimize/customcg.py
Python
_find_boundary
_find_boundary
219
226
219
220
48beae51508171908f4375184c6222348463f333
bigcode/the-stack
train
77ac11e1b01e6253468aa2e6
train
function
def _finite_diff_dfdx_and_bdflag(f, x, delta): x = x.copy() # make sure x is unaltered N = len(x) dfdx = _np.zeros(N) # complex? bd = _np.zeros(N) for k in range(N): x[k] += delta; fPlus = f(x) x[k] -= 2 * delta; fMinus = f(x) x[k] += delta if fPlus is None: bd[k] =...
def _finite_diff_dfdx_and_bdflag(f, x, delta):
x = x.copy() # make sure x is unaltered N = len(x) dfdx = _np.zeros(N) # complex? bd = _np.zeros(N) for k in range(N): x[k] += delta; fPlus = f(x) x[k] -= 2 * delta; fMinus = f(x) x[k] += delta if fPlus is None: bd[k] = +1.0 elif fMinus is None: bd[k] = -1.0...
s1 = m return s1, g(s1) #provide finite difference derivatives with boundary for a given function f. Boundaries are # determined by the function f returning a None value when it is not defined. def _finite_diff_dfdx_and_bdflag(f, x, delta):
64
64
196
16
48
colibri-coruscans/pyGSTi
pygsti/optimize/customcg.py
Python
_finite_diff_dfdx_and_bdflag
_finite_diff_dfdx_and_bdflag
231
246
231
231
ed708b1dbaa8c6693905b7b769354b1644c99532
bigcode/the-stack
train
0e7e05e0329308318505d7ae
train
function
def _max_within_bracket(g, s1, g1, s2, g2, s3, g3): TOL = 1e-10; FRAC_TOL = 1e-6 assert(s2 - s1 > TOL) # a legit bracket must have s1 < s2 while((abs(s3 - s1) > TOL) and (abs(s3 - s1) > FRAC_TOL * (abs(s3) + abs(s1)))): s4 = s1 + (s3 - s2); g4 = g(s4) #print "DEBUG: Max in brk iter: (",s1,"...
def _max_within_bracket(g, s1, g1, s2, g2, s3, g3):
TOL = 1e-10; FRAC_TOL = 1e-6 assert(s2 - s1 > TOL) # a legit bracket must have s1 < s2 while((abs(s3 - s1) > TOL) and (abs(s3 - s1) > FRAC_TOL * (abs(s3) + abs(s1)))): s4 = s1 + (s3 - s2); g4 = g(s4) #print "DEBUG: Max in brk iter: (",s1,",",g1,") (",s2,",",g2,") (",s3,",",g3,") (",s4,",",g...
s3, g3) print("Warning: maximize_1d could not find bracket") ret = s2 if g2 is not None else s1 # return s2 if it evaluates to a valid point assert(g(ret) is not None) # otherwise return s1, since it should always be valid return ret #TODO: g3 and g1 are unused! def _max_within_bracket(g, s1, g1,...
112
112
376
27
85
colibri-coruscans/pyGSTi
pygsti/optimize/customcg.py
Python
_max_within_bracket
_max_within_bracket
195
214
195
195
80a74853536dc8cff8e45d53d8dc82625a00d9b4
bigcode/the-stack
train
9cfd53ee58da5b139da4bd40
train
class
class TestRegistrationViews(RegistrationsTestBase): def test_node_register_page_not_registration_redirects(self): url = self.node.web_url_for('node_register_page') res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, http.FOUND) @mock.patch('website.archiver.tasks...
class TestRegistrationViews(RegistrationsTestBase):
def test_node_register_page_not_registration_redirects(self): url = self.node.web_url_for('node_register_page') res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, http.FOUND) @mock.patch('website.archiver.tasks.archive') def test_node_register_page_registrati...
httplib as http import pytz from django.utils import timezone from nose.tools import * # noqa PEP8 asserts from framework.exceptions import HTTPError from osf.models import MetaSchema, DraftRegistration from website.project.metadata.schemas import _name_to_id, LATEST_SCHEMA_VERSION from website.util import permiss...
148
148
496
10
137
laurenrevere/osf.io
tests/test_registrations/test_views.py
Python
TestRegistrationViews
TestRegistrationViews
28
86
28
29
71584fbaa855b260fb7bd2c7f3770137a5f75c5e
bigcode/the-stack
train
9cac8da99ea8c9c67d4b094d
train
class
class TestDraftRegistrationViews(RegistrationsTestBase): def test_submit_draft_for_review(self): url = self.draft_api_url('submit_draft_for_review') res = self.app.post_json( url, self.embargo_payload, auth=self.user.auth ) assert_equal(res.status...
class TestDraftRegistrationViews(RegistrationsTestBase):
def test_submit_draft_for_review(self): url = self.draft_api_url('submit_draft_for_review') res = self.app.post_json( url, self.embargo_payload, auth=self.user.auth ) assert_equal(res.status_code, http.ACCEPTED) data = res.json asse...
self.node.save() reg = RegistrationFactory(project=self.node) reg.is_public = True reg.save() url = reg.web_url_for('node_register_page') res = self.app.get(url, auth=None) assert_equal(res.status_code, http.OK) @mock.patch('framework.celery_tasks.handlers.en...
256
256
4,192
11
245
laurenrevere/osf.io
tests/test_registrations/test_views.py
Python
TestDraftRegistrationViews
TestDraftRegistrationViews
89
566
89
90
7d53594a4ea101fa89f8399139e8f09cd46f1582
bigcode/the-stack
train
d6f291f2651a64a8480937ce
train
class
class SourceGenerator(ast.NodeVisitor): """This visitor is able to transform a well formed syntax tree into python sourcecode. For more details have a look at the docstring of the `node_to_source` function. """ def __init__(self): self.result = [] def write(self, x): self.resu...
class SourceGenerator(ast.NodeVisitor):
"""This visitor is able to transform a well formed syntax tree into python sourcecode. For more details have a look at the docstring of the `node_to_source` function. """ def __init__(self): self.result = [] def write(self, x): self.result.append(x) def body(self, stateme...
.Gt] = '>' CMPOP_SYMBOLS[ast.GtE] = '>=' CMPOP_SYMBOLS[ast.Is] = 'is' CMPOP_SYMBOLS[ast.IsNot] = 'is not' CMPOP_SYMBOLS[ast.In] = 'in' CMPOP_SYMBOLS[ast.NotIn] = 'not in' def fix_feat_name(x): return "df[\"%s\"]" % x def to_source(node, updater=fix_feat_name): """This function can convert a node tree back i...
229
229
764
7
222
vuphan314/dpo
addmc/libraries/cryptominisat/scripts/crystal/crystalcodegen.py
Python
SourceGenerator
SourceGenerator
75
199
75
75
03abef12e897365d07802cc6663b8a6a46039009
bigcode/the-stack
train
af623cc990b37498b410e1dc
train
function
def to_source(node, updater=fix_feat_name): """This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you're dealing with custom asts not generated by python itself. It could be that the sourcecode is evaluable when the AST itself is not ...
def to_source(node, updater=fix_feat_name):
"""This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you're dealing with custom asts not generated by python itself. It could be that the sourcecode is evaluable when the AST itself is not compilable / evaluable. The reason for ...
.IsNot] = 'is not' CMPOP_SYMBOLS[ast.In] = 'in' CMPOP_SYMBOLS[ast.NotIn] = 'not in' def fix_feat_name(x): return "df[\"%s\"]" % x def to_source(node, updater=fix_feat_name):
64
64
131
11
52
vuphan314/dpo
addmc/libraries/cryptominisat/scripts/crystal/crystalcodegen.py
Python
to_source
to_source
59
73
59
59
7519dcee4d25be5229e773617b7bd3499750bdae
bigcode/the-stack
train
5afa33bf99f4da5eda24d7a1
train
function
def fix_feat_name(x): return "df[\"%s\"]" % x
def fix_feat_name(x):
return "df[\"%s\"]" % x
E] = '>=' CMPOP_SYMBOLS[ast.Is] = 'is' CMPOP_SYMBOLS[ast.IsNot] = 'is not' CMPOP_SYMBOLS[ast.In] = 'in' CMPOP_SYMBOLS[ast.NotIn] = 'not in' def fix_feat_name(x):
64
64
19
6
58
vuphan314/dpo
addmc/libraries/cryptominisat/scripts/crystal/crystalcodegen.py
Python
fix_feat_name
fix_feat_name
55
56
55
55
13dbf018709858c5d3f34943e0b17d7644e321fb
bigcode/the-stack
train
e1e850ac232ebb36ced4581e
train
class
class Generator_z_Listy: def __init__(self,nn): self.__n=nn self.__i=-1 self.__lista=['majonez','oliwki', 'kiełbasa', 'sok','kotlet'] def __iter__(self): return self def __next__(self): self.__i+=1 if self.__i>len(self.__lista)-1 or self.__i>self.__n...
class Generator_z_Listy:
def __init__(self,nn): self.__n=nn self.__i=-1 self.__lista=['majonez','oliwki', 'kiełbasa', 'sok','kotlet'] def __iter__(self): return self def __next__(self): self.__i+=1 if self.__i>len(self.__lista)-1 or self.__i>self.__n: raise StopI...
class Generator_z_Listy:
6
64
116
6
0
angelm1974/Bydgoszcz_2_spotkanie
styczen/generator2.py
Python
Generator_z_Listy
Generator_z_Listy
1
15
1
1
aa5266621aebf437bb7c45ce0b435dc410839300
bigcode/the-stack
train
55b1252c046071c9803cad13
train
function
def TellTime(): now = datetime.now() response_text = 'The time is {}:{:02d}'.format(now.hour,now.minute) # Configure speech synthesis # Able to change voice to male RyanNeural vs Female LibbyNeural speech_config.speech_synthesis_voice_name = "en-GB-LibbyNeural" speech_synthesizer = speech_sdk....
def TellTime():
now = datetime.now() response_text = 'The time is {}:{:02d}'.format(now.hour,now.minute) # Configure speech synthesis # Able to change voice to male RyanNeural vs Female LibbyNeural speech_config.speech_synthesis_voice_name = "en-GB-LibbyNeural" speech_synthesizer = speech_sdk.SpeechSynthesize...
else: print(speech.reason) if speech.reason == speech_sdk.ResultReason.Canceled: cancellation = speech.cancellation_details print(cancellation.reason) print(cancellation.error_details) # Return the command return command ''' # Function for speech synthesis ...
64
64
162
4
60
June-Han/AI-102-AIEngineer
07-speech/Python/speaking-clock/speaking-clock.py
Python
TellTime
TellTime
84
100
84
84
fed0cd7ef193700b977d9f080a7bdd4bfcbf9fc1
bigcode/the-stack
train
d5ac46e191b89112903b5622
train
function
def TranscribeCommand(): command = '' ''' # Configure speech recognition using microphone audio_config = speech_sdk.AudioConfig(use_default_microphone=True) speech_recognizer = speech_sdk.SpeechRecognizer(speech_config, audio_config) print('Speak now...') ''' # Configure Speech Rec...
def TranscribeCommand():
command = '' ''' # Configure speech recognition using microphone audio_config = speech_sdk.AudioConfig(use_default_microphone=True) speech_recognizer = speech_sdk.SpeechRecognizer(speech_config, audio_config) print('Speak now...') ''' # Configure Speech Recognition using audiofile ...
service speech_config = speech_sdk.SpeechConfig(cog_key, cog_region) print('Ready to use speech service in:', speech_config.region) # Get spoken input command = TranscribeCommand() if command.lower() == 'what time is it?': TellTime() except Exception as ex: ...
77
77
258
5
72
June-Han/AI-102-AIEngineer
07-speech/Python/speaking-clock/speaking-clock.py
Python
TranscribeCommand
TranscribeCommand
43
79
43
43
ebb356bb365f1050986fbf6068991679e6808693
bigcode/the-stack
train
ea359c8308a186a6cdeacc97
train
function
def main(): try: global speech_config # Get Configuration Settings load_dotenv() cog_key = os.getenv('COG_SERVICE_KEY') cog_region = os.getenv('COG_SERVICE_REGION') # Configure speech service speech_config = speech_sdk.SpeechConfig(cog_key, cog_region) ...
def main():
try: global speech_config # Get Configuration Settings load_dotenv() cog_key = os.getenv('COG_SERVICE_KEY') cog_region = os.getenv('COG_SERVICE_REGION') # Configure speech service speech_config = speech_sdk.SpeechConfig(cog_key, cog_region) print('Re...
based on the Twelve-Factor App methodology. ''' from email.mime import audio from fileinput import filename from dotenv import load_dotenv from datetime import datetime import os from playsound import playsound # Import namespaces import azure.cognitiveservices.speech as speech_sdk def main():
64
64
122
3
60
June-Han/AI-102-AIEngineer
07-speech/Python/speaking-clock/speaking-clock.py
Python
main
main
22
41
22
22
bb9b44e11ae01613ee05246cc42752aad9d95e2e
bigcode/the-stack
train
9edc8d711a326c43cf7fc7c7
train
function
def generate_lhs(npoints, ndim, seed): """ Generate a maximin Latin-hypercube sample (LHS) with the given number of points, dimensions, and random seed. """ logging.debug( 'generating maximin LHS: ' 'npoints = %d, ndim = %d, seed = %d', npoints, ndim, seed ) cachefi...
def generate_lhs(npoints, ndim, seed):
""" Generate a maximin Latin-hypercube sample (LHS) with the given number of points, dimensions, and random seed. """ logging.debug( 'generating maximin LHS: ' 'npoints = %d, ndim = %d, seed = %d', npoints, ndim, seed ) cachefile = ( cachedir / 'lhs' / ...
This means that R must be installed with the lhs package (run ``install.packages('lhs')`` in an R session). """ import itertools import logging from pathlib import Path import re import subprocess import numpy as np from . import cachedir, parse_system, keys, labels, ranges, design_array, systems def genera...
83
83
277
11
71
FHead/hic-param-est-2017
src/design.py
Python
generate_lhs
generate_lhs
33
74
33
33
c3b699269b892c0d542d1af72b9e8b9f6631a25f
bigcode/the-stack
train
dcc54a1529379324e1a83683
train
class
class Design: """ Latin-hypercube model design. Creates a design for the given system with the given number of points. Creates the main (training) design if `validation` is false (default); creates the validation design if `validation` is true. If `seed` is not given, a default random seed is ...
class Design:
""" Latin-hypercube model design. Creates a design for the given system with the given number of points. Creates the main (training) design if `validation` is false (default); creates the validation design if `validation` is true. If `seed` is not given, a default random seed is used (differen...
LHS) with the given number of points, dimensions, and random seed. """ logging.debug( 'generating maximin LHS: ' 'npoints = %d, ndim = %d, seed = %d', npoints, ndim, seed ) cachefile = ( cachedir / 'lhs' / 'npoints{}_ndim{}_seed{}.npy'.format(npoints, ndim, ...
256
256
2,792
3
252
FHead/hic-param-est-2017
src/design.py
Python
Design
Design
77
320
77
77
736e5126d99304bd3035c35096a82b91380ec3e5
bigcode/the-stack
train
19ea470216e1aeccfab8c223
train
class
class AppRegistrationAndOauthMigrationController(BaseController): """A Controller to access Endpoints in the finicityapi API.""" def set_customer_application_id(self, customer_id, application_id): """Does a PUT request to...
class AppRegistrationAndOauthMigrationController(BaseController):
"""A Controller to access Endpoints in the finicityapi API.""" def set_customer_application_id(self, customer_id, application_id): """Does a PUT request to /aggregation/v1/customers/{customerId}/applications/{applicationId}....
# -*- coding: utf-8 -*- from finicityapi.api_helper import APIHelper from finicityapi.configuration import Configuration from finicityapi.controllers.base_controller import BaseController from finicityapi.http.auth.custom_header_auth import CustomHeaderAuth from finicityapi.models.app_registration_response impor...
98
256
2,267
10
87
monarchmoney/finicity-python
finicityapi/controllers/app_registration_and_oauth_migration_controller.py
Python
AppRegistrationAndOauthMigrationController
AppRegistrationAndOauthMigrationController
11
307
11
12
6d313f665e594e859a96efa01361a9f822ae18ae
bigcode/the-stack
train
4a5f35e9e668c46e54f88406
train
function
def _stream_container_events_and_logs(container_group_client, container_client, resource_group_name, name, container_name): """Stream container events and logs. """ lastOutputLines = 0 lastContainerState = None while True: container_group, container = _find_container(container_group_client, res...
def _stream_container_events_and_logs(container_group_client, container_client, resource_group_name, name, container_name):
"""Stream container events and logs. """ lastOutputLines = 0 lastContainerState = None while True: container_group, container = _find_container(container_group_client, resource_group_name, name, container_name) container_state = 'Unknown' if container.instance_view and containe...
'{}' was just restarted; the tail of the current log might be missing. Exiting...".format(restart_policy, container_name)) break _move_console_cursor_up(lastOutputLines) print(log.content) lastOutputLines = currentOutputLines time.sleep(2) def _stream_container_events_and_...
83
83
278
23
60
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_stream_container_events_and_logs
_stream_container_events_and_logs
795
826
795
795
0bceda548fc3bfae004785c54dcd5c0b5aaa2a3f
bigcode/the-stack
train
9ae571e73a28886067af9816
train
function
def _get_vnet_network_profile(cmd, location, resource_group_name, vnet, vnet_address_prefix, subnet, subnet_address_prefix): from azure.cli.core.profiles import ResourceType from msrestazure.tools import parse_resource_id, is_valid_resource_id aci_delegation_service_name = "Microsoft.ContainerInstance/cont...
def _get_vnet_network_profile(cmd, location, resource_group_name, vnet, vnet_address_prefix, subnet, subnet_address_prefix):
from azure.cli.core.profiles import ResourceType from msrestazure.tools import parse_resource_id, is_valid_resource_id aci_delegation_service_name = "Microsoft.ContainerInstance/containerGroups" Delegation = cmd.get_models('Delegation', resource_type=ResourceType.MGMT_NETWORK) aci_delegation = Dele...
entities_info(identities): identities = identities or [] identity_type = ResourceIdentityType.none if not identities or MSI_LOCAL_ID in identities: identity_type = ResourceIdentityType.system_assigned external_identities = [x for x in identities if x != MSI_LOCAL_ID] if external_identities a...
256
256
967
29
226
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_get_vnet_network_profile
_get_vnet_network_profile
260
351
260
260
7407daed4f63bcfac7fbc0d1a98bb1d5c3708f7c
bigcode/the-stack
train
28ca9e444b65d17bcf903a1e
train
function
def _move_console_cursor_up(lines): """Move console cursor up. """ if lines > 0: # Use stdout.write to support Python 2 sys.stdout.write('\033[{}A\033[K\033[J'.format(lines))
def _move_console_cursor_up(lines):
"""Move console cursor up. """ if lines > 0: # Use stdout.write to support Python 2 sys.stdout.write('\033[{}A\033[K\033[J'.format(lines))
c for c in container_group.containers if c.name == container_name] if len(containers) != 1: raise CLIError("Found 0 or more than 1 container with name '{}'".format(container_name)) return container_group, containers[0] def _move_console_cursor_up(lines):
64
64
53
8
56
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_move_console_cursor_up
_move_console_cursor_up
861
865
861
861
e835c51d90fade308421c483b8227a07f74fc646
bigcode/the-stack
train
9e0de0f75e806f5f1abee507
train
function
def _start_streaming(terminate_condition, terminate_condition_args, shupdown_grace_period, stream_target, stream_args): """Start streaming for the stream target. """ import colorama colorama.init() try: t = threading.Thread(target=stream_target, args=stream_args) t.daemon = True ...
def _start_streaming(terminate_condition, terminate_condition_args, shupdown_grace_period, stream_target, stream_args):
"""Start streaming for the stream target. """ import colorama colorama.init() try: t = threading.Thread(target=stream_target, args=stream_args) t.daemon = True t.start() while not terminate_condition(*terminate_condition_args) and t.is_alive(): time.sleep(10...
updown_grace_period=5, stream_target=_stream_container_events_and_logs, stream_args=(container_group_client, container_client, resource_group_name, name, container_name)) def _start_streaming(terminate_condition, terminate_condition_args, shupdown_grace_period, stream_target, stream_args):
64
64
115
26
38
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_start_streaming
_start_streaming
756
772
756
756
9c8f1fc2cfd82875612f1a406f6563316153fdd0
bigcode/the-stack
train
1a2e581a665cccea6f7714d0
train
function
def _get_resource(client, resource_group_name, *subresources): from azure.core.exceptions import HttpResponseError try: resource = client.get(resource_group_name, *subresources) return resource except HttpResponseError as ex: if ex.error.code == "NotFound" or ex.error.code == "Resour...
def _get_resource(client, resource_group_name, *subresources):
from azure.core.exceptions import HttpResponseError try: resource = client.get(resource_group_name, *subresources) return resource except HttpResponseError as ex: if ex.error.code == "NotFound" or ex.error.code == "ResourceNotFound": return None raise
identity_type = ResourceIdentityType.user_assigned identity = ContainerGroupIdentity(type=identity_type) if external_identities: identity.user_assigned_identities = {e: {} for e in external_identities} return identity def _get_resource(client, resource_group_name, *subresources):
64
64
79
14
49
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_get_resource
_get_resource
249
257
249
249
3ed5d23f62acfd285217b94c092fa9809ff1a394
bigcode/the-stack
train
38ef889c0e84321f43aece28
train
function
def _create_resource_requirements(cpu, memory): """Create resource requirements. """ if cpu or memory: container_resource_requests = ResourceRequests(memory_in_gb=memory, cpu=cpu) return ResourceRequirements(requests=container_resource_requests)
def _create_resource_requirements(cpu, memory):
"""Create resource requirements. """ if cpu or memory: container_resource_requests = ResourceRequests(memory_in_gb=memory, cpu=cpu) return ResourceRequirements(requests=container_resource_requests)
_wait(no_wait, resource_client.resources.begin_create_or_update, resource_group_name, "Microsoft.ContainerInstance", '', "containerGroups", name, api_version, ...
64
64
52
10
53
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_create_resource_requirements
_create_resource_requirements
420
424
420
420
de2c96d7fcc81df92301f028a60b7aafa560a588
bigcode/the-stack
train
d87326d57d6d92f594649ede
train
function
def get_container(client, resource_group_name, name): """Show details of a container group. """ return client.get(resource_group_name, name)
def get_container(client, resource_group_name, name):
"""Show details of a container group. """ return client.get(resource_group_name, name)
_ID = '[system]' def list_containers(client, resource_group_name=None): """List all container groups in a resource group. """ if resource_group_name is None: return client.list() return client.list_by_resource_group(resource_group_name) def get_container(client, resource_group_name, name):
64
64
31
11
53
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
get_container
get_container
59
61
59
59
997e60bee802672a6ed21205c08bcc60739a6c05
bigcode/the-stack
train
af0251095ce374f4a4e4d5ea
train
function
def _create_secrets_volume(secrets): """Create secrets volume. """ return Volume(name=SECRETS_VOLUME_NAME, secret=secrets) if secrets else None
def _create_secrets_volume(secrets):
"""Create secrets volume. """ return Volume(name=SECRETS_VOLUME_NAME, secret=secrets) if secrets else None
_name=azure_file_volume_share_name, storage_account_name=azure_file_volume_account_name, storage_account_key=azure_file_volume_account_key) return Volume(name=AZURE_FILE_VOLUME_NAME, azure_file=azure_file_volume) if azure_file_...
64
64
37
9
54
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_create_secrets_volume
_create_secrets_volume
490
492
490
490
f36e0e2b3a2195a9a3c151968c175aea31626aae
bigcode/the-stack
train
f4b4275da6ab9b6dbbfca9d9
train
function
def _create_secrets_volume_mount(secrets_volume, secrets_mount_path): """Create secrets volume mount. """ if secrets_volume: if not secrets_mount_path: raise CLIError('Please specify --secrets --secrets-mount-path ' 'to enable secrets volume mount.') return...
def _create_secrets_volume_mount(secrets_volume, secrets_mount_path):
"""Create secrets volume mount. """ if secrets_volume: if not secrets_mount_path: raise CLIError('Please specify --secrets --secrets-mount-path ' 'to enable secrets volume mount.') return VolumeMount(name=SECRETS_VOLUME_NAME, mount_path=secrets_mount_path)
--azure-file-volume-share-name --azure-file-volume-account-name --azure-file-volume-account-key ' 'to enable Azure File volume mount.') return VolumeMount(name=AZURE_FILE_VOLUME_NAME, mount_path=azure_file_volume_mount_path) def _create_secrets_volume_mount(secrets_volume, secrets_mo...
64
64
80
15
49
guilhem/azure-cli
src/azure-cli/azure/cli/command_modules/container/custom.py
Python
_create_secrets_volume_mount
_create_secrets_volume_mount
512
518
512
512
6a21b4bbe917a5ad369ba38c098c87daaa0b48d6
bigcode/the-stack
train