id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
0089cbf01a32ad31cd6b | def to_txt_file(self, txt_file):
from pathlib import Path
path = Path(txt_file).expanduser().resolve().with_suffix(".txt")
path.mkdir(parents=True, exist_ok=True)
with path.open("w") as f:
f.write(self.to_txt() + "\n") | |
0089e2fb056a2ee34158 | def get_feeds(tid: int) -> List:
return list(rss_feeds.find({"tid": tid})) | |
0089fa2072862b6026b6 | def font_sizes(context):
return {
'ratio': context['request'].user.profile.font_ratio
} | |
008a0c1721932f50b453 | def game_card_poker_winner(hand1: "List of Cards with Player 1",hand2: "List of Cards with Player 1") -> 'Returns the number of player who won':
winner = 'Its a tie both players share the pot'
check1 = all(item in deck for item in hand2)
check2 = all(item in deck for item in hand2)
if len(hand1) == len... | |
008a14e9fe119c30916b | def index(request):
if request.user.is_authenticated():
return HttpResponseRedirect("/dashboard/")
else:
return render(request, 'index.html') | |
008a7ba2a8679dde53a4 | def confirm(self, block, tx, netParams):
self.height = block.height
self.maturity = (
block.height + netParams.CoinbaseMaturity if tx.looksLikeCoinbase() else 0
)
self.ts = block.timestamp | |
008a832bbe3313ea88e9 | def test_eu_setup_partial_config(self, mock_round, mock_evo):
config = {
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
honeywell.CONF_REGION: "eu",
}
mock_evo.return_value.temperatures.return_value = [{"id": "foo"}, {"id": "bar"}]
hass = mock.MagicMo... | |
008a9097239b6fbfbfec | def push(self, branch):
phlgit_push.push(self._clone, branch, self._remote) | |
008aa7ed0d9a5fbf5276 | def time_step():
return 0.03125 | |
008ab10f803c29e2d469 | def format_to_ext(format):
return {
constants.JPEG: 'jpg',
constants.PNG: 'png',
constants.SVG: 'svg',
}[format] | |
008ab95731cf69eccb57 | def set_secure_boot_mode(self, secure_boot_enable):
self._change_secure_boot_settings('SecureBootEnable',
secure_boot_enable) | |
008acb6ddafeefb00573 | def cartesian(arrays, out=None):
arrays = [asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = prod([x.size for x in arrays])
if out is None:
out = zeros([n, len(arrays)], dtype=dtype)
m = n / arrays[0].size
out[:,0] = repeat(arrays[0], m)
if arrays[1:]:
cartesian(array... | |
008ae23a90c956e3ef4d | def test_validate_invalid_transition_state(self) -> None:
with self.assertRaises(exceptions.InvalidStateError):
MNTM(
states={"q0", "q1"},
input_symbols={"0", "1"},
tape_symbols={"0", "1", "#"},
n_tapes=2,
transitions={
... | |
008afd960c0847e62687 | def main(args):
seq_dirs = args.sequence_dirs
seqs = []
fraction = args.fraction
for seq_dir in os.listdir(seq_dirs):
seq_dir = os.path.join(seq_dirs,seq_dir)
for f in os.listdir(seq_dir):
# ncbi genomes end with fna
if f.endswith(".fna"):
with ope... | |
008b01cdf76954fe0e13 | def on_msg(self, callback):
self._msg_callback = callback | |
008b07aaf57afe121adf | def generate_char():
return chr(np.random.randint(35, 126)) | |
008b1949faca7fd73658 | def getparser(self):
return getparser() | |
008b40056d3c7433e4c0 | def aggregate_logging_outputs(logging_outputs):
ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)
nsentences = sum(log.get('nsentences', 0) for log in logging_outputs)
sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)
return {
'loss': sum(l... | |
008b54dce180566b584d | def ping(host):
import os, platform
# Ping parameters as function of OS
ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1"
# Ping
return os.system("ping " + ping_str + " " + host) == 0 | |
008b5f597bc0346e57fa | def test_patch_unpatch_unpatch_import(self):
self.__patch_func__()
self.__unpatch_func__()
self.__unpatch_func__()
module = importlib.import_module(self.__module_name__)
self.assert_not_module_patched(module) | |
008b8d5457779ea47fe1 | def generateKeys(key):
# Inititalizing variables required
keys = []
key = stringToBitArray(key)
# Initial permutation on key
key = permutation(key, keyPermutationMatrix1)
# Split key in to (leftBlock->LEFT), (rightBlock->RIGHT)
leftBlock, rightBlock = nSplit(key, 28)
# 16 rounds of k... | |
008bb44ac11c0839f338 | def pool(pool_id):
response = check_fsid('cluster/', '/pool/' + str(pool_id), parse_pools)
return response | |
008bca4d253880cc711d | def get_iam_policy(
self,
request: compute.GetIamPolicyInstanceRequest,
*,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Policy:
# TODO(yon-mg): need to handle grpc transcoding and parse url correctly
# current impl assumes basic case of grpc t... | |
008bcc7b9abe7ec4d78c | def test_no_clones(self):
index_entries_x = self.generate_entries("x", 2, 0)
self.test_clone_index.add_index_entries(index_entries_x)
new_file_index_entries = self.generate_entries("y", 2, 2)
detector = CloneDetector(self.test_clone_index)
results: List[CloneGroup] = det... | |
008bea1f9138ff795112 | def __init__(self, elist: list):
self.elist = elist
self.node_names = list(set([s for s, t, w in elist] + [t for s,t,w in elist]))
self.nodes = {s:node(s) for s in self.node_names}
self.create_graph() | |
008bedbc04cca7f7c204 | def isOnBoard(x, y):
return x >= 0 and x <= 7 and y >= 0 and y <=7 | |
008c1091647ad4d0fc09 | def _create_protocol(self):
self.use_udp = True
return self | |
008c35b3b07ed8fdf3a8 | def print_port_description(port_descr, port_name, port_range_hints):
def port_type_str(port_descr):
res = ""
if LadspaConsts.is_port_input(port_descr) and LadspaConsts.is_port_output(port_descr):
res += "ERROR: INPUT AND OUTPUT, "
elif LadspaConsts.is_port_input(port_descr):
... | |
008c3ad50683436cc582 | def context_from_mentions(mentions):
return [m['id'] for m in mentions if m['choice_id'] == 'present'] | |
008c48e95f3e75f0d4af | def get_access_token_from_code(self, code):
url_parts = ('https', self.server, '/goauth/token', None, None)
result = token_utils.request_access_token(self.client,
self.client_secret, code, urlparse.urlunsplit(url_parts))
return (
result.access_token,
... | |
008c4a1ca0ff6f5275de | def sign(cls, ec, message, privateNumber):
# Calculate e = HASH(m). (Here HASH is a cryptographic hash function,
# SHA-256, with the output converted to an integer)
hashMessage_temp = cls.sha256(str(message))
hashMessage = ''.join(str(w) for w in hashMessage_temp)
# Conve... | |
008c68f063233d2460fc | def send_result_spell_check(update: Update, _: CallbackContext) -> None:
if update.message is not None and update.message.text is not None:
update.message.reply_text(
"Tunggu sebentar ya.",
reply_to_message_id=update.message.message_id,
)
user_text = update.message.te... | |
008c6e948c78879effff | def compute_spectrogram(self, waveform, *args):
s = self._settings
# Compute STFT. To use `tf.signal.stft`, we must add a leading
# unit dimension to the waveform tensor. After the call to
# `tf.signal.stft` we effectively remove the corresponding
# dimension ... | |
008c84d2eb115b2d18d4 | def get_min_freq(self):
return _analog_swig.pll_carriertracking_cc_sptr_get_min_freq(self) | |
008c8c9564526efccee9 | def test_sample_params_error():
params = dict(teff=20000, logg=4)
try:
Synfit({'vrot': [10, 20, 2, 5]}, **params)
except KeyError:
pass | |
008c8e4e05fff39b54c2 | def get_atom_symbol(self):
return self.get_property("atom_symbol") | |
008c909607284e0ccf90 | def get_met_data_wg(d, Ndays):
# declare empty arrays for output
ppfd = np.zeros((Ndays, 48))
tdays = np.zeros((Ndays, 48))
precip = np.zeros((Ndays, 48))
vpd = np.zeros((Ndays, 48))
u = np.zeros((Ndays, 48))
for i in range(Ndays):
doy = d.doy + float(i)
if i == 0:
... | |
008c92826e304d54802f | def thermal_comfort_prediction(clo_insulation,metabolic_rate,air_temparature,relative_humidity,air_velocity):
vect= np.array([[clo_insulation,metabolic_rate,air_temparature,relative_humidity,air_velocity]]).reshape((1,-1))
# vect= transformer.transform([[clo_insulation,metabolic_rate,air_temparature,relativ... | |
008cc0a6ad1c1b949d53 | def get_price_spread(price_a = 0.0, price_b = 0.0):
prices = [price_a, price_b]
price_a = max(prices)
price_b = min(prices)
try:
pips = price_increments.index(price_a) - price_increments.index(price_b)
return pips
except:
msg = 'INVALID PRICE INCREMENT!'
raise Excepti... | |
008ccda17399aa42b632 | def downcast_dtypes(df: pd.DataFrame):
float_cols = [c for c in df if df[c].dtype == "float64"]
int_cols = [c for c in df if df[c].dtype == "int64"]
df[float_cols] = df[float_cols].astype(np.float32)
df[int_cols] = df[int_cols].astype(np.int32)
return df | |
008d0f835f7b128868da | def manual_mean(arr):
sum = 0
for i in xrange(0,arr.shape[0]):
for j in xrange(0,arr.shape[1]):
sum = sum+arr[i,j]
return sum / arr.size | |
008d1a8ad832a26425ec | def pc_output_buffers_full_avg(self, *args) -> "std::vector< float,std::allocator< float > >":
return _analog_swig.vectornoise_source_sptr_pc_output_buffers_full_avg(self, *args) | |
008d2b2d8c5f977ace2a | def frequencyToIndex(self, f):
return np.int(f * 2 / self.fs * self.spec.size) | |
008d4dcbb9d5bee03593 | def build_query(self):
... | |
008d6606b3843c2c1f0c | def add_parameter():
parameter_info = {}
argget = utils.create_common_parameter_list()
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
return parameter_info | |
008d7590aebe1a46d9c2 | def test_is_teacher(self):
self.course.add_teachers(self.student2)
result = self.course.is_teacher(self.student2)
self.assertTrue(result) | |
008d7b96186955afd7de | def create(request):
if request.method != "POST":
return HttpResponseNotAllowed(["POST"])
data = json.loads(request.body.decode('utf-8'))
if debug:
pprint(data)
if 'agent_type' not in data or data['agent_type'] is None:
print("request body missing 'agent_type'")
return... | |
008d7e0777c059fb637f | def get_default_lens():
for lens in get_all_lenses():
if lens.default:
return lens
raise ValueError("You must declare one Lens to be the default") | |
008d862c39ccbb544f90 | def term_id(self) -> pulumi.Input[str]:
return pulumi.get(self, "term_id") | |
008d8becdc2aa15f9394 | def file_name(self, file_name: str):
self._file_name = file_name | |
008db846097121fc2e93 | def to_dict(self):
return {
'error': {
'code': self.status_code,
'message': self.message,
'type': str(self.__class__.__name__)
}
} | |
008db973f69b83c74596 | def _generate_expressions(cls, op, value, attr, target_type, full_data_key,
gettext):
_ = gettext
try:
if op == "$lt":
expression = attr < cls.convert_to_alchemy_type(
value, target_type)
elif op == "$lte":
... | |
008de1a8e78d3703cc4b | def convert_coord(df):
## convert the coordinates
df['x'] = df['x'].apply(lambda x: change_dims(x, 0, 100, 0, 104))
df['y'] = df['y'].apply(lambda y: change_dims(y, 0, 100, 0, 68))
df['endX'] = df['endX'].apply(lambda x: change_dims(x, 0, 100, 0, 104))
df['endY'] = df['endY'].apply(lambda y... | |
008df0915b0e4c6c209e | def prepare_validation_error(message):
return "{} {}".format(cli.error_messages['VALIDATION'], message) | |
008e02eafcfed50fcae2 | def on_start_put_in_queue(self):
db = openerp.sql_db.db_connect(self.db_name)
cr = db.cursor()
with Session(cr, openerp.SUPERUSER_ID, self.registry) as session:
cr.execute("SELECT uuid FROM jobs_storage "
"WHERE state in ('queued', 'started') "
... | |
008e276814c1b8931e02 | def _create_user(self, username, email, password, **extra_fields):
if not email:
raise ValueError('The given email must be set')
if not username:
raise ValueError('The given username must be set')
if not password:
raise ValueError('There must be a password')
... | |
008e280685c6c3f0e0f3 | def test_full_function(response_get_monkeypatch, sample_data, sample_processed_result):
response_get_monkeypatch(sample_data)
# Run the method in question
df = spin.statcast_pitcher_spin(start_dt="2019-07-01", end_dt="2019-07-31", player_id=506433)
# Columns needed to be checked
target_columns = ... | |
008e2ed67560ba882bac | def send_obj(self, obj, dst):
raise NotImplementedError("send_obj is not implemented") | |
008e45f79529f56a8711 | def size(self) -> int:
if self.root is None:
return 0
node = self.root
count = [0, 0]
self.count_node_leaves(node, count)
return count[0] | |
008e52903cb979422df8 | def training(func):
return _training_mode(func, True) | |
008e54faf31d27d3dd8d | def delete_queue(self, name: str): | |
008e669d62d9952163ef | def name2digits(name):
name = name.lower()
if len(name)>25:
name = name[0:25]
primenumbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
n = len(name)
s = 0.0
for i in range(n):
s += primenumbers[i] * ord(name[i])*2.0**(i+1)
import scipy.io.matlab
Da... | |
008ed72f429eb70aecd8 | def init_weights(self):
return None | |
008ee800490272aee9f9 | def create_dir(path):
if not os.path.exists(path):
os.makedirs(path) | |
008eee975e91753e571f | def append_to_file(file_name, data):
with open(file_name, 'a+') as f:
f.write('\n'.join(data)) | |
008ef0077aec473f2bda | def test_no_red(pytester):
pytester.copy_example("examples/test_example_simple.py")
result = pytester.runpytest("--color=no")
result.assert_outcomes(failed=1, passed=1)
result.stdout.fnmatch_lines(
[
"*FAILURE: assert*", # no red before assert
],
)
result.stdout.no_f... | |
008f251d7bfca2113eef | def how_to_compare():
for prot in prot_seq.index:
comparison_function = one_prot_all_shifts(prot, (input_data, prot_seq))
# The title and y axis labels that come out of one_prot_all_shifts are ignored.
_, result_df = turn_into_dataframe(comparison_function)
h... | |
008f260b187f769bbd7b | def test_replace_labels(self):
self.auto_login()
cassette_name = self.cassette_name("replace_labels")
with self.recorder.use_cassette(cassette_name):
issue = self.gh.issue(
username="sigmavirus24", repository="github3.py", number=509
)
labels =... | |
008f5ed53d5192d30b47 | def handle_reply_to(self, api, command):
content = command['content']
continue_session = command.get('continue_session', True)
orig_msg = api.get_inbound_message(command['in_reply_to'])
d = self.app_worker.reply_to(orig_msg, content,
continue_ses... | |
008f66efae6b9585e32b | def _buildNetwork(self):
#Core Network (reusable)
conv1 = self._convLayer(self.obsPH, filterDims = 8, outputFilters = 16, strides = 4,name="conv1", activation = tf.nn.relu)
conv2 = self._convLayer(conv1 , filterDims = 4, outputFilters = 32, strides = 2,name="conv2", activation = tf.nn.r... | |
008f963c1c7320151ea1 | def test_1drule_1eth_already_complete(self):
cur_eth0 = MACPCI("00:13:72:2d:2a:ec", "0000:04:00.0", "eth0")
drule_eth0 = MACPCI("00:13:72:2d:2a:ec", "0000:04:00.0", None, "eth0")
cur_state = [cur_eth0]
ts = rename_logic([],
deepcopy(cur_state),
... | |
008fa2dd70b316f8f014 | def get_stage_model(self, stage):
if stage == "classifier":
return self.classifier
elif stage == "generator":
return self.generator
if stage == "discriminator":
return self.discriminator | |
008fc6fac5f1b66c3ead | def detail_type(self, detail_type):
self._detail_type = detail_type | |
008fd1f087f49262edee | def __init__ (self) :
BatchJob.__init__(self)
QtCore.QObject.__init__(self, None)
self.job_id_cora_split = None
self.time_sub_split = None
self.job_id_cora_merge = None
self.time_sub_merge = None
self.nparts = None
self.init_list_for_p... | |
008fd3fa209d85d2c328 | def end_work_signal_received():
return _TERMINATION_SIGNAL_RECEIVED | |
0090100708775dcc4a88 | def mint_centrality_for_graph(G): | |
00903bc8e0986b866edb | def root(self):
return self._root(self._ptr) | |
00905b268a7e4664be51 | def extract(
spark: SparkSession,
file_paths: Dict,
) -> Tuple[DataFrame, DataFrame]:
generic_events = spark.read.json(
path=file_paths['generic_events'],
schema=generic_event_schema)
app_loading_events = generic_events\
.filter("event = 'app_loaded'")\
.select(
... | |
0090755c9c793a21b0d4 | def _make_header(metadata):
if use_fitsio:
hdr = fitsio.FITSHDR(metadata)
else:
if metadata is None:
hdr = fits.Header()
else:
hdr = fits.Header(metadata)
return hdr | |
00908d15057023af61da | def add_control_node(self, x, y):
controlNode = Particle(x, y, control=True, fixed=True)
if min(particle.dist(controlNode) for particle in self.particles) > self.eta:
self.particles.append(controlNode) | |
0090908084bfc61c008d | def load_medialive_state(self, state):
channelStatus = self.channel.check_status()
if channelStatus == None:
if state != "NONE":
self.set_state("NONE", "state missmatch! Adopting medialive state: NONE")
elif channelStatus == "IDLE":
if not (state == "C... | |
00909d3294138345cd40 | def writeScript(self, script):
from pkg_resources import resource_string
tpl_name = 'data/ScriptTestCase.tpl'
trace('Creating script: %s.\n' % self.script_path)
tpl = resource_string('collective.funkload', tpl_name)
content = tpl % {'script': script,
... | |
0090ab80d1467d7c2814 | def deWarp(self):
# If Gaussian filter is specified, set the flag accordingly. Compute the flow field.
if self.configuration.use_gaussian_filter:
flow = cv2.calcOpticalFlowFarneback(self.gui.image_reference_8bit_gray,
self.gui.image_rigid_tran... | |
0090c05102dc16b5286a | def key(self):
return self.req.access_token | |
009105810e279bb27eec | def vector_get_request(self, node, vectors):
pass | |
00910ca5a149f99ba990 | def processEtcShadow(self):
success = False
#####
# Process /etc/passwd
try:
pass_file = open("/etc/password", 'r')
except OSError as err:
self.logger.log(lp.INFO, "Error trying to acquire /etc/shadow data: " + str(err))
else:
for line ... | |
00912a720bdfa4cc88c6 | def from_failure(
cls: Type[_ResultBasedType], # noqa: N805
inner_value: _SecondType,
) -> KindN[_ResultBasedType, _FirstType, _SecondType, _ThirdType]: | |
009132c17aae10032e71 | def _gather_reassign_parts(self):
reassign_parts = array('I')
if self._remove_devs:
dev_ids = [d['id'] for d in self._remove_devs if d['parts']]
if dev_ids:
for replica in xrange(self.replicas):
part2dev = self._replica2part2dev[replica]
... | |
009138c8b32ae5c9ac4a | def configure_task(self, cfg, train_dataset):
super().configure_task(cfg)
if "task_adapt" in cfg:
if self.data_classes != self.model_classes:
self.configure_task_data_pipeline(cfg)
if cfg["task_adapt"].get("use_adaptive_anchor", False):
self.config... | |
0091552511a2ccdb7541 | def p2a(self, coeff):
# keep a window,
if self._frameNr > 0 :
# keep adding if not yet filled up
self._frameNr -= 1
else:
# if filled up, replace the oldest frame with the current
self._hiPassArray = np.roll(self._hiPassArray, 1, 0)
... | |
00916a8de6d62b3e980d | def n_weight_terms(self): | |
00918c8bf1033dc4aae1 | def classify(self, frame, contours, pir):
classification = False
contour_check = self.check_contours(contours)
# person_prob = self.get_person_prob(frame)
# Decide classification strictly on contour_check
if contour_check:
classification = True
ret... | |
009198c9dbc2719ae7e5 | def __getFiltroFecha(self, especialista_id, fecha):
filtro = {'ee__especialista__id':especialista_id,
'fecha__day':fecha.day,
'fecha__month':fecha.month,
'fecha__year':fecha.year,
'estado':Turno.DISPONIBLE,
}
retur... | |
0091c6b2b181348074e3 | def notify(self, **kwargs):
return self.send(kwargs) | |
0091f74df4a0d89f9cdd | def option(regex):
return nocatch(regex) + '?' | |
009209e62e50bcdd6bf6 | def string_to_int(cls, string, length, vocab):
u = vocab["<unk>"]
if len(string) > length:
string = string[:length]
rep = list(map(lambda x: vocab.get(x, u), string))
if len(string) < length:
rep += [vocab['<pad>']] * (length - len(string))
return rep | |
009213c37f5f41e8cf0d | def createTreeWidgetItem(self, properties, pathFile, fromType, extFile=TestSuite.TYPE,
descriptionTest="", colorTest="", aliasTest="",
testParentId=0, parentCondition="0", control="" ):
# find the parent test according to the id
parentItem = se... | |
00924e14fd3ac67d6e90 | def user_profile() -> object:
if "username" in session:
return redirect("/profile/" + session["username"])
return redirect("/") | |
00925c996321659b6571 | def _preprocess_od_pairs(self): # pylint: disable=too-many-locals, too-many-statements, too-many-branches
# Read the OD pairs into a dataframe for validation, preprocessing, and sorting
pair_table_fields = arcpy.ListFields(self.pair_table)
origin_id_field_type = [f.type for f in pair_table_f... | |
00927829d7dc3b266cb4 | def deleteMatches():
db, cursor = connect()
query = "DELETE from matches;"
cursor.execute(query)
db.commit()
db.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.