text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|>class RuleConditionKeys(models.Model):
name = models.CharField(primary_key=True, max_length=255)
def __str__(self):
return str(self.name)
class Meta:
db_table = 'rule_condition_keys'
verbose_name_plural = 'Rule Condition Keys'
class RuleCondition(models.Model):
... | code_fim | hard | {
"lang": "python",
"repo": "paytm/django-youknowho-app",
"path": "/youknowwhogui/models.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: paytm/django-youknowho-app path: /youknowwhogui/models.py
from django.db import models
from myghanta.fields import MysqlTimeStampField
class RuleTag(models.Model):
tag_name = models.CharField(primary_key=True, max_length=255)
created_at = MysqlTimeStampField(blank=True, auto_now_ad... | code_fim | hard | {
"lang": "python",
"repo": "paytm/django-youknowho-app",
"path": "/youknowwhogui/models.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> RULE_OPERATIONS = (
( '=', 'Equals ( = )'),
( '!=', 'Not Equals ( != )'),
( '>', 'Great than Integer ( > )'),
( '>=', 'Great than Equals Integer( >= )'),
( '<', 'Less than Integer( < )'),
( '<=', 'Less than Equals Integer( <= )'),
('range', 'I... | code_fim | hard | {
"lang": "python",
"repo": "paytm/django-youknowho-app",
"path": "/youknowwhogui/models.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: GAA-UAM/scikit-fda path: /examples/plot_boxplot.py
"""
Boxplot
=======
Shows the use of the functional Boxplot applied to the Canadian Weather
dataset.
"""
# Author: Amanda Hernando Bernabé
# License: MIT
# sphinx_gallery_thumbnail_number = 2
from skfda import datasets
from skfda.exploratory.... | code_fim | hard | {
"lang": "python",
"repo": "GAA-UAM/scikit-fda",
"path": "/examples/plot_boxplot.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>fd_temperatures.plot(group=fdBoxplot.outliers.astype(int),
group_colors=colormap([color, outliercol]),
group_names=["nonoutliers", "outliers"])
##############################################################################
# The curves pointed as outliers are are... | code_fim | hard | {
"lang": "python",
"repo": "GAA-UAM/scikit-fda",
"path": "/examples/plot_boxplot.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>color = 0.3
outliercol = 0.7
fd_temperatures.plot(group=fdBoxplot.outliers.astype(int),
group_colors=colormap([color, outliercol]),
group_names=["nonoutliers", "outliers"])
##############################################################################
# The curv... | code_fim | hard | {
"lang": "python",
"repo": "GAA-UAM/scikit-fda",
"path": "/examples/plot_boxplot.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: vicb1/miscellaneous-notes path: /educational-resources/robotics/gym-gazebo-master/gym_gazebo/utils/ros_utils.py
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from control_msgs.msg import JointTrajectoryControllerState
from baselines.agent.scara_arm.tree_urdf import treeFr... | code_fim | hard | {
"lang": "python",
"repo": "vicb1/miscellaneous-notes",
"path": "/educational-resources/robotics/gym-gazebo-master/gym_gazebo/utils/ros_utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def get_ee_points_velocities(ref_jacobian, ee_points, ref_rot, joint_velocities):
"""
Get the velocities of the points on a link
:param ref_jacobian: 6 x 6 numpy array, jacobian for the link's origin
:param ee_points: N x 3 numpy array, points' coordinates on the link's coordinate system
... | code_fim | hard | {
"lang": "python",
"repo": "vicb1/miscellaneous-notes",
"path": "/educational-resources/robotics/gym-gazebo-master/gym_gazebo/utils/ros_utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Carkib/harvest-balance-calculator path: /domain/harvestPeriod.py
import calendar
from config.loader import load_configuration_file
from httpclient.harvestApi import HarvestApi
from utils.timeUtils import get_number_of_weeks_between_dates
class HarvestPeriod:
<|fim_suffix|> if a_monday >... | code_fim | hard | {
"lang": "python",
"repo": "Carkib/harvest-balance-calculator",
"path": "/domain/harvestPeriod.py",
"mode": "psm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|> if a_monday > a_sunday:
raise RuntimeError('a_monday should be before a_sunday')
return self.api.get_user_time_entries(a_monday, a_sunday)
def get_total_number_of_worked_hours(self):
time_entries = self.get_full_weeks_worked_time_entries(self.begin_monday, self.en... | code_fim | hard | {
"lang": "python",
"repo": "Carkib/harvest-balance-calculator",
"path": "/domain/harvestPeriod.py",
"mode": "spm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|>
elif arg == "-v":
args.remove(arg)
verbose = True
elif arg.startswith("path="):
args.remove(arg)
path = arg.removeprefix("path=")
input = " ".join(args)
output = find(input, path, verbose=verbose, print_txts=print_txts)
... | code_fim | hard | {
"lang": "python",
"repo": "FoggyLight27/simple-regex-file-searcher",
"path": "/main.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: FoggyLight27/simple-regex-file-searcher path: /main.py
import os
from sys import argv
import re
def find(strRegex, startPath, find_first_only=False, print_txts=False, verbose=False):
regex = re.compile(strRegex, re.IGNORECASE)
matches = []
for path, folders, files in os.walk(s... | code_fim | hard | {
"lang": "python",
"repo": "FoggyLight27/simple-regex-file-searcher",
"path": "/main.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: charleskawczynski/SCAMPy path: /src/funcs_thermo.py
import numpy as np
from parameters import *
def sd_c(p_dry, T):
return sd_tilde + cpd*np.log(T/T_tilde) - Rd * np.log(p_dry/p_tilde)
def sv_c(p_vap, T):
return sv_tilde + cpv*np.log(T/T_tilde) - Rv * np.log(p_vap/p_tilde)
def sc_c(L, ... | code_fim | hard | {
"lang": "python",
"repo": "charleskawczynski/SCAMPy",
"path": "/src/funcs_thermo.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> return eps_v * (1.0 - q_tot) * p_vap / (p_0 - p_vap)
def alpha_c(p_0, T, q_tot, q_vap):
return (Rd * T)/p_0 * (1.0 - q_tot + eps_vi * q_vap)
def t_to_entropy_c(p_0, T, q_tot, q_liq, q_ice):
q_vap = q_tot - q_liq - q_ice
p_vap = pv_c(p_0, q_tot, q_vap)
p_dry = pd_c(p_0, q_tot, q_vap... | code_fim | hard | {
"lang": "python",
"repo": "charleskawczynski/SCAMPy",
"path": "/src/funcs_thermo.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> if args_.n_explorer is None:
n_explorer = multiprocessing.cpu_count() - 1
else:
n_explorer = args_.n_explorer
assert n_explorer > 0, "[error] number of explorers must be positive integer"
env = env_fn()
# Manager to share PER between a learner and explorers
SyncMa... | code_fim | hard | {
"lang": "python",
"repo": "Wshoway/tf2rl",
"path": "/tf2rl/algos/apex.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Wshoway/tf2rl path: /tf2rl/algos/apex.py
import time
import numpy as np
import tensorflow as tf
import argparse
import multiprocessing
from multiprocessing import Process, Queue, Value, Event, Lock
from multiprocessing.managers import SyncManager
from cpprb import ReplayBuffer, PrioritizedRepla... | code_fim | hard | {
"lang": "python",
"repo": "Wshoway/tf2rl",
"path": "/tf2rl/algos/apex.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: cohesity/management-sdk-python path: /cohesity_management_sdk/models/map_reduce_instance_run_info.py
# -*- coding: utf-8 -*-
# Copyright 2023 Cohesity Inc.
class MapReduceInstance_RunInfo(object):
"""Implementation of the 'MapReduceInstance_RunInfo' model.
TODO: type description here.
... | code_fim | hard | {
"lang": "python",
"repo": "cohesity/management-sdk-python",
"path": "/cohesity_management_sdk/models/map_reduce_instance_run_info.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> lower_bound = max(0, p - error)
lower_bound = opponent_rating * lower_bound / (1 - lower_bound)
higher_bound = min(1, p + error)
if higher_bound == 1:
higher_bound = math.inf
else:
higher_bound = opponent_rating * higher_bound / (1 - higher_bound)
return estimate... | code_fim | hard | {
"lang": "python",
"repo": "hsahovic/poke-env",
"path": "/src/poke_env/player/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hsahovic/poke-env path: /src/poke_env/player/utils.py
"""This module contains utility functions and objects related to Player classes.
"""
import asyncio
import math
from concurrent.futures import Future
from typing import Dict, List, Optional, Tuple
from poke_env.concurrency import POKE_LOOP
f... | code_fim | hard | {
"lang": "python",
"repo": "hsahovic/poke-env",
"path": "/src/poke_env/player/utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> :param player: The player to evaluate.
:type player: Player
:param n_battles: The total number of battle to perform, including placement
battles.
:type n_battles: int
:param n_placement_battles: Number of placement battles to perform per baseline
player.
:type n_pla... | code_fim | hard | {
"lang": "python",
"repo": "hsahovic/poke-env",
"path": "/src/poke_env/player/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: LokeshAgr1310/BigBucket-Ecommerce-Website path: /shop/migrations/0007_contact_pub_date.py
# Generated by Django 3.2.4 on 2021-07-02 14:39
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
<|fim_suffix|>
dependencies = [
('shop', '0006_al... | code_fim | medium | {
"lang": "python",
"repo": "LokeshAgr1310/BigBucket-Ecommerce-Website",
"path": "/shop/migrations/0007_contact_pub_date.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> dependencies = [
('shop', '0006_alter_contact_phone'),
]
operations = [
migrations.AddField(
model_name='contact',
name='pub_date',
field=models.DateTimeField(default=datetime.datetime(2021, 7, 2, 14, 39, 35, 889989, tzinfo=utc)),
... | code_fim | medium | {
"lang": "python",
"repo": "LokeshAgr1310/BigBucket-Ecommerce-Website",
"path": "/shop/migrations/0007_contact_pub_date.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> sparse_categorical_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
data_loader = MNISTLoader()
num_batches = int(data_loader.num_test_data // self.batch_size)
for batch_index in range(num_batches):
start_index, end_index = batch_index * self.batch_size, ... | code_fim | hard | {
"lang": "python",
"repo": "tangermi/nlp",
"path": "/src/demo/_tensorflow/multilayer_perceptron/evaluation.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tangermi/nlp path: /src/demo/_tensorflow/multilayer_perceptron/evaluation.py
# -*- coding:utf-8 -*-
import tensorflow as tf
from preprocess import MNISTLoader
<|fim_suffix|> sparse_categorical_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
data_loader = MNISTLoader()
... | code_fim | hard | {
"lang": "python",
"repo": "tangermi/nlp",
"path": "/src/demo/_tensorflow/multilayer_perceptron/evaluation.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>t = time.time()
result = comm.gather(result, root=0)
t = time.time() - t
print(rank, "Gather time: ", t, flush=True)
if rank == 0:
t = time.time()
s = 0.0
for i in range(size):
s += result[i]
t = time.time() - t
print("Final Result: ", s, ((N)*(N+1))/2, flush=True)
print("... | code_fim | hard | {
"lang": "python",
"repo": "ut-parla/Parla.py",
"path": "/examples/VECs/kokkos_multiload_example/test_shared_mpi.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ut-parla/Parla.py path: /examples/VECs/kokkos_multiload_example/test_shared_mpi.py
import time
import numpy as np
t = time.time()
from mpi4py import MPI
import kokkos.gpu.core as kokkos
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
kokkos.start(rank)
t = time.time() - t
... | code_fim | hard | {
"lang": "python",
"repo": "ut-parla/Parla.py",
"path": "/examples/VECs/kokkos_multiload_example/test_shared_mpi.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> path = download_url(self.url, self.raw_dir)
# Internal Cell
def data_masks(all_usr_pois, item_tail):
us_lens = [len(upois) for upois in all_usr_pois]
len_max = max(us_lens)
us_pois = [upois + item_tail * (len_max - le) for upois, le in zip(all_usr_pois, us_lens)]
us_msks = [[1] * ... | code_fim | hard | {
"lang": "python",
"repo": "recohut/recohut",
"path": "/recohut/datasets/sample_session.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> train_url = "https://github.com/RecoHut-Datasets/sample_session/raw/v2/train.txt"
test_url = "https://github.com/RecoHut-Datasets/sample_session/raw/v2/test.txt"
all_train_seq_url = "https://github.com/RecoHut-Datasets/sample_session/raw/v2/all_train_seq.txt"
def __init__(self, root, shuf... | code_fim | hard | {
"lang": "python",
"repo": "recohut/recohut",
"path": "/recohut/datasets/sample_session.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: recohut/recohut path: /recohut/datasets/sample_session.py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/datasets/datasets.sample_session.ipynb (unless otherwise specified).
__all__ = ['SampleDataset', 'SampleDatasetv2']
# Cell
from typing import List, Optional, Callable, Union, Any, Tuple
im... | code_fim | hard | {
"lang": "python",
"repo": "recohut/recohut",
"path": "/recohut/datasets/sample_session.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>PGPR Distribution: (k_means, no grad-optim)
ELBO - max: -431.688747, min: -467.903019, median: -455.840175, mean: -455.136209, std: 9.188429.
ACC - max: 0.986486, min: 0.967568, median: 0.977703, mean: 0.978243, std: 0.005036.
NLL - max: 0.091879, min: 0.044205, median: 0.060318, mean: 0.060964, std: 0.... | code_fim | hard | {
"lang": "python",
"repo": "GiovanniPasserello/SHGP",
"path": "/shgp/data/metadata_metrics.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>PGPR Distribution: (uniform subsample, no grad-optim)
ELBO - max: -30.102250, min: -30.634909, median: -30.341378, mean: -30.322743, std: 0.160593.
ACC - max: 1.000000, min: 1.000000, median: 1.000000, mean: 1.000000, std: 0.000000.
NLL - max: 0.028861, min: 0.003745, median: 0.008912, mean: 0.012525, s... | code_fim | hard | {
"lang": "python",
"repo": "GiovanniPasserello/SHGP",
"path": "/shgp/data/metadata_metrics.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: GiovanniPasserello/SHGP path: /shgp/data/metadata_metrics.py
:param num_cycles: The number of times to train a model and average results over.
:param M: The number of inducing points to use.
# SVGP
:param svgp_iters: The number of iterations to train the SVGP model for.
# PGP... | code_fim | hard | {
"lang": "python",
"repo": "GiovanniPasserello/SHGP",
"path": "/shgp/data/metadata_metrics.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@app.route('/api/inputs', methods=['GET', 'PUT'])
@token_required
def input_route(current_user):
logger.debug('inputs route. Method -> ' + request.method)
if not current_user.admin:
logger.debug('No admin user')
return jsonify({"message": "You are not allowed to perform this actio... | code_fim | hard | {
"lang": "python",
"repo": "bopopescu/iRulez",
"path": "/src/webservice/server.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bopopescu/iRulez path: /src/webservice/server.py
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
import jwt
from flask_cors import CORS
import src.irulez.log as log
from src.webservice._user import User
from src.webser... | code_fim | hard | {
"lang": "python",
"repo": "bopopescu/iRulez",
"path": "/src/webservice/server.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> token = auth_header.split(" ")[1]
if not token:
logger.debug('Token not found in Header')
return jsonify({'statusText': 'token is missing!'}), 401
try:
public_key = open('public.key').read()
data = jwt.decode(token, public_key, algori... | code_fim | hard | {
"lang": "python",
"repo": "bopopescu/iRulez",
"path": "/src/webservice/server.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: SHIVJITH/Odoo_Machine_Test path: /addons/google_calendar/controllers/main.py
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
from odoo.addons.google_calendar.utils.google_calendar import Google... | code_fim | hard | {
"lang": "python",
"repo": "SHIVJITH/Odoo_Machine_Test",
"path": "/addons/google_calendar/controllers/main.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Checking that admin have already configured Google API for google synchronization !
client_id = request.env['ir.config_parameter'].sudo().get_param('google_calendar_client_id')
if not client_id or client_id == '':
action_id = ''
if Goo... | code_fim | hard | {
"lang": "python",
"repo": "SHIVJITH/Odoo_Machine_Test",
"path": "/addons/google_calendar/controllers/main.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> train_data = vectorizer.fit_transform(train)
print("Train size {}".format(train_data.shape))
result = classification.fit(model, train_data, train_labels, Parameters.classification)
result_dict['model'] = vectorizer.model_name()
result_dict["{} precision".format(... | code_fim | hard | {
"lang": "python",
"repo": "mrForest13/sentiment-analysis",
"path": "/experiment/ClassificationData.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> vectorizer.clean()
print("Train time {} s".format(round(result.execution_time, 2)))
print("Finish processing for {} and {} ... \n".format(name, vectorizer.model_name()))
return pandas.DataFrame(data=result_dict, index=[0])
uni_gram_bow = predict(BagOfWordsModel(n=1))
bi_gra... | code_fim | hard | {
"lang": "python",
"repo": "mrForest13/sentiment-analysis",
"path": "/experiment/ClassificationData.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mrForest13/sentiment-analysis path: /experiment/ClassificationData.py
import pandas
from classification.Classification import Classification
from experiment.configuration import Parameters
from loader.PreprocessedDataLoader import PreprocessedDataLoader
from plot.Ploter import plot_pie, plot_box... | code_fim | hard | {
"lang": "python",
"repo": "mrForest13/sentiment-analysis",
"path": "/experiment/ClassificationData.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zhiru-liu/microbiome_evolution path: /plos_bio_scripts/calculate_snp_prevalences.py
import sys
import numpy
import bz2
import gzip
import config
import os.path
intermediate_filename_template = config.data_directory+"snp_prevalences/%s.txt.gz"
# Loading file
def parse_snp_prevalences(desire... | code_fim | hard | {
"lang": "python",
"repo": "zhiru-liu/microbiome_evolution",
"path": "/plos_bio_scripts/calculate_snp_prevalences.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> line = snp_file.readline() # header
items = line.split()[1:]
samples = numpy.array([item.strip() for item in items])
record_strs = ["Chromosome, Location, AltFreq, SNPFreq"]
sys.stderr.write("Calculating SNP prevalences...\n")
num_sites_processed = 0
for l... | code_fim | hard | {
"lang": "python",
"repo": "zhiru-liu/microbiome_evolution",
"path": "/plos_bio_scripts/calculate_snp_prevalences.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Holds panel wide prevalence for each species
os.system('mkdir -p %ssnp_prevalences' % config.data_directory)
# Open post-processed MIDAS output
snp_file = bz2.BZ2File("%ssnps/%s/annotated_snps.txt.bz2" % (config.data_directory, species_name),"r")
line = snp_file.readline() # h... | code_fim | hard | {
"lang": "python",
"repo": "zhiru-liu/microbiome_evolution",
"path": "/plos_bio_scripts/calculate_snp_prevalences.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: comic/grand-challenge.org path: /app/grandchallenge/github/views.py
import hashlib
import hmac
import json
from secrets import compare_digest
import requests
from dal_select2.views import Select2ListView
from django.conf import settings
from django.contrib.auth.decorators import login_required
f... | code_fim | hard | {
"lang": "python",
"repo": "comic/grand-challenge.org",
"path": "/app/grandchallenge/github/views.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class GitHubInstallationRequiredMixin:
"""
Ensures that the GitHub application is installed for the current user
Requires the user to be logged in, use after LoginRequiredMixin.
"""
@property
def github_state(self):
return encode_github_state(
redirect_url=se... | code_fim | hard | {
"lang": "python",
"repo": "comic/grand-challenge.org",
"path": "/app/grandchallenge/github/views.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> @property
def github_state(self):
return encode_github_state(
redirect_url=self.request.build_absolute_uri()
)
@property
def github_auth_url(self):
return f"https://github.com/login/oauth/authorize?client_id={settings.GITHUB_CLIENT_ID}&state={self.githu... | code_fim | hard | {
"lang": "python",
"repo": "comic/grand-challenge.org",
"path": "/app/grandchallenge/github/views.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def validate_with_client(self, client, value):
neutron_client = client.client('neutron')
neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'loadbalancer', value)
class ListenerConstraint(constraints.BaseCustomConstraint):
expected_exceptions = (exceptions.Neu... | code_fim | medium | {
"lang": "python",
"repo": "dragorosson/heat",
"path": "/heat/engine/clients/os/neutron/lbaas_constraints.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>class PoolConstraint(constraints.BaseCustomConstraint):
expected_exceptions = (exceptions.NeutronClientException,)
def validate_with_client(self, client, value):
neutron_client = client.client('neutron')
# v2 pool is called lbaas_pool to differentiate from v1 pool
neutron... | code_fim | hard | {
"lang": "python",
"repo": "dragorosson/heat",
"path": "/heat/engine/clients/os/neutron/lbaas_constraints.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: dragorosson/heat path: /heat/engine/clients/os/neutron/lbaas_constraints.py
#
# All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | code_fim | hard | {
"lang": "python",
"repo": "dragorosson/heat",
"path": "/heat/engine/clients/os/neutron/lbaas_constraints.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> app = self.app or current_app
return app.widgets
def widget(self, name):
def decorator(f):
self._widgets[name] = f
return decorator
def position(self, position, order=None):
if order is None:
order = -1
def decorator(f):
... | code_fim | hard | {
"lang": "python",
"repo": "maximilianoPizarro/flask-widgets",
"path": "/flask_widgets.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: maximilianoPizarro/flask-widgets path: /flask_widgets.py
__version__ = '0.4'
__versionfull__ = __version__
from flask import current_app, Markup, render_template, request
def _make_cache_key(key_prefix):
"""Make cache key from prefix
Borrowed from Flask-Cache extension
"""
if c... | code_fim | hard | {
"lang": "python",
"repo": "maximilianoPizarro/flask-widgets",
"path": "/flask_widgets.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def render_widget_position(self, position, **options):
if position not in self._positions:
current_app.logger.warning('Position not found: %s' % position)
return ''
cache_timeout = options.pop('timeout', None)
cache_key = _make_cache_key(options.pop('ke... | code_fim | hard | {
"lang": "python",
"repo": "maximilianoPizarro/flask-widgets",
"path": "/flask_widgets.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: yanshengjia/algorithm path: /leetcode/Tree & Recursion/235. Lowest Common Ancestor of a Binary Search Tree.py
"""
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is... | code_fim | hard | {
"lang": "python",
"repo": "yanshengjia/algorithm",
"path": "/leetcode/Tree & Recursion/235. Lowest Common Ancestor of a Binary Search Tree.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None:
return root
mn, mx = min(p.val, q.val), max(p.val, q.val)
if mn <= root.val <= mx:
return root
else:
if root.val >= mx:
... | code_fim | medium | {
"lang": "python",
"repo": "yanshengjia/algorithm",
"path": "/leetcode/Tree & Recursion/235. Lowest Common Ancestor of a Binary Search Tree.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def mock_subjurisdiction_redirect_page_meta(page_id):
tpl = """<html><head><META HTTP-EQUIV="Refresh" CONTENT="0; URL=./{page_id}/en/summary.html"></head></html>"""
return tpl.format(page_id=page_id)
class TestJurisdiction(TestCase):
def test_construct(self):
url = 'https://results.e... | code_fim | hard | {
"lang": "python",
"repo": "GPHemsley/clarify",
"path": "/tests/test_jurisdiction.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: GPHemsley/clarify path: /tests/test_jurisdiction.py
import os
import os.path
import re
from unittest import TestCase
# Require TestCase to have subTest().
if not hasattr(TestCase, "subTest"):
from unittest2 import TestCase
import responses
from clarify.jurisdiction import Jurisdiction
CO... | code_fim | hard | {
"lang": "python",
"repo": "GPHemsley/clarify",
"path": "/tests/test_jurisdiction.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.assertEqual(Jurisdiction._url_ensure_trailing_slash(url_with), url_with)
self.assertEqual(Jurisdiction._url_ensure_trailing_slash(url_without), url_with)
def test_get_current_ver(self):
election_urls = [
"https://results.enr.clarityelections.com/CO/63746/",
... | code_fim | hard | {
"lang": "python",
"repo": "GPHemsley/clarify",
"path": "/tests/test_jurisdiction.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: billingstack/python-fakturo path: /fakturo/core/cli/paymentmethod.py
from fakturo.core.cli.base import CreateCommand
from fakturo.core.cli.base import UpdateCommand
from fakturo.core.cli.base import DeleteCommand
from fakturo.core.cli.base import ListCommand
from fakturo.core.cli.base import GetC... | code_fim | medium | {
"lang": "python",
"repo": "billingstack/python-fakturo",
"path": "/fakturo/core/cli/paymentmethod.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> api = 'payment_method'
class PaymentMethodList(ListCommand):
api = 'payment_method'
class PaymentMethodGet(GetCommand):
api = 'payment_method'<|fim_prefix|># repo: billingstack/python-fakturo path: /fakturo/core/cli/paymentmethod.py
from fakturo.core.cli.base import CreateCommand
from fak... | code_fim | medium | {
"lang": "python",
"repo": "billingstack/python-fakturo",
"path": "/fakturo/core/cli/paymentmethod.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: martinjaeger/spinner path: /docs/theory/images/svpwm-abc-signs.py
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_xlabel("State space vector angle (deg)")
ax.set_ylabel(r"$a, b, c$")
alphad = np.arange(0, 360, 1)
alpha = np.deg2rad(alphad)
<|fim_suffix|>ax.... | code_fim | hard | {
"lang": "python",
"repo": "martinjaeger/spinner",
"path": "/docs/theory/images/svpwm-abc-signs.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>ax.plot(alphad, a, color="r", label="a")
ax.plot(alphad, b, color="g", label="b")
ax.plot(alphad, c, color="b", label="c")
ax.set_xticks([0, 60, 120, 180, 240, 300, 360])
ax.set_xlim([0, 360])
ax.set_yticks([-1, 0, 1])
ax.set_ylim([-1, 1])
ax.axvline(0, ls="--")
ax.axvline(60, ls="--")
ax.axvline(120, ... | code_fim | medium | {
"lang": "python",
"repo": "martinjaeger/spinner",
"path": "/docs/theory/images/svpwm-abc-signs.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Queer-AI/queer-ai path: /chatbot_website/chatbot_interface/reporting.py
from .airtable import Airtable
airtable = Airtable();
class Reporting():
batched_responses = []
def get_id_by_question(self, question):
questions_by_id = airtable.get_questions_by_id()
for id in que... | code_fim | medium | {
"lang": "python",
"repo": "Queer-AI/queer-ai",
"path": "/chatbot_website/chatbot_interface/reporting.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> hasQuestion = 'respondingTo' in response
question_id = self.get_id_by_question(response['respondingTo']) if hasQuestion else None
question_text = response['respondingTo'] if hasQuestion else None
self.batched_responses.append({
'Question': [ question_id ] if que... | code_fim | medium | {
"lang": "python",
"repo": "Queer-AI/queer-ai",
"path": "/chatbot_website/chatbot_interface/reporting.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> airtable.report_responses(self.batched_responses)
self.batched_responses = []
def report(self, response):
hasQuestion = 'respondingTo' in response
question_id = self.get_id_by_question(response['respondingTo']) if hasQuestion else None
question_text = response[... | code_fim | hard | {
"lang": "python",
"repo": "Queer-AI/queer-ai",
"path": "/chatbot_website/chatbot_interface/reporting.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: agustinhenze/mibs.snmplabs.com path: /pysnmp/UMSAOL-MIB.py
form Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValu... | code_fim | hard | {
"lang": "python",
"repo": "agustinhenze/mibs.snmplabs.com",
"path": "/pysnmp/UMSAOL-MIB.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>te")
if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationKeyIndex.setStatus('mandatory')
iBMPSGAOLControlFunctionConfigurationName = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 2), String()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfiguration... | code_fim | hard | {
"lang": "python",
"repo": "agustinhenze/mibs.snmplabs.com",
"path": "/pysnmp/UMSAOL-MIB.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>GAlertOnLANEventAutoClearEnabled.setStatus('mandatory')
iBMPSGAlertOnLANMaximumEventPollInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 14), Uint32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumEventPollInterval.setStatus('mandatory')
iBMPSGAlertOnLAN... | code_fim | hard | {
"lang": "python",
"repo": "agustinhenze/mibs.snmplabs.com",
"path": "/pysnmp/UMSAOL-MIB.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Legacy-Fabric/Legacy-Intermediaries path: /invert_match.py
#!/usr/bin/env python3
# usage: python3 invert_match.py <match_location> <inverted_match_location>
import sys
def invert(path, newPath):
with open(path) as match:
string = match.read()
lines = string.splitlines()
... | code_fim | hard | {
"lang": "python",
"repo": "Legacy-Fabric/Legacy-Intermediaries",
"path": "/invert_match.py",
"mode": "psm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> for i in range(0, len(obj["lines"])):
line = obj["lines"][i]
if line[0] == "c":
line[0] = line[1]
line[1] = line[2]
line[2] = line[0]
line[0] = "c"
elif line[1] == "m" or line[1] == "f":
line[0] = line[2]
... | code_fim | hard | {
"lang": "python",
"repo": "Legacy-Fabric/Legacy-Intermediaries",
"path": "/invert_match.py",
"mode": "spm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> lines = [
obj["title"],
"\ta:"
] + obj["a"] + ["\tb:"] + obj["b"] + ["\tcp:"] + obj["cp"] + ["\tcp a:"] + obj["cp_a"] + ["\tcp b:"] + obj["cp_b"] + obj["lines"]
txt = ""
for i in lines:
txt += i + "\n"
with open(newPath, 'w') as newFile:
newFile.w... | code_fim | hard | {
"lang": "python",
"repo": "Legacy-Fabric/Legacy-Intermediaries",
"path": "/invert_match.py",
"mode": "spm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> example = azure.compute.get_platform_image(location="West Europe",
publisher="Canonical",
offer="0001-com-ubuntu-server-focal",
sku="20_04-lts")
pulumi.export("id", example.id)
```
:param str location: Specifies the Location to pull information about this Platform... | code_fim | hard | {
"lang": "python",
"repo": "pulumi/pulumi-azure",
"path": "/sdk/python/pulumi_azure/compute/get_platform_image.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pulumi/pulumi-azure path: /sdk/python/pulumi_azure/compute/get_platform_image.py
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
imp... | code_fim | hard | {
"lang": "python",
"repo": "pulumi/pulumi-azure",
"path": "/sdk/python/pulumi_azure/compute/get_platform_image.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> v3 = v2 * 2
print("v1 * 2 = ({}, {}, {})".format(v3.getX(), v3.getY(), v3.getZ()))
v3 = v2 / 2
print("v1 / 2 = ({}, {}, {})".format(v3.getX(), v3.getY(), v3.getZ()))
print("Length of v1 : {}".format(v1.getLength()))<|fim_prefix|># repo: Elendeer/homework path: /python/11th/test.py
'... | code_fim | hard | {
"lang": "python",
"repo": "Elendeer/homework",
"path": "/python/11th/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __sub__(self, other):
return Vector(self.__x - other.getX(), self.__y - other.getY(), self.__z - other.getZ())
def __mul__(self, other):
return Vector(self.__x * other, self.__y * other, self.__z * other)
def __truediv__(self, other):
return Vector(self.__x / othe... | code_fim | hard | {
"lang": "python",
"repo": "Elendeer/homework",
"path": "/python/11th/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Elendeer/homework path: /python/11th/test.py
'''
Author : Daniel_Elendeer
Date : 2020-12-28 21:54:53
LastEditors : Daniel_Elendeer
LastEditTime : 2020-12-28 22:27:28
Description :
'''
class Vector:
def __init__(self, x, y, z):
self.__x = x
self.__y = y
... | code_fim | hard | {
"lang": "python",
"repo": "Elendeer/homework",
"path": "/python/11th/test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: vbuxbaum/git-black path: /src/git_black/__init__.py
import logging
import re
import sys
import time
from bisect import bisect
from collections import namedtuple
from concurrent.futures import (
FIRST_COMPLETED,
ProcessPoolExecutor,
ThreadPoolExecutor,
wait,
)
from dataclasses impo... | code_fim | hard | {
"lang": "python",
"repo": "vbuxbaum/git-black",
"path": "/src/git_black/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class GitBlack:
def __init__(self):
self.repo = Repository(".")
self.patchers = {}
def get_blamed_deltas(self, patch):
filename = patch.delta.old_file.path
self.patchers[filename] = Patcher(self.repo, filename)
hb = HunkBlamer(self.repo, patch)
retu... | code_fim | hard | {
"lang": "python",
"repo": "vbuxbaum/git-black",
"path": "/src/git_black/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> request = hangups.hangouts_pb2.SendChatMessageRequest(
request_header=self.client.get_request_header(),
event_request_header=hangups.hangouts_pb2.EventRequestHeader(
conversation_id=hangups.hangouts_pb2.ConversationId(
id=event.conversation_id.id
),
client_generated_id=self.client... | code_fim | medium | {
"lang": "python",
"repo": "mouseythemouse/pearl",
"path": "/plugins/badword.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mouseythemouse/pearl path: /plugins/badword.py
import asyncio
import hangups
class BadWord:
def __init__(self, client):
<|fim_suffix|> request = hangups.hangouts_pb2.SendChatMessageRequest(
request_header=self.client.get_request_header(),
event_request_header=hangups.hangouts_pb2.Event... | code_fim | medium | {
"lang": "python",
"repo": "mouseythemouse/pearl",
"path": "/plugins/badword.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: alexsanduk/otree-core path: /otree/management/commands/startproject.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# IMPORTS
# =============================================================================
import ... | code_fim | hard | {
"lang": "python",
"repo": "alexsanduk/otree-core",
"path": "/otree/management/commands/startproject.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> imp = platform.python_implementation()
implementation_name = IMPLEMENTATIONS_ALIAS.get(imp, imp).lower()
version = ".".join(map(str, sys.version_info[:3]))
runtime_string = "{}-{}\n".format(implementation_name, version)
runtime_path = os.path.join(top_dir, "runtime... | code_fim | hard | {
"lang": "python",
"repo": "alexsanduk/otree-core",
"path": "/otree/management/commands/startproject.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> output = model(input_ids, attention_mask)
_, prediction = torch.max(output, dim=1)
probs = output.detach().cpu().data.numpy()[0]
min_max = lambda v:(v - probs.min()) / (probs.max() - probs.min())
probs = np.array([min_max(xi) for xi in probs])
sum_probs=sum(probs)
probs = np.array([x/sum_pr... | code_fim | hard | {
"lang": "python",
"repo": "shawnchen63/nlp_assignment_1",
"path": "/SourceCode/part_3/application/deep_sentiment_analysis.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: shawnchen63/nlp_assignment_1 path: /SourceCode/part_3/application/deep_sentiment_analysis.py
print("Loading model do not close the program unless unresponsive for more than 3 minutes...")
from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup
import torch
impor... | code_fim | hard | {
"lang": "python",
"repo": "shawnchen63/nlp_assignment_1",
"path": "/SourceCode/part_3/application/deep_sentiment_analysis.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> encoded_review = tokenizer.encode_plus(
review_text,
max_length=MAX_LEN,
add_special_tokens=True,
return_token_type_ids=False,
padding=True,
return_attention_mask=True,
return_tensors='pt',
)
input_ids = encoded_review['input_ids'].to(device)
attention_mask = encoded_re... | code_fim | hard | {
"lang": "python",
"repo": "shawnchen63/nlp_assignment_1",
"path": "/SourceCode/part_3/application/deep_sentiment_analysis.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: synteny/AuroraBot path: /sessioncontroller/settings.py
import os
TELEGRAM_TOKEN = os.environ['TELEGRAM_TOKEN']
DATABASE = {
'HOST': os.getenv('DB_PORT_3306_TCP_ADDR', 'localhos<|fim_suffix|>RD': os.getenv('DB_MYSQL_PASSWORD', ''),
'NAME': 'aurora',
}<|fim_middle|>t'),
'USER': os.get... | code_fim | medium | {
"lang": "python",
"repo": "synteny/AuroraBot",
"path": "/sessioncontroller/settings.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>RD': os.getenv('DB_MYSQL_PASSWORD', ''),
'NAME': 'aurora',
}<|fim_prefix|># repo: synteny/AuroraBot path: /sessioncontroller/settings.py
import os
TELEGRAM_TOKEN = os.environ['TELEGRAM_TOKEN']
DATAB<|fim_middle|>ASE = {
'HOST': os.getenv('DB_PORT_3306_TCP_ADDR', 'localhost'),
'USER': os.get... | code_fim | medium | {
"lang": "python",
"repo": "synteny/AuroraBot",
"path": "/sessioncontroller/settings.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> assert 'healthy' in rep.results
assert 'failed' in rep.results
assert rep.results['healthy'].__len__() == 1
assert rep.results['failed'].__len__() == 2
def test_report_str(self, rep):
assert str(rep) == '1/3 passed (33.33%)'<|fim_prefix|># repo: zcking/http_rx ... | code_fim | hard | {
"lang": "python",
"repo": "zcking/http_rx",
"path": "/rx/test_report.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zcking/http_rx path: /rx/test_report.py
import pytest
import requests
from . import report, check
def make_result(is_healthy, failure_reason=None):
fake_resp = requests.Response()
fake_resp.url = 'http://test.com'
fake_resp.status_code = 200
return check.Result(
name='... | code_fim | medium | {
"lang": "python",
"repo": "zcking/http_rx",
"path": "/rx/test_report.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_creating_report(self, rep):
assert 'healthy' in rep.results
assert 'failed' in rep.results
assert rep.results['healthy'].__len__() == 1
assert rep.results['failed'].__len__() == 2
def test_report_str(self, rep):
assert str(rep) == '1/3 passed (33.3... | code_fim | medium | {
"lang": "python",
"repo": "zcking/http_rx",
"path": "/rx/test_report.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def execute(self):
# Check provider config before doing stuff
results = ""
if self.auth_token:
results = self.client.execute()
# print(results)
if results:
logger.info(
"✓ {}: {} Record {} -> {}".format(
... | code_fim | hard | {
"lang": "python",
"repo": "Peter-SAARLAND/ns0",
"path": "/ns0/providers/lexicon.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Peter-SAARLAND/ns0 path: /ns0/providers/lexicon.py
from lexicon.client import Client as LexClient
from lexicon.config import ConfigResolver as LexiconConfigResolver
from logzero import logger
class LexiconClient:
def __init__(self, provider_name, action, domain, name, type, content):
<|fim... | code_fim | hard | {
"lang": "python",
"repo": "Peter-SAARLAND/ns0",
"path": "/ns0/providers/lexicon.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mayorana/FeedML path: /build/lib/FeedML/get_data.py
# -*- coding: utf-8 -*-
"""
Created on Sun May 20 22:09:55 2018
@author: Lenovo
"""
import pandas as pd
import unidecode
def stripos(os):
if "ő" in os.lower() or "ű" in os.lower() or "ü" in os.lower() or "ö" in os.lower():
... | code_fim | hard | {
"lang": "python",
"repo": "mayorana/FeedML",
"path": "/build/lib/FeedML/get_data.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> asz = pd.read_excel(excelfile)
asz['Location2'] = pd.Series(asz.ASZ, index=asz.index)
asz['Location2'] = asz['Location2'].str.split(' és környéke').str[0]
asz['jaras'] = asz['Location2'].map(pd.DataFrame.to_dict(match)['jaras'])
asz['Location'] = asz['Location2'].apply(stripos)
... | code_fim | medium | {
"lang": "python",
"repo": "mayorana/FeedML",
"path": "/build/lib/FeedML/get_data.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def __init__(self, resolve_values=False, resolve_names=False):
self.resolve_values = resolve_values
self.resolve_names = resolve_names
def __iter__(self):
if self.resolve_values:
yield {'param': 'id',
'value': '${OBJECT_ID}'}
yie... | code_fim | hard | {
"lang": "python",
"repo": "behave-restful/behave-restful",
"path": "/tests/test_lang_imp/test_request_builder.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: behave-restful/behave-restful path: /tests/test_lang_imp/test_request_builder.py
import unittest
from assertpy import assert_that, fail
import behave_restful._definitions as _definitions
import behave_restful._lang_imp.request_builder as _builder
class TestBuilderInterface(unittest.TestCase):... | code_fim | hard | {
"lang": "python",
"repo": "behave-restful/behave-restful",
"path": "/tests/test_lang_imp/test_request_builder.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zlalanne/msp430-webcontrol path: /msp430backend/msp430_ws/buffer.py
class UpdateDict(dict):
# (sent_value, stored_value)
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, (None, value))
return
sent_value, stored_valu... | code_fim | hard | {
"lang": "python",
"repo": "zlalanne/msp430-webcontrol",
"path": "/msp430backend/msp430_ws/buffer.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __len__(self):
counter = 0
for key, (sent_value, stored_value) in dict.iteritems(self):
if sent_value != stored_value:
counter += 1
return counter<|fim_prefix|># repo: zlalanne/msp430-webcontrol path: /msp430backend/msp430_ws/buffer.py
class Upd... | code_fim | hard | {
"lang": "python",
"repo": "zlalanne/msp430-webcontrol",
"path": "/msp430backend/msp430_ws/buffer.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: yo16/tips_python path: /文字列/文字列と数値の判定.py
# -*- coding: utf-8 -*-
# 自前で用意するのがベターか
# 参考:http://www.python.ambitious-engineer.com/archives/420
def is_float_str(num_str, default=0):
try:
return {"is_float": True ,"val": float(num_str)}
except ValueError:
return {"is_float": False , "val": defa... | code_fim | hard | {
"lang": "python",
"repo": "yo16/tips_python",
"path": "/文字列/文字列と数値の判定.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>print("-1".isnumeric())
# False
print("三十五".isnumeric())
# True
# 柔軟すぎるのもどうかと思う・・・
print("百二十一京".isnumeric())
# False
print("百二十一兆".isnumeric())
# True
print("百二十一億".isnumeric())
# True<|fim_prefix|># repo: yo16/tips_python path: /文字列/文字列と数値の判定.py
# -*- coding: utf-8 -*-
# 自前で用意するのがベターか
# 参考:http://ww... | code_fim | hard | {
"lang": "python",
"repo": "yo16/tips_python",
"path": "/文字列/文字列と数値の判定.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>print("-1".isdigit())
# False <-!?
print("3.14".isdigit())
# False <-!?
print("a".isdigit())
# False
print("------------------")
# isnumeric
# ヨクワカラナイ
print("-1".isnumeric())
# False
print("三十五".isnumeric())
# True
# 柔軟すぎるのもどうかと思う・・・
print("百二十一京".isnumeric())
# False
print("百二十一兆".isnumeric())... | code_fim | medium | {
"lang": "python",
"repo": "yo16/tips_python",
"path": "/文字列/文字列と数値の判定.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.