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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4cf2bae652da80b2815a067d | train | function | def get_action(Q, counter, score, game_info, params):
epsilon = params[0]
policy = make_policy(Q, epsilon, get_action_num())
action_probs = policy(get_state(counter, score, game_info))
action = np.random.choice(np.arange(len(action_probs)), p=action_probs)
return action
| def get_action(Q, counter, score, game_info, params):
| epsilon = params[0]
policy = make_policy(Q, epsilon, get_action_num())
action_probs = policy(get_state(counter, score, game_info))
action = np.random.choice(np.arange(len(action_probs)), p=action_probs)
return action
| sys.stdout.flush()
return Q
def train(num_episodes, params):
g = Game(False)
Q = q_learning(g, num_episodes, params)
return Q
## This function will be called in the game.py
def get_action(Q, counter, score, game_info, params):
| 64 | 64 | 69 | 14 | 49 | jooncco/coindrop-game-ai-agent | project/q_learning_.py | Python | get_action | get_action | 238 | 243 | 238 | 238 | 9329df071a95ec8a1a2d0ed63e08cf93a02d1f70 | bigcode/the-stack | train |
e654aae6b1dd4bb1ae4dea83 | train | function | def train(num_episodes, params):
g = Game(False)
Q = q_learning(g, num_episodes, params)
return Q
| def train(num_episodes, params):
| g = Game(False)
Q = q_learning(g, num_episodes, params)
return Q
| .
if (i_episode + 1) % 100 == 0:
print("Episode {}/{} (Score: {})\n".format(i_episode + 1, num_episodes, score), end="")
sys.stdout.flush()
return Q
def train(num_episodes, params):
| 64 | 64 | 31 | 8 | 55 | jooncco/coindrop-game-ai-agent | project/q_learning_.py | Python | train | train | 231 | 234 | 231 | 231 | c306e5612b0bf2f8fe84b7702610c6ff7da404ca | bigcode/the-stack | train |
65bc831008328eeddac02e7e | train | function | def make_policy(Q, epsilon, nA):
def policy_fn(observation):
A = np.ones(nA, dtype=float) * epsilon / nA
best_action = np.argmax(Q[observation])
A[best_action] += (1.0 - epsilon)
return A
return policy_fn
| def make_policy(Q, epsilon, nA):
| def policy_fn(observation):
A = np.ones(nA, dtype=float) * epsilon / nA
best_action = np.argmax(Q[observation])
A[best_action] += (1.0 - epsilon)
return A
return policy_fn
| 11], [10, 11]]
# In our case, we have 3 actions (stay, go-left, go-right)
def get_action_num():
return 3
## this function return policy function to choose the action based on Q value.
def make_policy(Q, epsilon, nA):
| 64 | 64 | 68 | 10 | 54 | jooncco/coindrop-game-ai-agent | project/q_learning_.py | Python | make_policy | make_policy | 32 | 38 | 32 | 32 | d112ed4880db7f59fb5c545ee4d9587f77e6ede5 | bigcode/the-stack | train |
88689f599c494db7bfca4540 | train | function | def load_q(filename="model_q.pkl"):
with open(filename, "rb") as f:
data = pickle.loads(f.read())
return defaultdict(lambda: np.zeros(3), data["q_table"]), data["num_episode"], data["params"]
| def load_q(filename="model_q.pkl"):
| with open(filename, "rb") as f:
data = pickle.loads(f.read())
return defaultdict(lambda: np.zeros(3), data["q_table"]), data["num_episode"], data["params"]
| _q(Q, num_episode, params, filename="model_q.pkl"):
data = {"num_episode": num_episode, "params": params, "q_table": dict(Q)}
with open(filename, "wb") as w:
w.write(pickle.dumps(data))
def load_q(filename="model_q.pkl"):
| 64 | 64 | 52 | 9 | 55 | jooncco/coindrop-game-ai-agent | project/q_learning_.py | Python | load_q | load_q | 159 | 162 | 159 | 159 | 016e0fe547a936da06b47e3d86cf23555be86ad8 | bigcode/the-stack | train |
32b277c6b499b90a48cc629e | train | function | def save_q(Q, num_episode, params, filename="model_q.pkl"):
data = {"num_episode": num_episode, "params": params, "q_table": dict(Q)}
with open(filename, "wb") as w:
w.write(pickle.dumps(data))
| def save_q(Q, num_episode, params, filename="model_q.pkl"):
| data = {"num_episode": num_episode, "params": params, "q_table": dict(Q)}
with open(filename, "wb") as w:
w.write(pickle.dumps(data))
| :
return (current_score - prev_score) + 100*(current_counter - prev_counter)
else:
return (current_score - prev_score) + (current_counter - prev_counter) + (basket_rn-previous)
def save_q(Q, num_episode, params, filename="model_q.pkl"):
| 64 | 64 | 57 | 16 | 48 | jooncco/coindrop-game-ai-agent | project/q_learning_.py | Python | save_q | save_q | 154 | 157 | 154 | 154 | ea853ed3087c9493d2b911223697f2a2e9592aae | bigcode/the-stack | train |
382522d5ba79f7693fd57152 | train | function | def get_reward(prev_score, current_score, prev_counter, current_counter, game_info):
global basket_rn
# evaluate 'right now' basket
def above_basket(game_info):
right_now = 0
basket = table_coverage[game_info[0]]
for item in game_info[1]:
if item[1] in basket and... | def get_reward(prev_score, current_score, prev_counter, current_counter, game_info):
| global basket_rn
# evaluate 'right now' basket
def above_basket(game_info):
right_now = 0
basket = table_coverage[game_info[0]]
for item in game_info[1]:
if item[1] in basket and item[2] >= 5:
if item[0] == 1:
right_now += 5
... | if timeFlag:
return timeFlag
greedyFlag = isGreedy(game_info)
return greedyFlag if greedyFlag else smell(game_info)
## this function return reward from given previous and current score and counter.
def get_reward(prev_score, current_score, prev_counter, current_counter, game_info):
| 64 | 64 | 191 | 18 | 46 | jooncco/coindrop-game-ai-agent | project/q_learning_.py | Python | get_reward | get_reward | 132 | 152 | 132 | 132 | 6df9776aab13c1f9aa75ac2c86a33b47a4aff148 | bigcode/the-stack | train |
a3128399a28ce678eb6ad1fc | train | function | def q_learning(game, num_episodes, params):
"""
Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy
while following an epsilon-greedy policy.
You can edit those parameters, please speficy your changes in the report.
Args:
game: Coin drop game environment.
... | def q_learning(game, num_episodes, params):
| """
Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy
while following an epsilon-greedy policy.
You can edit those parameters, please speficy your changes in the report.
Args:
game: Coin drop game environment.
num_episodes: Number of episodes to run... | 100*(current_counter - prev_counter)
else:
return (current_score - prev_score) + (current_counter - prev_counter) + (basket_rn-previous)
def save_q(Q, num_episode, params, filename="model_q.pkl"):
data = {"num_episode": num_episode, "params": params, "q_table": dict(Q)}
with open(filename, "w... | 156 | 157 | 526 | 11 | 145 | jooncco/coindrop-game-ai-agent | project/q_learning_.py | Python | q_learning | q_learning | 165 | 229 | 165 | 165 | b9e9024cb8fef2d24e4511b04890e0c5c6dd3c3c | bigcode/the-stack | train |
ebef64093618ab2a59f591ad | train | function | @app.route('/hbnb', strict_slashes=False)
def hbnb():
"""hbnb"""
return 'HBNB'
| @app.route('/hbnb', strict_slashes=False)
def hbnb():
| """hbnb"""
return 'HBNB'
| #!/usr/bin/python3
"""web_flask"""
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/", strict_slashes=False)
def index():
"""index"""
return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
| 63 | 64 | 27 | 15 | 48 | jj131204/AirBnB_clone_v2 | web_flask/5-number_template.py | Python | hbnb | hbnb | 15 | 18 | 15 | 16 | fb8e2363973046272fa1551a7272cb8ef08a02b8 | bigcode/the-stack | train |
94284c7f70ffec1a4af3f4ec | train | function | @app.route('/number/<int:n>', strict_slashes=False)
def number_(n):
"""display “n is a number” only if n is an integer"""
return '{:d} is a number'.format(n)
| @app.route('/number/<int:n>', strict_slashes=False)
def number_(n):
| """display “n is a number” only if n is an integer"""
return '{:d} is a number'.format(n)
| /<text>', strict_slashes=False)
def python_(text='is cool'):
"""" display “Python ”, followed by the value of the text variable"""
return ('Python ' + text.replace('_', ' '))
@app.route('/number/<int:n>', strict_slashes=False)
def number_(n):
| 63 | 64 | 47 | 18 | 46 | jj131204/AirBnB_clone_v2 | web_flask/5-number_template.py | Python | number_ | number_ | 34 | 37 | 34 | 35 | 126929902a1355254684384125e2de7d1908d166 | bigcode/the-stack | train |
8dd2563b8d964b55c3d25351 | train | function | @app.route('/number_template/<int:n>', strict_slashes=False)
def template_(n):
""" display a HTML page only if n is an integer"""
return render_template("5-number.html", n=n)
| @app.route('/number_template/<int:n>', strict_slashes=False)
def template_(n):
| """ display a HTML page only if n is an integer"""
return render_template("5-number.html", n=n)
| ('/number/<int:n>', strict_slashes=False)
def number_(n):
"""display “n is a number” only if n is an integer"""
return '{:d} is a number'.format(n)
@app.route('/number_template/<int:n>', strict_slashes=False)
def template_(n):
| 64 | 64 | 44 | 19 | 45 | jj131204/AirBnB_clone_v2 | web_flask/5-number_template.py | Python | template_ | template_ | 40 | 43 | 40 | 41 | fc8b0cf4cede4786ec5a3f43fd82f1180c3030b7 | bigcode/the-stack | train |
b482a7ba444e94878b8fe924 | train | function | @app.route('/python')
@app.route('/python/<text>', strict_slashes=False)
def python_(text='is cool'):
"""" display “Python ”, followed by the value of the text variable"""
return ('Python ' + text.replace('_', ' '))
| @app.route('/python')
@app.route('/python/<text>', strict_slashes=False)
def python_(text='is cool'):
| """" display “Python ”, followed by the value of the text variable"""
return ('Python ' + text.replace('_', ' '))
| text>', strict_slashes=False)
def c(text):
"""display “C ” followed by the value of the text variable"""
return ('C ' + text.replace('_', ' '))
@app.route('/python')
@app.route('/python/<text>', strict_slashes=False)
def python_(text='is cool'):
| 63 | 64 | 54 | 25 | 39 | jj131204/AirBnB_clone_v2 | web_flask/5-number_template.py | Python | python_ | python_ | 27 | 31 | 27 | 29 | feb8cd680d04f5573c7bb9e265024916eeeb694a | bigcode/the-stack | train |
c2219732eb201d2e22ce3e8d | train | function | @app.route('/c/<text>', strict_slashes=False)
def c(text):
"""display “C ” followed by the value of the text variable"""
return ('C ' + text.replace('_', ' '))
| @app.route('/c/<text>', strict_slashes=False)
def c(text):
| """display “C ” followed by the value of the text variable"""
return ('C ' + text.replace('_', ' '))
| strict_slashes=False)
def index():
"""index"""
return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
"""hbnb"""
return 'HBNB'
@app.route('/c/<text>', strict_slashes=False)
def c(text):
| 64 | 64 | 43 | 16 | 48 | jj131204/AirBnB_clone_v2 | web_flask/5-number_template.py | Python | c | c | 21 | 24 | 21 | 22 | fc6aee3a92a22e90e724c8639e4c992bf2a2fd68 | bigcode/the-stack | train |
88699e518934f5a848d83ffe | train | function | @app.route("/", strict_slashes=False)
def index():
"""index"""
return "Hello HBNB!"
| @app.route("/", strict_slashes=False)
def index():
| """index"""
return "Hello HBNB!"
| #!/usr/bin/python3
"""web_flask"""
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/", strict_slashes=False)
def index():
| 36 | 64 | 23 | 11 | 25 | jj131204/AirBnB_clone_v2 | web_flask/5-number_template.py | Python | index | index | 9 | 12 | 9 | 10 | 1d5676e98fa1851f1f4efb0562344469f32582c3 | bigcode/the-stack | train |
51792b39874ce06964b8f9eb | train | function | def find_nums_with_task_scheduled_pkl(data, rand_schedule):
nums = []
for i, data_at_timestep_i in enumerate(data[rand_schedule]):
if data[rand_schedule][i][131][0] != -1:
nums.append(i)
else:
continue
return nums
| def find_nums_with_task_scheduled_pkl(data, rand_schedule):
| nums = []
for i, data_at_timestep_i in enumerate(data[rand_schedule]):
if data[rand_schedule][i][131][0] != -1:
nums.append(i)
else:
continue
return nums
| elif type(element) == list:
state_input = state_input + element
else:
state_input.append(element)
else:
continue
output = schedule_timestep_data[131][0]
return state_input, output
def find_nums_with_task_scheduled_pkl... | 64 | 64 | 64 | 14 | 49 | CORE-Robotics-Lab/Personalized_Neural_Trees | utils/naive_utils.py | Python | find_nums_with_task_scheduled_pkl | find_nums_with_task_scheduled_pkl | 61 | 68 | 61 | 61 | c449501ea6d7916ec1b21c272e19ce4bc1f6ffb3 | bigcode/the-stack | train |
df2ce68ef369f9646d446c72 | train | function | def find_which_schedule_this_belongs_to(schedule_array, sample_val):
"""
Takes a sample and determines with schedule this belongs to.
Note: A schedule is task * task sized
:param sample_val: an int
:return: schedule num
"""
for i, each_array in enumerate(schedule_array):
if each_arra... | def find_which_schedule_this_belongs_to(schedule_array, sample_val):
| """
Takes a sample and determines with schedule this belongs to.
Note: A schedule is task * task sized
:param sample_val: an int
:return: schedule num
"""
for i, each_array in enumerate(schedule_array):
if each_array[0] <= sample_val <= each_array[1]:
return i
els... | nums = []
for i, data_at_timestep_i in enumerate(data[rand_schedule]):
if data[rand_schedule][i][131][0] != -1:
nums.append(i)
else:
continue
return nums
def find_which_schedule_this_belongs_to(schedule_array, sample_val):
| 64 | 64 | 95 | 15 | 48 | CORE-Robotics-Lab/Personalized_Neural_Trees | utils/naive_utils.py | Python | find_which_schedule_this_belongs_to | find_which_schedule_this_belongs_to | 71 | 82 | 71 | 71 | ff6787d0fd3b431edcd862e012fe532eff0420c4 | bigcode/the-stack | train |
6d2a5d2571af3938bc04e980 | train | function | def rebuild_input_output_from_pickle(data, rand_schedule, rand_timestep):
schedule_timestep_data = data[rand_schedule][rand_timestep]
state_input = []
for i, element in enumerate(schedule_timestep_data):
if i == 0:
if type(element) == float:
state_... | def rebuild_input_output_from_pickle(data, rand_schedule, rand_timestep):
| schedule_timestep_data = data[rand_schedule][rand_timestep]
state_input = []
for i, element in enumerate(schedule_timestep_data):
if i == 0:
if type(element) == float:
state_input.append(element)
elif type(element) == int:
... | imestep in timesteps_where_things_scheduled:
input_nn, output = rebuild_input_output_from_pickle(data, i, each_timestep)
X.append(input_nn)
Y.append(output)
return X, Y, schedule_array
def rebuild_input_output_from_pickle(data, rand_schedule, rand_timestep):
| 64 | 64 | 170 | 15 | 48 | CORE-Robotics-Lab/Personalized_Neural_Trees | utils/naive_utils.py | Python | rebuild_input_output_from_pickle | rebuild_input_output_from_pickle | 35 | 58 | 35 | 35 | e74876ea7fa56ab5ac6d016bac3d8380b365f7f5 | bigcode/the-stack | train |
207081d0b02aaf7de97b40de | train | function | def load_in_naive_data(num_schedules, num_test_schedules):
# load in data
load_directory = '/home/rohanpaleja/PycharmProjects/bayesian_prolo/scheduling_env/scheduling_dataset/' + str(
num_schedules) + 'EDF_9_25_2019_old_naive.pkl'
data = pickle.load(open(load_directory, "rb"))
X_train_naive, Y... | def load_in_naive_data(num_schedules, num_test_schedules):
# load in data
| load_directory = '/home/rohanpaleja/PycharmProjects/bayesian_prolo/scheduling_env/scheduling_dataset/' + str(
num_schedules) + 'EDF_9_25_2019_old_naive.pkl'
data = pickle.load(open(load_directory, "rb"))
X_train_naive, Y_train_naive, schedule_array_train_naive = create_new_dataset(num_schedules=num... | belongs to.
Note: A schedule is task * task sized
:param sample_val: an int
:return: schedule num
"""
for i, each_array in enumerate(schedule_array):
if each_array[0] <= sample_val <= each_array[1]:
return i
else:
continue
def load_in_naive_data(num_schedules... | 90 | 91 | 304 | 21 | 68 | CORE-Robotics-Lab/Personalized_Neural_Trees | utils/naive_utils.py | Python | load_in_naive_data | load_in_naive_data | 85 | 105 | 85 | 87 | 8e0df59d347f039d6a23d3d31b16e5badc0a18e4 | bigcode/the-stack | train |
157f3a600ce6124fb9dc01ec | train | function | def create_new_dataset(data, num_schedules):
"""
creates a dataset where each row is the twenty timesteps of a schedule alongside the chosen task
creates a schedule array that tracks when each schedules starts and ends
:return:
"""
X = []
Y = []
schedule_array = []
for i in range(0, ... | def create_new_dataset(data, num_schedules):
| """
creates a dataset where each row is the twenty timesteps of a schedule alongside the chosen task
creates a schedule array that tracks when each schedules starts and ends
:return:
"""
X = []
Y = []
schedule_array = []
for i in range(0, num_schedules):
rand_schedule = i
... | """
utils for naive data loading
"""
import pickle
def create_new_dataset(data, num_schedules):
| 21 | 78 | 263 | 10 | 10 | CORE-Robotics-Lab/Personalized_Neural_Trees | utils/naive_utils.py | Python | create_new_dataset | create_new_dataset | 6 | 32 | 6 | 6 | 6c1ac6e976a77b20bb65315b0afaee4244e73d21 | bigcode/the-stack | train |
4da88e932b4d852867c1358d | train | function | def make_dir(dir_path):
"""Create directory if it does not already exist."""
try:
os.makedirs(dir_path)
except OSError:
pass
return dir_path
| def make_dir(dir_path):
| """Create directory if it does not already exist."""
try:
os.makedirs(dir_path)
except OSError:
pass
return dir_path
| '), ('episode_reward', 'R', 'float'), ('total_time', 'T', 'time')]
AGENT_METRICS = ['consistency_loss', 'reward_loss', 'value_loss', 'total_loss', 'weighted_loss', 'pi_loss', 'grad_norm']
def make_dir(dir_path):
| 63 | 64 | 37 | 6 | 57 | nicklashansen/tdmpc | src/logger.py | Python | make_dir | make_dir | 16 | 22 | 16 | 16 | 99efb654ad1479f1d87156c4ce1edb230d7d7310 | bigcode/the-stack | train |
b8fbde7f1b4c691d2eeb5999 | train | class | class Logger(object):
"""Primary logger object. Logs either locally or using wandb."""
def __init__(self, log_dir, cfg):
self._log_dir = make_dir(log_dir)
self._model_dir = make_dir(self._log_dir / 'models')
self._save_model = cfg.save_model
self._group = cfg_to_group(cfg)
self._seed = cfg.seed
se... | class Logger(object):
| """Primary logger object. Logs either locally or using wandb."""
def __init__(self, log_dir, cfg):
self._log_dir = make_dir(log_dir)
self._model_dir = make_dir(self._log_dir / 'models')
self._save_model = cfg.save_model
self._group = cfg_to_group(cfg)
self._seed = cfg.seed
self._cfg = cfg
self._... | cfg.exp_name)]
return lst if return_list else '-'.join(lst)
class VideoRecorder:
"""Utility class for logging evaluation videos."""
def __init__(self, root_dir, wandb, render_size=384, fps=15):
self.save_dir = (root_dir / 'eval_video') if root_dir else None
self._wandb = wandb
self.render_size = re... | 250 | 250 | 835 | 4 | 246 | nicklashansen/tdmpc | src/logger.py | Python | Logger | Logger | 79 | 156 | 79 | 79 | ccece16ba8907b1311e0bde5168c4eceea749c92 | bigcode/the-stack | train |
57b99d65beec3dd5a31be93b | train | function | def print_run(cfg, reward=None):
"""Pretty-printing of run information. Call at start of training."""
prefix, color, attrs = ' ', 'green', ['bold']
def limstr(s, maxlen=32):
return str(s[:maxlen]) + '...' if len(str(s)) > maxlen else s
def pprint(k, v):
print(prefix + colored(f'{k.capitalize()+":":<16}',... | def print_run(cfg, reward=None):
| """Pretty-printing of run information. Call at start of training."""
prefix, color, attrs = ' ', 'green', ['bold']
def limstr(s, maxlen=32):
return str(s[:maxlen]) + '...' if len(str(s)) > maxlen else s
def pprint(k, v):
print(prefix + colored(f'{k.capitalize()+":":<16}', color, attrs=attrs), limstr(v))
... | consistency_loss', 'reward_loss', 'value_loss', 'total_loss', 'weighted_loss', 'pi_loss', 'grad_norm']
def make_dir(dir_path):
"""Create directory if it does not already exist."""
try:
os.makedirs(dir_path)
except OSError:
pass
return dir_path
def print_run(cfg, reward=None):
| 74 | 74 | 248 | 8 | 65 | nicklashansen/tdmpc | src/logger.py | Python | print_run | print_run | 25 | 44 | 25 | 25 | a0f3271a776c027da8789a0dcfe47c21d1d2353b | bigcode/the-stack | train |
342c090184303c310590b5e3 | train | function | def cfg_to_group(cfg, return_list=False):
"""Return a wandb-safe group name for logging. Optionally returns group name as list."""
lst = [cfg.task, cfg.modality, re.sub('[^0-9a-zA-Z]+', '-', cfg.exp_name)]
return lst if return_list else '-'.join(lst)
| def cfg_to_group(cfg, return_list=False):
| """Return a wandb-safe group name for logging. Optionally returns group name as list."""
lst = [cfg.task, cfg.modality, re.sub('[^0-9a-zA-Z]+', '-', cfg.exp_name)]
return lst if return_list else '-'.join(lst)
| bold'])))
w = np.max([len(limstr(str(kv[1]))) for kv in kvs]) + 21
div = '-'*w
print(div)
for k,v in kvs:
pprint(k, v)
print(div)
def cfg_to_group(cfg, return_list=False):
| 64 | 64 | 71 | 10 | 54 | nicklashansen/tdmpc | src/logger.py | Python | cfg_to_group | cfg_to_group | 47 | 50 | 47 | 47 | 5d12bc3b5657bb7c364a9259c473de4de370698b | bigcode/the-stack | train |
cc26c26eb6ff60dcfb93bea3 | train | class | class VideoRecorder:
"""Utility class for logging evaluation videos."""
def __init__(self, root_dir, wandb, render_size=384, fps=15):
self.save_dir = (root_dir / 'eval_video') if root_dir else None
self._wandb = wandb
self.render_size = render_size
self.fps = fps
self.frames = []
self.enabled = Fa... | class VideoRecorder:
| """Utility class for logging evaluation videos."""
def __init__(self, root_dir, wandb, render_size=384, fps=15):
self.save_dir = (root_dir / 'eval_video') if root_dir else None
self._wandb = wandb
self.render_size = render_size
self.fps = fps
self.frames = []
self.enabled = False
def init(self,... | return_list=False):
"""Return a wandb-safe group name for logging. Optionally returns group name as list."""
lst = [cfg.task, cfg.modality, re.sub('[^0-9a-zA-Z]+', '-', cfg.exp_name)]
return lst if return_list else '-'.join(lst)
class VideoRecorder:
| 69 | 69 | 231 | 4 | 65 | nicklashansen/tdmpc | src/logger.py | Python | VideoRecorder | VideoRecorder | 53 | 76 | 53 | 53 | c7b38c3142cb8ac2bbb7cba09bdfe5354d4c6d11 | bigcode/the-stack | train |
3ebf72484b07f0a2c92910e9 | train | class | class SubscriptionClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for SubscriptionClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure... | class SubscriptionClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
| """Configuration for SubscriptionClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:keyword api_version: A... | under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing im... | 146 | 146 | 487 | 18 | 127 | vincenttran-msft/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2016_06_01/aio/_configuration.py | Python | SubscriptionClientConfiguration | SubscriptionClientConfiguration | 22 | 66 | 22 | 22 | 24cd9e8c885e7ca1676e4679407e21aa3c3498dc | bigcode/the-stack | train |
d276666fa3cb1b3daa861b49 | train | class | class UsersTable(users_tables.UsersTable):
"""Display Users of the project with roles."""
roles = tables.Column(
lambda obj: ", ".join(getattr(obj, 'roles', [])),
verbose_name=_('Roles'),
form_field=forms.CharField(
widget=forms.Textarea(attrs={'rows': 4}),
requir... | class UsersTable(users_tables.UsersTable):
| """Display Users of the project with roles."""
roles = tables.Column(
lambda obj: ", ".join(getattr(obj, 'roles', [])),
verbose_name=_('Roles'),
form_field=forms.CharField(
widget=forms.Textarea(attrs={'rows': 4}),
required=False))
groups_roles = tables.Colum... | the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import forms
from horizon import tables
from openstack_dashboard.dashboards.identity.users \
import tables as users_tables
class UsersTable(user... | 64 | 64 | 161 | 8 | 55 | stackhpc/horizon | openstack_dashboard/dashboards/identity/projects/users/tables.py | Python | UsersTable | UsersTable | 22 | 41 | 22 | 22 | 5f0c3071ae21fd2dcb1f7772f1807f93ff6ae82d | bigcode/the-stack | train |
0952ce85180c135415d88f4a | train | class | class TestMap:
@pytest.mark.parametrize(
"data, categories",
[
(list("abcbca"), list("cab")),
(pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)),
],
ids=["string", "interval"],
)
def test_map_str(self, data, categories, ordered):
... | class TestMap:
@pytest.mark.parametrize(
"data, categories",
[
(list("abcbca"), list("cab")),
(pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)),
],
ids=["string", "interval"],
)
| def test_map_str(self, data, categories, ordered):
# GH 31202 - override base class since we want to maintain categorical/ordered
index = CategoricalIndex(data, categories=categories, ordered=ordered)
result = index.map(str)
expected = CategoricalIndex(
map(str, data... | import numpy as np
import pytest
import pandas as pd
from pandas import (
CategoricalIndex,
Index,
Series,
)
import pandas._testing as tm
class TestMap:
@pytest.mark.parametrize(
"data, categories",
[
(list("abcbca"), list("cab")),
(pd.interval_rang... | 103 | 256 | 1,042 | 67 | 35 | arnoyu-hub/COMP0016miemie | venv/Lib/site-packages/pandas/tests/indexes/categorical/test_map.py | Python | TestMap | TestMap | 13 | 115 | 13 | 21 | 320c097fff3d3a4f9458b7ef0731d93118864c7d | bigcode/the-stack | train |
5cb8398b24ce0aac22fdb93e | train | function | def write_page(url, content, title=""):
write_file(url + "/index.html", build_layout(url, content, title=title))
| def write_page(url, content, title=""):
| write_file(url + "/index.html", build_layout(url, content, title=title))
| "",
"menu_active_download": "active" if url.startswith("/download") else "",
"menu_active_examples": "active" if url.startswith("/examples") else "",
"menu_active_reference": "active" if url.startswith("/reference") else "",
})
def write_page(url, content, title=""):
| 64 | 64 | 29 | 10 | 54 | dolfly/plotfx | extra/web/build_layout.py | Python | write_page | write_page | 101 | 102 | 101 | 101 | 45ff6a0b39619a54859dc864e5080570881dd2d4 | bigcode/the-stack | train |
8599cf6633d4150d5bef7bc5 | train | function | def copy_file(path, src_path):
output_path = os.environ["output_dir"] + path
copyfile(src_path, output_path)
| def copy_file(path, src_path):
| output_path = os.environ["output_dir"] + path
copyfile(src_path, output_path)
| , content):
output_path = os.environ["output_dir"] + path
output_dir = Path(os.path.dirname(output_path))
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_path, "w+") as f:
f.write(content)
def copy_file(path, src_path):
| 64 | 64 | 30 | 8 | 56 | dolfly/plotfx | extra/web/build_layout.py | Python | copy_file | copy_file | 111 | 113 | 111 | 111 | 64d513a950c64c9cd3d1ce221869129d5028155d | bigcode/the-stack | train |
e0d74de0a7946865fe727138 | train | function | def build_layout(url, content, title=""):
toc = yaml.load(Path("manual/toc.yaml").read_text())["documentation"]
toc = map(lambda x: extend_toc(x), toc)
title_seo = title
if title_seo != "PlotFX":
title_seo += " - PlotFX"
return TPL.render(tpl, {
"content": content,
"url": url,
"toc": toc,
... | def build_layout(url, content, title=""):
| toc = yaml.load(Path("manual/toc.yaml").read_text())["documentation"]
toc = map(lambda x: extend_toc(x), toc)
title_seo = title
if title_seo != "PlotFX":
title_seo += " - PlotFX"
return TPL.render(tpl, {
"content": content,
"url": url,
"toc": toc,
"title": title,
"title_seo": title_s... | </body>
</html>
"""
def extend_toc(entry):
if "pages" in entry:
entry["pages"] = map(lambda x: extend_toc(x), entry["pages"])
else:
entry["pages"] = []
return entry
def build_layout(url, content, title=""):
| 64 | 64 | 189 | 10 | 53 | dolfly/plotfx | extra/web/build_layout.py | Python | build_layout | build_layout | 81 | 99 | 81 | 81 | 5bdc9705fe75ff3af536ecb21ca1067862430887 | bigcode/the-stack | train |
121be310b8b11bc4b0337eea | train | function | def write_file(path, content):
output_path = os.environ["output_dir"] + path
output_dir = Path(os.path.dirname(output_path))
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_path, "w+") as f:
f.write(content)
| def write_file(path, content):
| output_path = os.environ["output_dir"] + path
output_dir = Path(os.path.dirname(output_path))
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_path, "w+") as f:
f.write(content)
| " if url.startswith("/examples") else "",
"menu_active_reference": "active" if url.startswith("/reference") else "",
})
def write_page(url, content, title=""):
write_file(url + "/index.html", build_layout(url, content, title=title))
def write_file(path, content):
| 64 | 64 | 60 | 7 | 57 | dolfly/plotfx | extra/web/build_layout.py | Python | write_file | write_file | 104 | 109 | 104 | 104 | a92904986c5ba6ef9dfdda304234535b8777b67d | bigcode/the-stack | train |
5b2a957886c2efc8dc943303 | train | function | def extend_toc(entry):
if "pages" in entry:
entry["pages"] = map(lambda x: extend_toc(x), entry["pages"])
else:
entry["pages"] = []
return entry
| def extend_toc(entry):
| if "pages" in entry:
entry["pages"] = map(lambda x: extend_toc(x), entry["pages"])
else:
entry["pages"] = []
return entry
| ">
Copyright © 2011-2018 Paul Asmuth, Laura Schlimmer et al. —
PlotFX is free software licensed under a 3-Clause BSD License
</div>
</article>
</body>
</html>
"""
def extend_toc(entry):
| 64 | 64 | 47 | 6 | 58 | dolfly/plotfx | extra/web/build_layout.py | Python | extend_toc | extend_toc | 73 | 79 | 73 | 73 | be7279c64113eac8819b5d0be667b1f98c356bbb | bigcode/the-stack | train |
5d02212053271cc1484ee0b0 | train | function | def _topk(scores, K=40):
batch, num_class, height, width = scores.size()
topk_scores, topk_inds = torch.topk(scores.flatten(2, 3), K)
topk_inds = topk_inds % (height * width)
topk_ys = (topk_inds // width).float()
topk_xs = (topk_inds % width).int().float()
topk_score, topk_ind = tor... | def _topk(scores, K=40):
| batch, num_class, height, width = scores.size()
topk_scores, topk_inds = torch.topk(scores.flatten(2, 3), K)
topk_inds = topk_inds % (height * width)
topk_ys = (topk_inds // width).float()
topk_xs = (topk_inds % width).int().float()
topk_score, topk_ind = torch.topk(topk_scores.view(b... | ather_feat(feat, ind):
feat = feat.permute(0, 2, 3, 1).contiguous()
feat = feat.view(feat.size(0), -1, feat.size(3))
feat = _gather_feat(feat, ind)
return feat
def _topk(scores, K=40):
| 73 | 73 | 246 | 10 | 62 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | _topk | _topk | 136 | 151 | 136 | 136 | 856a9a264fe52cd76bd6d1cb2f377330bdc0785b | bigcode/the-stack | train |
cbff0e5634b7286a987fffdf | train | function | @numba.jit(nopython=True)
def circle_nms(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
scores = dets[:, 2]
order = scores.argsort()[::-1].astype(np.int32) # highest->lowest
ndets = dets.shape[0]
suppressed = np.zeros((ndets), dtype=np.int32)
keep = []
for _i in range(ndets):
... | @numba.jit(nopython=True)
def circle_nms(dets, thresh):
| x1 = dets[:, 0]
y1 = dets[:, 1]
scores = dets[:, 2]
order = scores.argsort()[::-1].astype(np.int32) # highest->lowest
ndets = dets.shape[0]
suppressed = np.zeros((ndets), dtype=np.int32)
keep = []
for _i in range(ndets):
i = order[_i] # start with highest score box
... | =3):
pad = (kernel - 1) // 2
hmax = F.max_pool2d(heat, (kernel, kernel), stride=1, padding=pad)
keep = (hmax == heat).float()
return heat * keep
@numba.jit(nopython=True)
def circle_nms(dets, thresh):
| 77 | 77 | 257 | 19 | 57 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | circle_nms | circle_nms | 80 | 104 | 80 | 81 | 9b563024fb9189c29a732df79b41b12cc78af031 | bigcode/the-stack | train |
9a7566f29f6ca6f0d25ec79d | train | function | def gaussian2D(shape, sigma=1):
m, n = [(ss - 1.) / 2. for ss in shape]
y, x = np.ogrid[-m:m + 1, -n:n + 1]
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
return h
| def gaussian2D(shape, sigma=1):
| m, n = [(ss - 1.) / 2. for ss in shape]
y, x = np.ogrid[-m:m + 1, -n:n + 1]
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
return h
| = (b3 ** 2 - 4 * a3 * c3).sqrt()
r3 = (b3 + sq3) / 2
ret = torch.min(torch.min(r1, r2), r3)
return ret
def gaussian2D(shape, sigma=1):
| 64 | 64 | 98 | 10 | 53 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | gaussian2D | gaussian2D | 38 | 44 | 38 | 38 | a6ed2ed4cf149a33c5159eda213c9e44f5dbc65a | bigcode/the-stack | train |
33f78cdd61bd59cba60c9847 | train | function | def _circle_nms(boxes, min_radius, post_max_size=83):
"""
NMS according to center distance
"""
keep = np.array(circle_nms(boxes.cpu().numpy(), thresh=min_radius))[:post_max_size]
keep = torch.from_numpy(keep).long().to(boxes.device)
return keep
| def _circle_nms(boxes, min_radius, post_max_size=83):
| """
NMS according to center distance
"""
keep = np.array(circle_nms(boxes.cpu().numpy(), thresh=min_radius))[:post_max_size]
keep = torch.from_numpy(keep).long().to(boxes.device)
return keep
| ]) ** 2 + (y1[i] - y1[j]) ** 2
# ovr = inter / areas[j]
if dist <= thresh:
suppressed[j] = 1
return keep
def _circle_nms(boxes, min_radius, post_max_size=83):
| 64 | 64 | 72 | 17 | 46 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | _circle_nms | _circle_nms | 107 | 115 | 107 | 107 | 72707252344f5df5b8fc7ed1b79ac284d894ad0a | bigcode/the-stack | train |
04041ecba1367267e49c3688 | train | function | def gaussian_radius(height, width, min_overlap=0.5):
"""
Args:
height: (N)
width: (N)
min_overlap:
Returns:
"""
a1 = 1
b1 = (height + width)
c1 = width * height * (1 - min_overlap) / (1 + min_overlap)
sq1 = (b1 ** 2 - 4 * a1 * c1).sqrt()
r1 = (b1 +... | def gaussian_radius(height, width, min_overlap=0.5):
| """
Args:
height: (N)
width: (N)
min_overlap:
Returns:
"""
a1 = 1
b1 = (height + width)
c1 = width * height * (1 - min_overlap) / (1 + min_overlap)
sq1 = (b1 ** 2 - 4 * a1 * c1).sqrt()
r1 = (b1 + sq1) / 2
a2 = 4
b2 = 2 * (height + width)... | # This file is modified from https://github.com/tianweiy/CenterPoint
import torch
import torch.nn.functional as F
import numpy as np
import numba
def gaussian_radius(height, width, min_overlap=0.5):
| 51 | 84 | 283 | 14 | 36 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | gaussian_radius | gaussian_radius | 9 | 35 | 9 | 9 | 7cd7085da57c1aeb98165f3160e2420f30b9403b | bigcode/the-stack | train |
d4463c35a6776a5fbdb4f0f4 | train | function | def _transpose_and_gather_feat(feat, ind):
feat = feat.permute(0, 2, 3, 1).contiguous()
feat = feat.view(feat.size(0), -1, feat.size(3))
feat = _gather_feat(feat, ind)
return feat
| def _transpose_and_gather_feat(feat, ind):
| feat = feat.permute(0, 2, 3, 1).contiguous()
feat = feat.view(feat.size(0), -1, feat.size(3))
feat = _gather_feat(feat, ind)
return feat
| feat = feat.gather(1, ind)
if mask is not None:
mask = mask.unsqueeze(2).expand_as(feat)
feat = feat[mask]
feat = feat.view(-1, dim)
return feat
def _transpose_and_gather_feat(feat, ind):
| 64 | 64 | 68 | 12 | 51 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | _transpose_and_gather_feat | _transpose_and_gather_feat | 129 | 133 | 129 | 129 | 956f82dac956c215bc418fb5fc9113f9bfc1e8d6 | bigcode/the-stack | train |
626ef3b514989bfcb18ab1f1 | train | function | def _gather_feat(feat, ind, mask=None):
dim = feat.size(2)
ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim)
feat = feat.gather(1, ind)
if mask is not None:
mask = mask.unsqueeze(2).expand_as(feat)
feat = feat[mask]
feat = feat.view(-1, dim)
return feat
| def _gather_feat(feat, ind, mask=None):
| dim = feat.size(2)
ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim)
feat = feat.gather(1, ind)
if mask is not None:
mask = mask.unsqueeze(2).expand_as(feat)
feat = feat[mask]
feat = feat.view(-1, dim)
return feat
| MS according to center distance
"""
keep = np.array(circle_nms(boxes.cpu().numpy(), thresh=min_radius))[:post_max_size]
keep = torch.from_numpy(keep).long().to(boxes.device)
return keep
def _gather_feat(feat, ind, mask=None):
| 64 | 64 | 94 | 13 | 50 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | _gather_feat | _gather_feat | 118 | 126 | 118 | 118 | 562c7469b128d784f1b9b76a06e5fc4cde972332 | bigcode/the-stack | train |
00828eca0f11f74764a470b0 | train | function | def draw_gaussian_to_heatmap(heatmap, center, radius, k=1, valid_mask=None):
diameter = 2 * radius + 1
gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6)
x, y = int(center[0]), int(center[1])
height, width = heatmap.shape[0:2]
left, right = min(x, radius), min(width - x, radi... | def draw_gaussian_to_heatmap(heatmap, center, radius, k=1, valid_mask=None):
| diameter = 2 * radius + 1
gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6)
x, y = int(center[0]), int(center[1])
height, width = heatmap.shape[0:2]
left, right = min(x, radius), min(width - x, radius + 1)
top, bottom = min(y, radius), min(height - y, radius + 1)
... | id[-m:m + 1, -n:n + 1]
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
return h
def draw_gaussian_to_heatmap(heatmap, center, radius, k=1, valid_mask=None):
| 83 | 83 | 278 | 23 | 59 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | draw_gaussian_to_heatmap | draw_gaussian_to_heatmap | 47 | 69 | 47 | 47 | dfaae6f1f250322da85d893afc11d9f13998c133 | bigcode/the-stack | train |
209ec2d040f010fb0095eae0 | train | function | def _nms(heat, kernel=3):
pad = (kernel - 1) // 2
hmax = F.max_pool2d(heat, (kernel, kernel), stride=1, padding=pad)
keep = (hmax == heat).float()
return heat * keep
| def _nms(heat, kernel=3):
| pad = (kernel - 1) // 2
hmax = F.max_pool2d(heat, (kernel, kernel), stride=1, padding=pad)
keep = (hmax == heat).float()
return heat * keep
| [y - top:y + bottom, x - left:x + right]
masked_gaussian = masked_gaussian * cur_valid_mask.float()
torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap)
return heatmap
def _nms(heat, kernel=3):
| 64 | 64 | 66 | 11 | 52 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | _nms | _nms | 72 | 77 | 72 | 72 | 79690385faf2b733a7ea556e6f96a5bb5f3e9681 | bigcode/the-stack | train |
f3b48588c5cc4fcdb657def9 | train | function | def decode_bbox_from_heatmap(heatmap, rot_cos, rot_sin, center, center_z, dim,
point_cloud_range=None, voxel_size=None, feature_map_stride=None, vel=None, K=100,
circle_nms=False, score_thresh=None, post_center_limit_range=None):
batch_size, num_class, _,... | def decode_bbox_from_heatmap(heatmap, rot_cos, rot_sin, center, center_z, dim,
point_cloud_range=None, voxel_size=None, feature_map_stride=None, vel=None, K=100,
circle_nms=False, score_thresh=None, post_center_limit_range=None):
| batch_size, num_class, _, _ = heatmap.size()
if circle_nms:
# TODO: not checked yet
assert False, 'not checked yet'
heatmap = _nms(heatmap)
scores, inds, class_ids, ys, xs = _topk(heatmap, K=K)
center = _transpose_and_gather_feat(center, inds).view(batch_size, K, 2)
... | _score, topk_ind = torch.topk(topk_scores.view(batch, -1), K)
topk_classes = (topk_ind // K).int()
topk_inds = _gather_feat(topk_inds.view(batch, -1, 1), topk_ind).view(batch, K)
topk_ys = _gather_feat(topk_ys.view(batch, -1, 1), topk_ind).view(batch, K)
topk_xs = _gather_feat(topk_xs.view(batch, -1... | 214 | 214 | 716 | 62 | 151 | twn29004/OpenPCDet | pcdet/models/model_utils/centernet_utils.py | Python | decode_bbox_from_heatmap | decode_bbox_from_heatmap | 154 | 216 | 154 | 156 | 6fd5d0a30e41bbee0323d278292adc8c702627e5 | bigcode/the-stack | train |
b803b5bf1763c269b17444c5 | train | class | class BaseImage(Base):
"""
Object that loads an image, stores as a surface, transform it and
let write the image to a surface.
:param image_path: Path of the image to be loaded. It can be a string (path, base64), :py:class:`pathlib.Path`, or :py:class:`io.BytesIO`
:param drawing_mode: Drawing mode ... | class BaseImage(Base):
| """
Object that loads an image, stores as a surface, transform it and
let write the image to a surface.
:param image_path: Path of the image to be loaded. It can be a string (path, base64), :py:class:`pathlib.Path`, or :py:class:`io.BytesIO`
:param drawing_mode: Drawing mode of the image
:param... | python.svg')
IMAGE_EXAMPLE_WALLPAPER = __images_path__.format('wallpaper.jpg')
IMAGE_EXAMPLES = (IMAGE_EXAMPLE_CARBON_FIBER, IMAGE_EXAMPLE_GRAY_LINES,
IMAGE_EXAMPLE_METAL, IMAGE_EXAMPLE_PYGAME_MENU, IMAGE_EXAMPLE_PYTHON,
IMAGE_EXAMPLE_WALLPAPER)
# Drawing modes
IMAGE_MODE_CENTER = ... | 256 | 256 | 6,333 | 5 | 251 | mrkprdo/pygame-menu | pygame_menu/baseimage.py | Python | BaseImage | BaseImage | 110 | 901 | 110 | 110 | 748b348369bec6855098c06338ffae499ae25a8a | bigcode/the-stack | train |
3901c4a0b4bc7483d05fff4e | train | function | def distill_final_count(duo_counter: Counter, polymer: str) -> Counter:
"""Distill final counter"""
double_final_count = Counter(polymer[0] + polymer[-1])
for chars, count in duo_counter.items():
for char in chars:
double_final_count.update({char: count})
final_counter = Counter({cha... | def distill_final_count(duo_counter: Counter, polymer: str) -> Counter:
| """Distill final counter"""
double_final_count = Counter(polymer[0] + polymer[-1])
for chars, count in duo_counter.items():
for char in chars:
double_final_count.update({char: count})
final_counter = Counter({char: count//2 for char, count in double_final_count.items()})
return f... | : count for duo in inverse_mutation_mapper[triple]})
triple_counts = Counter({mutation_mapper[duo]: count for duo, count in duo_counts.items()})
return duo_counts, triple_counts
def distill_final_count(duo_counter: Counter, polymer: str) -> Counter:
| 64 | 64 | 95 | 19 | 44 | teije01/adventofcode | solutions/2021/day14/day14.py | Python | distill_final_count | distill_final_count | 104 | 111 | 104 | 104 | e75f5bf9cc4f53d98493b5b2c4d8109c39c95fe5 | bigcode/the-stack | train |
3eb6d87ee9656737d6377fff | train | function | def mutate_polymer(polymer, pattern_mapper):
"""
Sequence new polymer based on the previous polymer (slow for large polymers)
"""
polymer_list = [polymer[0]] + [None] * (len(polymer) * 2 - 2)
for position in range(1, len(polymer)):
polymer_list[position * 2 - 1] = pattern_mapper.get(polymer[... | def mutate_polymer(polymer, pattern_mapper):
| """
Sequence new polymer based on the previous polymer (slow for large polymers)
"""
polymer_list = [polymer[0]] + [None] * (len(polymer) * 2 - 2)
for position in range(1, len(polymer)):
polymer_list[position * 2 - 1] = pattern_mapper.get(polymer[position - 1 : position + 1])
polymer... | and find the most and least common
elements in the result. What do you get if you take the quantity of the most common element and
subtract the quantity of the least common element?
"""
from collections import Counter
import itertools
from typing import Dict, Tuple
def mutate_polymer(polymer, pattern_mapper):
| 64 | 64 | 115 | 10 | 53 | teije01/adventofcode | solutions/2021/day14/day14.py | Python | mutate_polymer | mutate_polymer | 79 | 88 | 79 | 79 | 41946a3d2de61d1c3ef456e8952f06603ff7e2bd | bigcode/the-stack | train |
b73d4ff337a212b75ec8daae | train | function | def update_polymer_counters(
triple_counts: Counter,
mutation_mapper: Dict[str, str],
inverse_mutation_mapper: Dict[str, Tuple[str, str]],
) -> Tuple[Counter, Counter]:
"""Polymer update duo counts"""
duo_counts = Counter()
for triple, count in triple_counts.items():
duo_counts.update({d... | def update_polymer_counters(
triple_counts: Counter,
mutation_mapper: Dict[str, str],
inverse_mutation_mapper: Dict[str, Tuple[str, str]],
) -> Tuple[Counter, Counter]:
| """Polymer update duo counts"""
duo_counts = Counter()
for triple, count in triple_counts.items():
duo_counts.update({duo: count for duo in inverse_mutation_mapper[triple]})
triple_counts = Counter({mutation_mapper[duo]: count for duo, count in duo_counts.items()})
return duo_counts, triple_... | polymer_list[position * 2] = polymer[position]
return str.join("", polymer_list)
def update_polymer_counters(
triple_counts: Counter,
mutation_mapper: Dict[str, str],
inverse_mutation_mapper: Dict[str, Tuple[str, str]],
) -> Tuple[Counter, Counter]:
| 64 | 64 | 120 | 44 | 20 | teije01/adventofcode | solutions/2021/day14/day14.py | Python | update_polymer_counters | update_polymer_counters | 91 | 101 | 91 | 95 | 40010fc7dd2a3cf252b58a7741c788a5fa55ef3f | bigcode/the-stack | train |
e0f3392a0efbb3e71f044648 | train | class | class MyModel(QAbstractTableModel):
def __init__(self, parent):
super().__init__(parent)
def rowCount(self, parent):
return 2
def columnCount(self, parent):
return 3
def data(self, index, role):
if role == Qt.DisplayRole:
return "({},{})".format(index.row(... | class MyModel(QAbstractTableModel):
| def __init__(self, parent):
super().__init__(parent)
def rowCount(self, parent):
return 2
def columnCount(self, parent):
return 3
def data(self, index, role):
if role == Qt.DisplayRole:
return "({},{})".format(index.row(), index.column())
return QV... | .qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView, QVBoxLayout, QWidget
class MyModel(QAbstractTableModel):
| 64 | 64 | 85 | 8 | 55 | jeremiedecock/snippets | python/pyqt/pyqt5/widget_QTableView_share_selection_in_two_views.py | Python | MyModel | MyModel | 11 | 26 | 11 | 12 | 4d7c160d7cb89b07762280ab09b1fc0d6ca3a389 | bigcode/the-stack | train |
c4773951f52ad3e317148121 | train | class | @attr('event', 'service')
class EventServiceTest(BaseTestCase):
def test_create_event_service(self):
""" Creating event service"""
service = EventService(db=self.db)
self.assertIsInstance(service, EventService)
def test_raise_validation_errors_when_creating_invalid_event(self):
... | @attr('event', 'service')
class EventServiceTest(BaseTestCase):
| def test_create_event_service(self):
""" Creating event service"""
service = EventService(db=self.db)
self.assertIsInstance(service, EventService)
def test_raise_validation_errors_when_creating_invalid_event(self):
""" Raise validation exception when creating event from bad data... | from tests.base import BaseTestCase
from nose.plugins.attrib import attr
from unittest.mock import MagicMock
from pprint import pprint as pp
from inspect import isclass
from shiftevent import exceptions as x
from shiftevent.event_service import EventService
from shiftevent.event import Event
from shiftevent.handlers i... | 121 | 256 | 2,037 | 16 | 104 | projectshift/shift-event | tests/event_service_test.py | Python | EventServiceTest | EventServiceTest | 17 | 308 | 17 | 19 | 193c81f28afbf1506b09c7ac4911af46e2d34429 | bigcode/the-stack | train |
70e9f75d6110492594c1b773 | train | function | def str_convert(my_string, flag=1):
tmp = str(my_string)
fmt = "{:3.4f}"
output = tmp[2 : len(tmp) - 1]
if flag:
return fmt.format(float(output))
else:
return output
| def str_convert(my_string, flag=1):
| tmp = str(my_string)
fmt = "{:3.4f}"
output = tmp[2 : len(tmp) - 1]
if flag:
return fmt.format(float(output))
else:
return output
| caget', BENDER, '-t']).rstrip()
Bender_force = str_convert(Bender_force)
else:
Bender_force = 'N/A'
return stat, pos, P_gain, I_gain, D_gain, Bender_force
"""
def str_convert(my_string, flag=1):
| 64 | 64 | 59 | 10 | 54 | NSLS-II-FXI/ipython_ophyd | startup/50-save_log.py | Python | str_convert | str_convert | 295 | 302 | 295 | 295 | bd6ff82f976c83522546f66d31f8f12ae738363c | bigcode/the-stack | train |
cb6c26731d0a0e58ae6cdb1f | train | function | def save_pos(print_flag=0, comment=""):
"""
Get motor positions and save to file /nsls2/data/fxi-new/legacy/log/motor_position/
To print it out, set print_flag=1
"""
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for ... | def save_pos(print_flag=0, comment=""):
| """
Get motor positions and save to file /nsls2/data/fxi-new/legacy/log/motor_position/
To print it out, set print_flag=1
"""
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write... | (/nsls2/data/fxi-new/legacy/log/motor_position/) at 11pm everyday.
"""
def __init__(self, interval=1):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):... | 129 | 129 | 430 | 11 | 118 | NSLS-II-FXI/ipython_ophyd | startup/50-save_log.py | Python | save_pos | save_pos | 34 | 84 | 34 | 34 | 76fcd3e54f1e9da49a0f429f215440c7a0fcae1c | bigcode/the-stack | train |
4f30e4dc238a57b55633e45b | train | class | class Auto_Log_Save(object):
"""
Auto save the motor position into logfile (/nsls2/data/fxi-new/legacy/log/motor_position/) at 11pm everyday.
"""
def __init__(self, interval=1):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # ... | class Auto_Log_Save(object):
| """
Auto save the motor position into logfile (/nsls2/data/fxi-new/legacy/log/motor_position/) at 11pm everyday.
"""
def __init__(self, interval=1):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thre... |
import shutil
import inspect
import time
import subprocess
import threading
from datetime import datetime
from pathlib import Path
if not is_re_worker_active():
BlueskyMagics.positioners = motor_txm + motor_optics + motor_pzt + motor_lakeshore
class Auto_Log_Save(object):
| 64 | 64 | 134 | 6 | 57 | NSLS-II-FXI/ipython_ophyd | startup/50-save_log.py | Python | Auto_Log_Save | Auto_Log_Save | 15 | 31 | 15 | 15 | ea6814b51edcf4ed6de5533b385a543a3ff33215 | bigcode/the-stack | train |
d1a4ba130aa878447e7444a8 | train | function | def wh_pos(comment="", print_on_screen=1):
positioners = BlueskyMagics.positioners
values = []
for p in positioners:
try:
values.append(p.position)
except Exception as exc:
values.append(exc)
headers = [
"Positioner",
"Value",
"Unit",
... | def wh_pos(comment="", print_on_screen=1):
| positioners = BlueskyMagics.positioners
values = []
for p in positioners:
try:
values.append(p.position)
except Exception as exc:
values.append(exc)
headers = [
"Positioner",
"Value",
"Unit",
"Low Limit",
"High Limit",
... | current_date = year + "-" + mon + "-" + day
base_dir = Path("/nsls2/data/fxi-new/legacy/log/motor_position/")
base_dir.mkdir(parents=True, exist_ok=True)
fn = f"log-{current_date}_{hour}-{minu}.log"
f = open(base_dir / fn, "w")
"""
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
... | 256 | 256 | 1,244 | 11 | 245 | NSLS-II-FXI/ipython_ophyd | startup/50-save_log.py | Python | wh_pos | wh_pos | 87 | 244 | 87 | 88 | 1e47eec4e097d8c7d3becc10f2520e3dd5b3f25b | bigcode/the-stack | train |
0023d09b08773458429b0a84 | train | function | def generator(image, label):
return (image, label), (label, image)
| def generator(image, label):
| return (image, label), (label, image)
| (
image, 0, offset, CIFAR_IMG_SIZE, CIFAR_IMG_SIZE + offset_mod)
image = tf.image.crop_to_bounding_box(
image, 0, 0, CIFAR_IMG_SIZE, CIFAR_IMG_SIZE)
return image, label
def generator(image, label):
| 64 | 64 | 18 | 6 | 57 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | generator | generator | 131 | 132 | 131 | 131 | 38094a62fe93bcb8d85c5573ff50e6190dd9ee10 | bigcode/the-stack | train |
de866db56bc0349a44119c60 | train | function | def image_erase_random(image, label):
sess = tf.compat.v1.Session()
with sess.as_default():
rand_amts = tf.random.uniform([2])
x = tf.cast(tf.floor(rand_amts[0] * 19) + 4, tf.int32)
y = tf.cast(tf.floor(rand_amts[1] * 19) + 4, tf.int32)
patch = tf.zeros([4, 4])
mask = tf.... | def image_erase_random(image, label):
| sess = tf.compat.v1.Session()
with sess.as_default():
rand_amts = tf.random.uniform([2])
x = tf.cast(tf.floor(rand_amts[0] * 19) + 4, tf.int32)
y = tf.cast(tf.floor(rand_amts[1] * 19) + 4, tf.int32)
patch = tf.zeros([4, 4])
mask = tf.pad(patch, [[x, CIFAR_IMG_SIZE - x - 4... | new_image = tf.py_function(image_rotate_random_py_func,
(image, angle), tf.float32)
new_image = tf.cond(rand_amts[1] > 0, lambda: image, lambda: new_image)
return new_image, label
def image_erase_random(image, label):
| 64 | 64 | 163 | 9 | 54 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | image_erase_random | image_erase_random | 99 | 110 | 99 | 99 | 5d05c0b75739d01ec9dcd9e1283cc188509f0f7a | bigcode/the-stack | train |
04ec14af03dd20e507b8d9f6 | train | function | def image_rotate_random_py_func(image, angle):
rot_mat = cv2.getRotationMatrix2D(
(CIFAR_IMG_SIZE / 2, CIFAR_IMG_SIZE / 2), int(angle), 1.0)
# image = tf.squeeze(image, axis=-1)
rotated = cv2.warpAffine(image.numpy(), rot_mat,
(CIFAR_IMG_SIZE, CIFAR_IMG_SIZE))
return... | def image_rotate_random_py_func(image, angle):
| rot_mat = cv2.getRotationMatrix2D(
(CIFAR_IMG_SIZE / 2, CIFAR_IMG_SIZE / 2), int(angle), 1.0)
# image = tf.squeeze(image, axis=-1)
rotated = cv2.warpAffine(image.numpy(), rot_mat,
(CIFAR_IMG_SIZE, CIFAR_IMG_SIZE))
return rotated
| _IMG_SIZE, CIFAR_IMG_CHANNEL])
image = tf.reshape(image, [CIFAR_IMG_CHANNEL, CIFAR_IMG_SIZE, CIFAR_IMG_SIZE])
image = tf.transpose(image, (1, 2, 0))
return image, label
def image_rotate_random_py_func(image, angle):
| 64 | 64 | 92 | 10 | 53 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | image_rotate_random_py_func | image_rotate_random_py_func | 80 | 86 | 80 | 80 | a6674b725509e7119f20d01ecd08eacef288c3c5 | bigcode/the-stack | train |
c31405504769f13827599279 | train | function | def image_squish_random(image, label):
rand_amts = tf.minimum(tf.abs(tf.random.normal([2], 0, .33)), .9999)
width_mod = tf.cast(tf.floor(
(rand_amts[0] * (CIFAR_IMG_SIZE / 4)) + 1), tf.int32)
offset_mod = tf.cast(tf.floor(rand_amts[1] * 2.0), tf.int32)
offset = (width_mod // 2) + offset_mod
... | def image_squish_random(image, label):
| rand_amts = tf.minimum(tf.abs(tf.random.normal([2], 0, .33)), .9999)
width_mod = tf.cast(tf.floor(
(rand_amts[0] * (CIFAR_IMG_SIZE / 4)) + 1), tf.int32)
offset_mod = tf.cast(tf.floor(rand_amts[1] * 2.0), tf.int32)
offset = (width_mod // 2) + offset_mod
image = tf.image.resize(image,
... | x, CIFAR_IMG_SIZE - x - 4],
[y, CIFAR_IMG_SIZE - y - 4]],
mode='CONSTANT', constant_values=1)
image = tf.multiply(image, tf.expand_dims(mask, -1))
return image, label
def image_squish_random(image, label):
| 68 | 68 | 227 | 10 | 57 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | image_squish_random | image_squish_random | 113 | 128 | 113 | 113 | bc53857ec0b84bc18edb148fe75f97d595e547ac | bigcode/the-stack | train |
22770ed3addd19fda691063e | train | function | def label_smoothing(label, smoothing=0.001):
label -= smoothing * (label - 1. / tf.cast(label.shape[-1], label.dtype))
return label
| def label_smoothing(label, smoothing=0.001):
| label -= smoothing * (label - 1. / tf.cast(label.shape[-1], label.dtype))
return label
|
tf2 = tf.compat.v2
# constants
CIFAR_IMG_SIZE = 32
CIFAR_IMG_CHANNEL = 3
CIFAR_TRAIN_IMAGE_COUNT = 50000
PARALLEL_INPUT_CALLS = 16
def label_smoothing(label, smoothing=0.001):
| 64 | 64 | 38 | 12 | 51 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | label_smoothing | label_smoothing | 31 | 33 | 31 | 31 | 7caf41a7495206a1e63ff2777ef13c66111b37e0 | bigcode/the-stack | train |
2f6e1d51942ca84b78d5a777 | train | function | def generate_tf_data(X_train, y_train, X_test, y_test, batch_size, for_capsule=True):
dataset_train = tf.data.Dataset.from_tensor_slices((X_train, y_train))
dataset_train = dataset_train.shuffle(buffer_size=CIFAR_TRAIN_IMAGE_COUNT)
dataset_train = dataset_train.map(image_rotate_random)
dataset_train = d... | def generate_tf_data(X_train, y_train, X_test, y_test, batch_size, for_capsule=True):
| dataset_train = tf.data.Dataset.from_tensor_slices((X_train, y_train))
dataset_train = dataset_train.shuffle(buffer_size=CIFAR_TRAIN_IMAGE_COUNT)
dataset_train = dataset_train.map(image_rotate_random)
dataset_train = dataset_train.map(image_shift_rand,
num_parallel_... | offset_mod)
image = tf.image.crop_to_bounding_box(
image, 0, 0, CIFAR_IMG_SIZE, CIFAR_IMG_SIZE)
return image, label
def generator(image, label):
return (image, label), (label, image)
def generate_tf_data(X_train, y_train, X_test, y_test, batch_size, for_capsule=True):
| 81 | 81 | 272 | 24 | 57 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | generate_tf_data | generate_tf_data | 135 | 159 | 135 | 135 | a4ce9918319e806bbf084bc1f6de56c9497ca0e2 | bigcode/the-stack | train |
78a37c80f3f2394b69969f5c | train | function | def image_shift_rand(image, label):
image = tf.transpose(image, (2, 0, 1))
image = tf.reshape(image, [CIFAR_IMG_SIZE, CIFAR_IMG_SIZE, CIFAR_IMG_CHANNEL])
nonzero_x_cols = tf.cast(tf.where(tf.greater(
tf.reduce_sum(image, axis=0), 0)), tf.int32)
nonzero_y_rows = tf.cast(tf.where(tf.greater(
... | def image_shift_rand(image, label):
| image = tf.transpose(image, (2, 0, 1))
image = tf.reshape(image, [CIFAR_IMG_SIZE, CIFAR_IMG_SIZE, CIFAR_IMG_CHANNEL])
nonzero_x_cols = tf.cast(tf.where(tf.greater(
tf.reduce_sum(image, axis=0), 0)), tf.int32)
nonzero_y_rows = tf.cast(tf.where(tf.greater(
tf.reduce_sum(image, axis=1), 0))... | ==============================================================================
import numpy as np
import tensorflow as tf
import os
import cv2
from keras_preprocessing.image import ImageDataGenerator
tf2 = tf.compat.v2
# constants
CIFAR_IMG_SIZE = 32
CIFAR_IMG_CHANNEL = 3
CIFAR_TRAIN_IMAGE_COUNT = 50000
PARALLEL_IN... | 188 | 188 | 627 | 8 | 179 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | image_shift_rand | image_shift_rand | 44 | 77 | 44 | 44 | 6c50113a43eb94716bf2f21ef0028452968f214e | bigcode/the-stack | train |
d7c92d317741bd90a1d86240 | train | function | def pre_process(image, label):
image = (image / 256).astype('float32')
label = tf.keras.utils.to_categorical(label, num_classes=10)
label = label_smoothing(label, smoothing=0.02)
return image, label
| def pre_process(image, label):
| image = (image / 256).astype('float32')
label = tf.keras.utils.to_categorical(label, num_classes=10)
label = label_smoothing(label, smoothing=0.02)
return image, label
| = 50000
PARALLEL_INPUT_CALLS = 16
def label_smoothing(label, smoothing=0.001):
label -= smoothing * (label - 1. / tf.cast(label.shape[-1], label.dtype))
return label
# normalize dataset
def pre_process(image, label):
| 64 | 64 | 57 | 7 | 56 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | pre_process | pre_process | 37 | 41 | 37 | 37 | b6ed1465885d933bdd7913df7bdd6ad228f518af | bigcode/the-stack | train |
3bf144cae482a5139477e42f | train | function | def image_rotate_random(image, label):
rand_amts = tf.maximum(tf.minimum(
tf.random.normal([2], 0, .33), .9999), -.9999)
angle = rand_amts[0] * 180 # degrees
new_image = tf.py_function(image_rotate_random_py_func,
(image, angle), tf.float32)
new_image = tf.cond(ra... | def image_rotate_random(image, label):
| rand_amts = tf.maximum(tf.minimum(
tf.random.normal([2], 0, .33), .9999), -.9999)
angle = rand_amts[0] * 180 # degrees
new_image = tf.py_function(image_rotate_random_py_func,
(image, angle), tf.float32)
new_image = tf.cond(rand_amts[1] > 0, lambda: image, lambda: ... | _SIZE / 2), int(angle), 1.0)
# image = tf.squeeze(image, axis=-1)
rotated = cv2.warpAffine(image.numpy(), rot_mat,
(CIFAR_IMG_SIZE, CIFAR_IMG_SIZE))
return rotated
def image_rotate_random(image, label):
| 64 | 64 | 111 | 8 | 55 | StephenTerror/TSSCapsNet | utils/pre_process_cifar10.py | Python | image_rotate_random | image_rotate_random | 89 | 96 | 89 | 89 | 21c24061ca4da6f906d31ef778887a33e957a477 | bigcode/the-stack | train |
1828c0773bb5c6bd66c3eba0 | train | class | class BatchsizeGuesser:
"""Try to figure out the batchsize, but never error out
If this cannot figure out anything else, will fallback to guessing 1
Example
-------
>>> guesser = BatchsizeGuesser()
>>> # Works with simple tensors:
>>> guesser(torch.randn((2,3)))
2
>>> # Works with ... | class BatchsizeGuesser:
| """Try to figure out the batchsize, but never error out
If this cannot figure out anything else, will fallback to guessing 1
Example
-------
>>> guesser = BatchsizeGuesser()
>>> # Works with simple tensors:
>>> guesser(torch.randn((2,3)))
2
>>> # Works with sequences of tensors:
... | setattr(self, key, pinned)
return self
def to(self, *args, **kwargs):
"""In-place move/cast relevant elements.
Passes all arguments to torch.Tensor.to, see its documentation.
"""
for key in self.__device_prep_keys:
value = getattr(self, key)
... | 150 | 150 | 502 | 6 | 143 | anonymspeechbrain/speechbrain | speechbrain/dataio/batch.py | Python | BatchsizeGuesser | BatchsizeGuesser | 190 | 265 | 190 | 190 | 4583973bc12f5f172c3d5e25f1a98d60f162ad23 | bigcode/the-stack | train |
4412f6f93fb7321caf337955 | train | class | class PaddedBatch:
"""Collate_fn when examples are dicts and have variable-length sequences.
Different elements in the examples get matched by key.
All numpy tensors get converted to Torch (PyTorch default_convert)
Then, by default, all torch.Tensor valued elements get padded and support
collective... | class PaddedBatch:
| """Collate_fn when examples are dicts and have variable-length sequences.
Different elements in the examples get matched by key.
All numpy tensors get converted to Torch (PyTorch default_convert)
Then, by default, all torch.Tensor valued elements get padded and support
collective pin_memory() and t... | """Batch collation
Authors
* Anonymous
"""
import collections
import torch
from speechbrain.utils.data_utils import mod_default_collate
from speechbrain.utils.data_utils import recursive_to
from speechbrain.utils.data_utils import batch_pad_right
from torch.utils.data._utils.collate import default_convert
from torch... | 106 | 256 | 1,505 | 5 | 101 | anonymspeechbrain/speechbrain | speechbrain/dataio/batch.py | Python | PaddedBatch | PaddedBatch | 20 | 187 | 20 | 20 | 9fc079a658092b178313b80a864f09383ad8641c | bigcode/the-stack | train |
72acf26874e30e0effd4d7b9 | train | class | class StoryGraph:
"""Graph of the story-steps pooled from all stories in the training data."""
def __init__(
self,
story_steps: List[StoryStep],
story_end_checkpoints: Optional[Dict[Text, Text]] = None,
) -> None:
self.story_steps = story_steps
self.step_lookup = {s.... | class StoryGraph:
| """Graph of the story-steps pooled from all stories in the training data."""
def __init__(
self,
story_steps: List[StoryStep],
story_end_checkpoints: Optional[Dict[Text, Text]] = None,
) -> None:
self.story_steps = story_steps
self.step_lookup = {s.id: s for s in sel... | =False)
)
events.append(ActionExecuted(ACTION_LISTEN_NAME))
return Dialogue(sender_id, events)
def as_story_string(self, flat: bool = False, e2e: bool = False) -> Text:
story_content = ""
# initialize helper for first story step
story_string_helper = StoryStrin... | 256 | 256 | 2,855 | 4 | 252 | rafaelugolini/rasa | rasa/core/training/structures.py | Python | StoryGraph | StoryGraph | 414 | 796 | 414 | 414 | d50cf4d571f1f3fa65c14c25f22ae4443d38ab5f | bigcode/the-stack | train |
46a96fba9209165ef7000cdc | train | class | class StoryStringHelper:
"""A helper class to mark story steps that are inside a form with `form: `
"""
def __init__(
self,
active_form=None,
form_validation=True,
form_rejected=False,
form_prefix_string="",
no_form_prefix_string="",
):
# track ac... | class StoryStringHelper:
| """A helper class to mark story steps that are inside a form with `form: `
"""
def __init__(
self,
active_form=None,
form_validation=True,
form_rejected=False,
form_prefix_string="",
no_form_prefix_string="",
):
# track active form
self.ac... | GENR_"
CHECKPOINT_CYCLE_PREFIX = "CYCL_"
GENERATED_HASH_LENGTH = 5
FORM_PREFIX = "form: "
# prefix for storystep ID to get reproducible sorting results
# will get increased with each new instance
STEP_COUNT = 1
class StoryStringHelper:
| 64 | 64 | 160 | 5 | 58 | rafaelugolini/rasa | rasa/core/training/structures.py | Python | StoryStringHelper | StoryStringHelper | 42 | 63 | 42 | 42 | 6d50a91461f290d7d46855b12ea0899442dd3ef2 | bigcode/the-stack | train |
a917d4bf35f307dcd43d6e51 | train | class | class StoryStep:
"""A StoryStep is a section of a story block between two checkpoints.
NOTE: Checkpoints are not only limited to those manually written
in the story file, but are also implicitly created at points where
multiple intents are separated in one line by chaining them with "OR"s.
"""
... | class StoryStep:
| """A StoryStep is a section of a story block between two checkpoints.
NOTE: Checkpoints are not only limited to those manually written
in the story file, but are also implicitly created at points where
multiple intents are separated in one line by chaining them with "OR"s.
"""
def __init__(
... | = form_validation
# track whether a from was rejected
self.form_rejected = form_rejected
# save story strings with form prefix for later
self.form_prefix_string = form_prefix_string
# save story strings without form prefix for later
self.no_form_prefix_string = no_form_p... | 256 | 256 | 1,962 | 4 | 252 | rafaelugolini/rasa | rasa/core/training/structures.py | Python | StoryStep | StoryStep | 94 | 354 | 94 | 94 | 34d1d54da0c8101ed949d89e4d75b058f406afc6 | bigcode/the-stack | train |
8dc7be819219b9b5b65ebf17 | train | class | class Checkpoint:
def __init__(
self, name: Optional[Text], conditions: Optional[Dict[Text, Any]] = None
) -> None:
self.name = name
self.conditions = conditions if conditions else {}
def as_story_string(self):
dumped_conds = json.dumps(self.conditions) if self.conditions e... | class Checkpoint:
| def __init__(
self, name: Optional[Text], conditions: Optional[Dict[Text, Any]] = None
) -> None:
self.name = name
self.conditions = conditions if conditions else {}
def as_story_string(self):
dumped_conds = json.dumps(self.conditions) if self.conditions else ""
ret... | whether a from was rejected
self.form_rejected = form_rejected
# save story strings with form prefix for later
self.form_prefix_string = form_prefix_string
# save story strings without form prefix for later
self.no_form_prefix_string = no_form_prefix_string
class Checkpoint:
| 64 | 64 | 185 | 4 | 59 | rafaelugolini/rasa | rasa/core/training/structures.py | Python | Checkpoint | Checkpoint | 66 | 91 | 66 | 66 | 4abe203ab5142dd1f5944824afa28d2aa8ae43f1 | bigcode/the-stack | train |
2b2c670bef760507c1381585 | train | class | class Story:
def __init__(
self, story_steps: List[StoryStep] = None, story_name: Optional[Text] = None
) -> None:
self.story_steps = story_steps if story_steps else []
self.story_name = story_name
@staticmethod
def from_events(events, story_name=None):
"""Create a story... | class Story:
| def __init__(
self, story_steps: List[StoryStep] = None, story_name: Optional[Text] = None
) -> None:
self.story_steps = story_steps if story_steps else []
self.story_name = story_name
@staticmethod
def from_events(events, story_name=None):
"""Create a story from a list ... | (domain.slots_for_entities(e.entities))
else:
events.append(e)
if not self.end_checkpoints and should_append_final_listen:
self._add_action_listen(events)
return events
def __repr__(self):
return (
"StoryStep("
"block_name={!... | 121 | 121 | 404 | 3 | 118 | rafaelugolini/rasa | rasa/core/training/structures.py | Python | Story | Story | 357 | 411 | 357 | 357 | ba1d03fd083efc117e57bb11b7131bb2a48ced16 | bigcode/the-stack | train |
e970cb8728907915bc2e7cab | train | function | def _cleanup():
"""Remove temporary files"""
shutil.rmtree(tempdir)
| def _cleanup():
| """Remove temporary files"""
shutil.rmtree(tempdir)
| (r'\s*\(.*\)\s*')
null_file = open(os.devnull, "w")
logger = logging.getLogger("parsedmarc")
mailparser_logger = logging.getLogger("mailparser")
mailparser_logger.setLevel(logging.CRITICAL)
tempdir = tempfile.mkdtemp()
def _cleanup():
| 64 | 64 | 17 | 4 | 60 | Robitx/parsedmarc | parsedmarc/utils.py | Python | _cleanup | _cleanup | 44 | 46 | 44 | 44 | ab3b25e1ca1a2c283fa59f5ac3463e4f21418566 | bigcode/the-stack | train |
45ac0b5031c09b69fed0d531 | train | class | class EmailParserError(RuntimeError):
"""Raised when an error parsing the email occurs"""
| class EmailParserError(RuntimeError):
| """Raised when an error parsing the email occurs"""
| Logger("parsedmarc")
mailparser_logger = logging.getLogger("mailparser")
mailparser_logger.setLevel(logging.CRITICAL)
tempdir = tempfile.mkdtemp()
def _cleanup():
"""Remove temporary files"""
shutil.rmtree(tempdir)
atexit.register(_cleanup)
class EmailParserError(RuntimeError):
| 64 | 64 | 18 | 7 | 57 | Robitx/parsedmarc | parsedmarc/utils.py | Python | EmailParserError | EmailParserError | 52 | 53 | 52 | 52 | f925963bbec691bc456ecc9bd21154cd549c9913 | bigcode/the-stack | train |
04172d89ff3f2d499d596cb7 | train | function | def is_mbox(path):
"""
Checks if the given content is a MBOX mailbox file
Args:
path: Content to check
Returns:
bool: A flag the indicates if a file is a MBOX mailbox file
"""
_is_mbox = False
try:
mbox = mailbox.mbox(path)
if len(mbox.keys()) > 0:
... | def is_mbox(path):
| """
Checks if the given content is a MBOX mailbox file
Args:
path: Content to check
Returns:
bool: A flag the indicates if a file is a MBOX mailbox file
"""
_is_mbox = False
try:
mbox = mailbox.mbox(path)
if len(mbox.keys()) > 0:
_is_mbox = True
... | ', '/', ':', '"', '*', '?', '|', '\n',
'\r']
if string is None:
string = "None"
for char in invalid_filename_chars:
string = string.replace(char, "")
string = string.rstrip(".")
return string
def is_mbox(path):
| 64 | 64 | 125 | 6 | 57 | Robitx/parsedmarc | parsedmarc/utils.py | Python | is_mbox | is_mbox | 401 | 419 | 401 | 401 | 4ee6c13128a4e7c71eb46e4c469320720d06a237 | bigcode/the-stack | train |
a51a590edf46fd34ea3e74a9 | train | function | def convert_outlook_msg(msg_bytes):
"""
Uses the ``msgconvert`` Perl utility to convert an Outlook MS file to
standard RFC 822 format
Args:
msg_bytes (bytes): the content of the .msg file
Returns:
A RFC 822 string
"""
if not is_outlook_msg(msg_bytes):
raise ValueErr... | def convert_outlook_msg(msg_bytes):
| """
Uses the ``msgconvert`` Perl utility to convert an Outlook MS file to
standard RFC 822 format
Args:
msg_bytes (bytes): the content of the .msg file
Returns:
A RFC 822 string
"""
if not is_outlook_msg(msg_bytes):
raise ValueError("The supplied bytes are not an Ou... | : Content to check
Returns:
bool: A flag the indicates if a file is a Outlook MSG file
"""
return type(content) == bytes and content.startswith(
b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1")
def convert_outlook_msg(msg_bytes):
| 71 | 71 | 239 | 8 | 63 | Robitx/parsedmarc | parsedmarc/utils.py | Python | convert_outlook_msg | convert_outlook_msg | 436 | 467 | 436 | 436 | f3187012982e8a8bc546bdde5ff49c06fe15850f | bigcode/the-stack | train |
4998ad19c1a5dfa90b04d6a7 | train | function | def query_dns(domain, record_type, cache=None, nameservers=None, timeout=2.0):
"""
Queries DNS
Args:
domain (str): The domain or subdomain to query about
record_type (str): The record type to query for
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or ... | def query_dns(domain, record_type, cache=None, nameservers=None, timeout=2.0):
| """
Queries DNS
Args:
domain (str): The domain or subdomain to query about
record_type (str): The record type to query for
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
... | ()
else:
psl_age = datetime.now() - datetime.fromtimestamp(
os.stat(psl_path).st_mtime)
if psl_age > timedelta(hours=24):
download_psl()
with open(psl_path, encoding="utf-8") as psl_file:
psl = publicsuffix2.PublicSuffixList(psl_file)
... | 119 | 119 | 399 | 21 | 98 | Robitx/parsedmarc | parsedmarc/utils.py | Python | query_dns | query_dns | 125 | 172 | 125 | 125 | f5d23f704502fa6dfe927df3922a49eb984723ef | bigcode/the-stack | train |
382b915fbc98e90230963e2f | train | function | def parse_email(data, strip_attachment_payloads=False):
"""
A simplified email parser
Args:
data: The RFC 822 message string, or MSG binary
strip_attachment_payloads (bool): Remove attachment payloads
Returns (dict): Parsed email data
"""
if type(data) == bytes:
if is_... | def parse_email(data, strip_attachment_payloads=False):
| """
A simplified email parser
Args:
data: The RFC 822 message string, or MSG binary
strip_attachment_payloads (bool): Remove attachment payloads
Returns (dict): Parsed email data
"""
if type(data) == bytes:
if is_outlook_msg(data):
data = convert_outlook_ms... | to convert an Outlook MS file to
standard RFC 822 format
Args:
msg_bytes (bytes): the content of the .msg file
Returns:
A RFC 822 string
"""
if not is_outlook_msg(msg_bytes):
raise ValueError("The supplied bytes are not an Outlook MSG file")
orig_dir = os.getcwd()
... | 231 | 231 | 771 | 11 | 219 | Robitx/parsedmarc | parsedmarc/utils.py | Python | parse_email | parse_email | 470 | 573 | 470 | 470 | a818fa73013d38e2756191b6b62792a4c073d9bb | bigcode/the-stack | train |
1b5d3677e7aba89c6f750b4d | train | function | def timestamp_to_datetime(timestamp):
"""
Converts a UNIX/DMARC timestamp to a Python ``DateTime`` object
Args:
timestamp (int): The timestamp
Returns:
DateTime: The converted timestamp as a Python ``DateTime`` object
"""
return datetime.fromtimestamp(int(timestamp))
| def timestamp_to_datetime(timestamp):
| """
Converts a UNIX/DMARC timestamp to a Python ``DateTime`` object
Args:
timestamp (int): The timestamp
Returns:
DateTime: The converted timestamp as a Python ``DateTime`` object
"""
return datetime.fromtimestamp(int(timestamp))
| try:
address = dns.reversename.from_address(ip_address)
hostname = query_dns(address, "PTR", cache=cache,
nameservers=nameservers,
timeout=timeout)[0]
except dns.exception.DNSException:
pass
return hostname
def timestamp_to_... | 64 | 64 | 65 | 6 | 57 | Robitx/parsedmarc | parsedmarc/utils.py | Python | timestamp_to_datetime | timestamp_to_datetime | 202 | 212 | 202 | 202 | cef1f65ee92b48fe237bf0b551024ba68fc1c7ce | bigcode/the-stack | train |
4051c6100363756a5f175054 | train | function | def decode_base64(data):
"""
Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes
"""
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=... | def decode_base64(data):
| """
Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes
"""
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=' * (4 - missing_padding)... | ():
"""Remove temporary files"""
shutil.rmtree(tempdir)
atexit.register(_cleanup)
class EmailParserError(RuntimeError):
"""Raised when an error parsing the email occurs"""
class DownloadError(RuntimeError):
"""Rasied when an error occurs when downloading a file"""
def decode_base64(data):
| 64 | 64 | 96 | 6 | 58 | Robitx/parsedmarc | parsedmarc/utils.py | Python | decode_base64 | decode_base64 | 60 | 75 | 60 | 60 | 6fe950c2baa0867d9df5a89851bb30c7892f043e | bigcode/the-stack | train |
4de1578afc18d1b61b1e2b8b | train | class | class DownloadError(RuntimeError):
"""Rasied when an error occurs when downloading a file"""
| class DownloadError(RuntimeError):
| """Rasied when an error occurs when downloading a file"""
| mailparser_logger.setLevel(logging.CRITICAL)
tempdir = tempfile.mkdtemp()
def _cleanup():
"""Remove temporary files"""
shutil.rmtree(tempdir)
atexit.register(_cleanup)
class EmailParserError(RuntimeError):
"""Raised when an error parsing the email occurs"""
class DownloadError(RuntimeError):
| 64 | 64 | 20 | 6 | 58 | Robitx/parsedmarc | parsedmarc/utils.py | Python | DownloadError | DownloadError | 56 | 57 | 56 | 56 | 2bf876b1f7f027eea8261c99e9a18b7293521fa1 | bigcode/the-stack | train |
47990b30bb8e8603df92ec13 | train | function | def get_filename_safe_string(string):
"""
Converts a string to a string that is safe for a filename
Args:
string (str): A string to make safe for a filename
Returns:
str: A string safe for a filename
"""
invalid_filename_chars = ['\\', '/', ':', '"', '*', '?', '|', '\n',
... | def get_filename_safe_string(string):
| """
Converts a string to a string that is safe for a filename
Args:
string (str): A string to make safe for a filename
Returns:
str: A string safe for a filename
"""
invalid_filename_chars = ['\\', '/', ':', '"', '*', '?', '|', '\n',
'\r']
if st... | _parts) > 1:
local = address_parts[0].lower()
domain = address_parts[-1].lower()
return OrderedDict([("display_name", display_name),
("address", address),
("local", local),
("domain", domain)])
def get_filename_safe_string(stri... | 63 | 64 | 120 | 7 | 56 | Robitx/parsedmarc | parsedmarc/utils.py | Python | get_filename_safe_string | get_filename_safe_string | 381 | 398 | 381 | 381 | 8eec1db7001d4324451d553959603eddad8b71e8 | bigcode/the-stack | train |
bc08362de8c44400ce454eb3 | train | function | def timestamp_to_human(timestamp):
"""
Converts a UNIX/DMARC timestamp to a human-readable string
Args:
timestamp: The timestamp
Returns:
str: The converted timestamp in ``YYYY-MM-DD HH:MM:SS`` format
"""
return timestamp_to_datetime(timestamp).strftime("%Y-%m-%d %H:%M:%S")
| def timestamp_to_human(timestamp):
| """
Converts a UNIX/DMARC timestamp to a human-readable string
Args:
timestamp: The timestamp
Returns:
str: The converted timestamp in ``YYYY-MM-DD HH:MM:SS`` format
"""
return timestamp_to_datetime(timestamp).strftime("%Y-%m-%d %H:%M:%S")
| Converts a UNIX/DMARC timestamp to a Python ``DateTime`` object
Args:
timestamp (int): The timestamp
Returns:
DateTime: The converted timestamp as a Python ``DateTime`` object
"""
return datetime.fromtimestamp(int(timestamp))
def timestamp_to_human(timestamp):
| 64 | 64 | 77 | 7 | 57 | Robitx/parsedmarc | parsedmarc/utils.py | Python | timestamp_to_human | timestamp_to_human | 215 | 225 | 215 | 215 | 56506fffd412dbe08f3c9b311e63dc46d2a997cb | bigcode/the-stack | train |
92ad1b83fa70195a2db0c5dd | train | function | def human_timestamp_to_timestamp(human_timestamp):
"""
Converts a human-readable timestamp into a into a UNIX timestamp
Args:
human_timestamp (str): A timestamp in `YYYY-MM-DD HH:MM:SS`` format
Returns:
float: The converted timestamp
"""
human_timestamp = human_timestamp.replac... | def human_timestamp_to_timestamp(human_timestamp):
| """
Converts a human-readable timestamp into a into a UNIX timestamp
Args:
human_timestamp (str): A timestamp in `YYYY-MM-DD HH:MM:SS`` format
Returns:
float: The converted timestamp
"""
human_timestamp = human_timestamp.replace("T", " ")
return human_timestamp_to_datetime(... | _timestamp = human_timestamp.replace("-0000", "")
human_timestamp = parenthesis_regex.sub("", human_timestamp)
settings = {}
if to_utc:
settings = {"TO_TIMEZONE": "UTC"}
return dateparser.parse(human_timestamp, settings=settings)
def human_timestamp_to_timestamp(human_timestamp):
| 64 | 64 | 84 | 9 | 55 | Robitx/parsedmarc | parsedmarc/utils.py | Python | human_timestamp_to_timestamp | human_timestamp_to_timestamp | 250 | 261 | 250 | 250 | 6dfcbb3f21e647490c862632fdaf315590d8b5e7 | bigcode/the-stack | train |
ec8c207a51ba7eff85850ee6 | train | function | def parse_email_address(original_address):
if original_address[0] == "":
display_name = None
else:
display_name = original_address[0]
address = original_address[1]
address_parts = address.split("@")
local = None
domain = None
if len(address_parts) > 1:
local = address... | def parse_email_address(original_address):
| if original_address[0] == "":
display_name = None
else:
display_name = original_address[0]
address = original_address[1]
address_parts = address.split("@")
local = None
domain = None
if len(address_parts) > 1:
local = address_parts[0].lower()
domain = address_... | ["country"] = country
info["reverse_dns"] = reverse_dns
info["base_domain"] = None
if reverse_dns is not None:
base_domain = get_base_domain(reverse_dns)
info["base_domain"] = base_domain
return info
def parse_email_address(original_address):
| 64 | 64 | 120 | 7 | 56 | Robitx/parsedmarc | parsedmarc/utils.py | Python | parse_email_address | parse_email_address | 362 | 378 | 362 | 362 | 7534180d3151c8ce8b93fbfb9a952d8de0a8a59c | bigcode/the-stack | train |
9783666b27485f1e9cbafe07 | train | function | def human_timestamp_to_datetime(human_timestamp, to_utc=False):
"""
Converts a human-readable timestamp into a Python ``DateTime`` object
Args:
human_timestamp (str): A timestamp string
to_utc (bool): Convert the timestamp to UTC
Returns:
DateTime: The converted timestamp
"... | def human_timestamp_to_datetime(human_timestamp, to_utc=False):
| """
Converts a human-readable timestamp into a Python ``DateTime`` object
Args:
human_timestamp (str): A timestamp string
to_utc (bool): Convert the timestamp to UTC
Returns:
DateTime: The converted timestamp
"""
human_timestamp = human_timestamp.replace("-0000", "")
... | timestamp: The timestamp
Returns:
str: The converted timestamp in ``YYYY-MM-DD HH:MM:SS`` format
"""
return timestamp_to_datetime(timestamp).strftime("%Y-%m-%d %H:%M:%S")
def human_timestamp_to_datetime(human_timestamp, to_utc=False):
| 64 | 64 | 127 | 14 | 50 | Robitx/parsedmarc | parsedmarc/utils.py | Python | human_timestamp_to_datetime | human_timestamp_to_datetime | 228 | 247 | 228 | 228 | 1674f75547b3ca9c17eeaa157bb1e560a2f43578 | bigcode/the-stack | train |
6ec60bbeecc3ade99d165564 | train | function | def get_ip_address_info(ip_address, cache=None, offline=False,
nameservers=None, timeout=2.0, parallel=False):
"""
Returns reverse DNS and country information for the given IP address
Args:
ip_address (str): The IP address to check
cache (ExpiringDict): Cache storage... | def get_ip_address_info(ip_address, cache=None, offline=False,
nameservers=None, timeout=2.0, parallel=False):
| """
Returns reverse DNS and country information for the given IP address
Args:
ip_address (str): The IP address to check
cache (ExpiringDict): Cache storage
offline (bool): Do not make online queries for geolocation or DNS
nameservers (list): A list of one or more nameserver... | a week old")
db_path = db_path
db_reader = geoip2.database.Reader(db_path)
country = None
try:
country = db_reader.country(ip_address).country.iso_code
except geoip2.errors.AddressNotFoundError:
pass
return country
def get_ip_address_info(ip_address, cache=None, offline=... | 90 | 90 | 302 | 28 | 61 | Robitx/parsedmarc | parsedmarc/utils.py | Python | get_ip_address_info | get_ip_address_info | 320 | 359 | 320 | 321 | 6d9185a440fd25597030569413c261abd1499d20 | bigcode/the-stack | train |
cb8db0ade16a8cbccb66b1a8 | train | function | def get_base_domain(domain, use_fresh_psl=False):
"""
Gets the base domain name for the given domain
.. note::
Results are based on a list of public domain suffixes at
https://publicsuffix.org/list/public_suffix_list.dat.
Args:
domain (str): A domain or subdomain
use_fr... | def get_base_domain(domain, use_fresh_psl=False):
| """
Gets the base domain name for the given domain
.. note::
Results are based on a list of public domain suffixes at
https://publicsuffix.org/list/public_suffix_list.dat.
Args:
domain (str): A domain or subdomain
use_fresh_psl (bool): Download a fresh Public Suffix Lis... | decode_base64(data):
"""
Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes
"""
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=' *... | 108 | 108 | 361 | 13 | 95 | Robitx/parsedmarc | parsedmarc/utils.py | Python | get_base_domain | get_base_domain | 78 | 122 | 78 | 78 | 9b5ea252a6452aac10cfb2da4c1f48344fbb9598 | bigcode/the-stack | train |
0ff09ac95adf9341f8e251f8 | train | function | def is_outlook_msg(content):
"""
Checks if the given content is a Outlook msg OLE file
Args:
content: Content to check
Returns:
bool: A flag the indicates if a file is a Outlook MSG file
"""
return type(content) == bytes and content.startswith(
b"\xD0\xCF\x11\xE0\xA1\xB... | def is_outlook_msg(content):
| """
Checks if the given content is a Outlook msg OLE file
Args:
content: Content to check
Returns:
bool: A flag the indicates if a file is a Outlook MSG file
"""
return type(content) == bytes and content.startswith(
b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1")
| mailbox.mbox(path)
if len(mbox.keys()) > 0:
_is_mbox = True
except Exception as e:
logger.debug("Error checking for MBOX file: {0}".format(e.__str__()))
return _is_mbox
def is_outlook_msg(content):
| 64 | 64 | 91 | 7 | 56 | Robitx/parsedmarc | parsedmarc/utils.py | Python | is_outlook_msg | is_outlook_msg | 422 | 433 | 422 | 422 | da3fd93e2103ed220f8a092b1d430d1e2374b3b0 | bigcode/the-stack | train |
97dd1d76fe1ed2882f16671b | train | function | def get_ip_address_country(ip_address):
"""
Uses the MaxMind Geolite2 Country database to return the ISO code for the
country associated with the given IPv4 or IPv6 address
Args:
ip_address (str): The IP address to query for
Returns:
str: And ISO country code associated with the gi... | def get_ip_address_country(ip_address):
| """
Uses the MaxMind Geolite2 Country database to return the ISO code for the
country associated with the given IPv4 or IPv6 address
Args:
ip_address (str): The IP address to query for
Returns:
str: And ISO country code associated with the given IP address
"""
system_paths ... | .sub("", human_timestamp)
settings = {}
if to_utc:
settings = {"TO_TIMEZONE": "UTC"}
return dateparser.parse(human_timestamp, settings=settings)
def human_timestamp_to_timestamp(human_timestamp):
"""
Converts a human-readable timestamp into a into a UNIX timestamp
Args:
huma... | 130 | 130 | 434 | 8 | 122 | Robitx/parsedmarc | parsedmarc/utils.py | Python | get_ip_address_country | get_ip_address_country | 264 | 317 | 264 | 264 | a1d6627fbb1ce6a0fbd32f68efc5e912947a60a5 | bigcode/the-stack | train |
9d48cb1936996bbc6debffdd | train | function | def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
"""
Resolves an IP address to a hostname using a reverse DNS query
Args:
ip_address (str): The IP address to resolve
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers ... | def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
| """
Resolves an IP address to a hostname using a reverse DNS query
Args:
ip_address (str): The IP address to resolve
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
timeou... | lambda r: r.to_text().replace('"', '').rstrip("."),
resolver.query(domain, record_type, lifetime=timeout)))
if cache:
cache[cache_key] = records
return records
def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
| 64 | 64 | 183 | 20 | 43 | Robitx/parsedmarc | parsedmarc/utils.py | Python | get_reverse_dns | get_reverse_dns | 175 | 199 | 175 | 175 | 19a6dfb053bf23a319cb628461e169b45296108b | bigcode/the-stack | train |
b07da6699490c67285c9b49d | train | class | class FeedForwardTransformer(torch.nn.Module):
def __init__(self, idim: int, odim: int, hp: Dict):
"""Initialize feed-forward Transformer module.
Args:
idim (int): Dimension of the inputs.
odim (int): Dimension of the outputs.
"""
# initialize base classes
... | class FeedForwardTransformer(torch.nn.Module):
| def __init__(self, idim: int, odim: int, hp: Dict):
"""Initialize feed-forward Transformer module.
Args:
idim (int): Dimension of the inputs.
odim (int): Dimension of the outputs.
"""
# initialize base classes
assert check_argument_types()
torc... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""FastSpeech related loss."""
import logging
import torch
from core.duration_modeling.duration_predictor import DurationPredictor
from core.duration_modeling.duration_predictor... | 211 | 256 | 2,025 | 8 | 202 | karan-deepsync/FastSpeech2 | utils/fastspeech2_script.py | Python | FeedForwardTransformer | FeedForwardTransformer | 28 | 249 | 28 | 28 | facaf1db369b80d629c538538265194b85e15489 | bigcode/the-stack | train |
9a9ca3e4dd24d6b93d3b6757 | train | class | class ConsoleOutput(Label):
pass
| class ConsoleOutput(Label):
| pass
| run_cmd(self, cmd, *args):
commands = cmd.split("\n")
_num = len(commands)
_idx = 0
while(_idx < _num):
if not EQ.full():
EQ.put(commands[_idx])
_idx += 1
class ConsoleOutput(Label):
| 64 | 64 | 8 | 5 | 58 | Stanford-BIS/pystorm | src/bindings/python/3.5/DriverGUI/console.py | Python | ConsoleOutput | ConsoleOutput | 133 | 134 | 133 | 133 | 729ab233b0589f640b6a80a5036ea160df3461b0 | bigcode/the-stack | train |
093fc68bf9b5b4e3f6299145 | train | class | class Shell(EventDispatcher):
__events__ = ('on_output', 'on_complete')
def run_command(self, command, show_output=True, *args):
_old_stdout = sys.stdout
_old_stderr = sys.stderr
_redirected_output = sys.stdout = StringIO()
_redirected_error = sys.stderr = StringIO()
_su... | class Shell(EventDispatcher):
| __events__ = ('on_output', 'on_complete')
def run_command(self, command, show_output=True, *args):
_old_stdout = sys.stdout
_old_stderr = sys.stderr
_redirected_output = sys.stdout = StringIO()
_redirected_error = sys.stderr = StringIO()
_success = True
try:
... | directories
:return:
"""
import re
_pwd = os.getcwd()
_home = os.path.expanduser('~')
_pwd = re.sub(_home, "~", _pwd)
_paths = _pwd.split('/')
if len(_paths) > 4:
_pwd = "%s/%s/.../%s/%s" % (_paths[0], _paths[1], _paths[-2], _paths[-1])
return _pwd
class Shell(EventDispatch... | 107 | 107 | 359 | 5 | 101 | Stanford-BIS/pystorm | src/bindings/python/3.5/DriverGUI/console.py | Python | Shell | Shell | 40 | 88 | 40 | 40 | 77af9a59992de1d390a9491531038d75c8fcdaa9 | bigcode/the-stack | train |
538d0184231e6adc2cc26d37 | train | class | class KivyConsole(BoxLayout, Shell):
"""Instance of BoxLayout
:data:`console_input` is a :class:`~kivy.properties.ObjectProperty`
"""
console_area = ObjectProperty(None)
"""Instance of :class:`~kivy.uix.scrollview.ScrollView`
:data:`scroll_view` is a :class:`~kivy.properties.ObjectProper... | class KivyConsole(BoxLayout, Shell):
| """Instance of BoxLayout
:data:`console_input` is a :class:`~kivy.properties.ObjectProperty`
"""
console_area = ObjectProperty(None)
"""Instance of :class:`~kivy.uix.scrollview.ScrollView`
:data:`scroll_view` is a :class:`~kivy.properties.ObjectProperty`
"""
scroll_view = ObjectPr... | _key_down(
window, keycode, text, modifiers)
def _run_cmd(self, cmd, *args):
commands = cmd.split("\n")
_num = len(commands)
_idx = 0
while(_idx < _num):
if not EQ.full():
EQ.put(commands[_idx])
_idx += 1
class ConsoleOutput(L... | 252 | 252 | 843 | 9 | 242 | Stanford-BIS/pystorm | src/bindings/python/3.5/DriverGUI/console.py | Python | KivyConsole | KivyConsole | 154 | 262 | 154 | 155 | c600ba22ae01322fe7d8725fa8fe69c008f6f81e | bigcode/the-stack | train |
ef78c9b3e26cf05a18f17fbb | train | function | def _truncate_pwd():
"""
Truncate path if it is more than 4 directories
:return:
"""
import re
_pwd = os.getcwd()
_home = os.path.expanduser('~')
_pwd = re.sub(_home, "~", _pwd)
_paths = _pwd.split('/')
if len(_paths) > 4:
_pwd = "%s/%s/.../%s/%s" % (_paths[0], _paths[1]... | def _truncate_pwd():
| """
Truncate path if it is more than 4 directories
:return:
"""
import re
_pwd = os.getcwd()
_home = os.path.expanduser('~')
_pwd = re.sub(_home, "~", _pwd)
_paths = _pwd.split('/')
if len(_paths) > 4:
_pwd = "%s/%s/.../%s/%s" % (_paths[0], _paths[1], _paths[-2], _paths[... | .uix.label import Label
from kivy.metrics import sp
import os
import threading
import queue
from io import StringIO
import sys
import traceback
# message queue for REPL
EQ = queue.Queue(1)
# namespace for the console interpreter
NS = {}
def _truncate_pwd():
| 63 | 64 | 120 | 5 | 58 | Stanford-BIS/pystorm | src/bindings/python/3.5/DriverGUI/console.py | Python | _truncate_pwd | _truncate_pwd | 24 | 37 | 24 | 24 | e5e3ed057fdf0225d4b280215cede6e8d3a6b052 | bigcode/the-stack | train |
6ca4387cd95e6d9b2ac9c1cf | train | class | class ConsoleInput(TextInput):
"""
Displays Output and sends input to Shell. Emits 'on_ready_to_input'
when it is ready to get input from user.
"""
# Instance of KivyConsole(parent) widget
shell = ObjectProperty(None)
# Active prompt
current_prompt = ObjectProperty(None)
def __ini... | class ConsoleInput(TextInput):
| """
Displays Output and sends input to Shell. Emits 'on_ready_to_input'
when it is ready to get input from user.
"""
# Instance of KivyConsole(parent) widget
shell = ObjectProperty(None)
# Active prompt
current_prompt = ObjectProperty(None)
def __init__(self, **kwargs):
su... | , **kwargs):
"""
Main REPL loop
"""
while(self._do_run):
if not EQ.empty():
_item = EQ.get()
self.run_command(_item)
def init(self, *args, **kwargs):
self._do_run = True
self.run_thread = threading.Thread(target=self.main_l... | 91 | 91 | 304 | 6 | 85 | Stanford-BIS/pystorm | src/bindings/python/3.5/DriverGUI/console.py | Python | ConsoleInput | ConsoleInput | 91 | 131 | 91 | 91 | cda352b492610128b27239f7602195e1934124cd | bigcode/the-stack | train |
bb7666810086b6f0c797a047 | train | class | class ConsolePrompt(BoxLayout):
ps1_text = StringProperty('>')
font_name = StringProperty('Inconsolata-Regular.ttf')
font_size = NumericProperty(28)
prompt_ps1 = ObjectProperty(None)
prompt_input = ObjectProperty(None)
prompt_height = NumericProperty(sp(20))
def __init__(self, **kwargs):
... | class ConsolePrompt(BoxLayout):
| ps1_text = StringProperty('>')
font_name = StringProperty('Inconsolata-Regular.ttf')
font_size = NumericProperty(28)
prompt_ps1 = ObjectProperty(None)
prompt_input = ObjectProperty(None)
prompt_height = NumericProperty(sp(20))
def __init__(self, **kwargs):
super(ConsolePrompt, self... | commands = cmd.split("\n")
_num = len(commands)
_idx = 0
while(_idx < _num):
if not EQ.full():
EQ.put(commands[_idx])
_idx += 1
class ConsoleOutput(Label):
pass
class ConsolePrompt(BoxLayout):
| 64 | 64 | 160 | 6 | 57 | Stanford-BIS/pystorm | src/bindings/python/3.5/DriverGUI/console.py | Python | ConsolePrompt | ConsolePrompt | 136 | 152 | 136 | 136 | 075a56db93728eb190f3421d43ffcb40da896cfc | bigcode/the-stack | train |
b4c02ed45ff4034dbd69f001 | train | class | class Individual(object):
def __init__(self, chromosome):
self.chromosome = chromosome
self.fitness = self.calc_fitness()
def calc_fitness(self):
fit = self.check_for_vert_hor_attacks()
fit += self.check_for_diag_attacks()
return fit
# check_for_diag_attac... | class Individual(object):
| def __init__(self, chromosome):
self.chromosome = chromosome
self.fitness = self.calc_fitness()
def calc_fitness(self):
fit = self.check_for_vert_hor_attacks()
fit += self.check_for_diag_attacks()
return fit
# check_for_diag_attacks was inspired by techniqu... | import random
import numpy as np
N = 0
popSize = 0
population = []
# class 'Individual' is inspired by Dr. Nisha's genetic_algorithm.py class example
class Individual(object):
| 46 | 256 | 942 | 4 | 41 | dereksotoasty/N-Queens | N-Queens.py | Python | Individual | Individual | 9 | 124 | 9 | 9 | 63f1ecf476f0c44b247219e916697f13d2946200 | bigcode/the-stack | train |
5f5dec210af61edb1304ecc3 | train | function | def check_for_solution():
if population[0].fitness == 0:
return True
else:
return False
| def check_for_solution():
| if population[0].fitness == 0:
return True
else:
return False
| = list(range(N))
board = [[0 for x in range(N)] for x in range(N)]
for x in board:
x = random.choice(columns)
columns.remove(x)
board[random.choice(range(N))][x] = 1
return board
def check_for_solution():
| 64 | 64 | 27 | 5 | 58 | dereksotoasty/N-Queens | N-Queens.py | Python | check_for_solution | check_for_solution | 127 | 131 | 127 | 127 | c7b578863828b4ce6d436d5678db3b7ceb1bdede | bigcode/the-stack | train |
54c4dfb2e3c344ab9d41b707 | train | function | def na_arithmetic_op(left, right, op, str_rep: str):
"""
Return the result of evaluating op on the passed in values.
If native types are not compatible, try coersion to object dtype.
Parameters
----------
left : np.ndarray
right : np.ndarray or scalar
str_rep : str or None
Returns... | def na_arithmetic_op(left, right, op, str_rep: str):
| """
Return the result of evaluating op on the passed in values.
If native types are not compatible, try coersion to object dtype.
Parameters
----------
left : np.ndarray
right : np.ndarray or scalar
str_rep : str or None
Returns
-------
array-like
Raises
------
... | D compat
return result
def define_na_arithmetic_op(op, str_rep: str):
def na_op(x, y):
return na_arithmetic_op(x, y, op, str_rep)
return na_op
def na_arithmetic_op(left, right, op, str_rep: str):
| 64 | 64 | 158 | 16 | 47 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | na_arithmetic_op | na_arithmetic_op | 125 | 152 | 125 | 125 | 7c5589e143695106a01f73a813c73f46a08e25c9 | bigcode/the-stack | train |
c4ffe91d6b38592269f37dcb | train | function | def masked_arith_op(x, y, op):
"""
If the given arithmetic operation fails, attempt it again on
only the non-null elements of the input array(s).
Parameters
----------
x : np.ndarray
y : np.ndarray, Series, Index
op : binary operator
"""
# For Series `x` is 1D so ravel() is a no... | def masked_arith_op(x, y, op):
| """
If the given arithmetic operation fails, attempt it again on
only the non-null elements of the input array(s).
Parameters
----------
x : np.ndarray
y : np.ndarray, Series, Index
op : binary operator
"""
# For Series `x` is 1D so ravel() is a no-op; calling it anyway makes
... | _method_OBJECT_ARRAY(op, x, y):
if isinstance(y, list):
y = construct_1d_object_array_from_listlike(y)
# TODO: Should the checks below be ABCIndexClass?
if isinstance(y, (np.ndarray, ABCSeries, ABCIndex)):
# TODO: should this be ABCIndexClass??
if not is_object_dtype(y.dtype):
... | 149 | 149 | 499 | 11 | 137 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | masked_arith_op | masked_arith_op | 60 | 115 | 60 | 60 | 38cbc2e29006419a141ed2762c78c3503e06555f | bigcode/the-stack | train |
d2ee04e06cc8b1310262ea4f | train | function | def comp_method_OBJECT_ARRAY(op, x, y):
if isinstance(y, list):
y = construct_1d_object_array_from_listlike(y)
# TODO: Should the checks below be ABCIndexClass?
if isinstance(y, (np.ndarray, ABCSeries, ABCIndex)):
# TODO: should this be ABCIndexClass??
if not is_object_dtype(y.dtype... | def comp_method_OBJECT_ARRAY(op, x, y):
| if isinstance(y, list):
y = construct_1d_object_array_from_listlike(y)
# TODO: Should the checks below be ABCIndexClass?
if isinstance(y, (np.ndarray, ABCSeries, ABCIndex)):
# TODO: should this be ABCIndexClass??
if not is_object_dtype(y.dtype):
y = y.astype(np.object_)
... | .dtypes.missing import isna, notna
from pandas.core.ops import missing
from pandas.core.ops.dispatch import dispatch_to_extension_op, should_extension_dispatch
from pandas.core.ops.invalid import invalid_comparison
from pandas.core.ops.roperator import rpow
def comp_method_OBJECT_ARRAY(op, x, y):
| 64 | 64 | 140 | 11 | 52 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | comp_method_OBJECT_ARRAY | comp_method_OBJECT_ARRAY | 41 | 57 | 41 | 41 | 20a3542a8c27235337d8ff1212b4e2108d3bd18b | bigcode/the-stack | train |
4e1799ce26f3286b795d24a0 | train | function | def comparison_op(
left: Union[np.ndarray, ABCExtensionArray], right: Any, op
) -> Union[np.ndarray, ABCExtensionArray]:
"""
Evaluate a comparison operation `=`, `!=`, `>=`, `>`, `<=`, or `<`.
Parameters
----------
left : np.ndarray or ExtensionArray
right : object
Cannot be a DataF... | def comparison_op(
left: Union[np.ndarray, ABCExtensionArray], right: Any, op
) -> Union[np.ndarray, ABCExtensionArray]:
| """
Evaluate a comparison operation `=`, `!=`, `>=`, `>`, `<=`, or `<`.
Parameters
----------
left : np.ndarray or ExtensionArray
right : object
Cannot be a DataFrame, Series, or Index.
op : {operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le}
Returns
... | , rvalues) or isinstance(
rvalues, (ABCTimedeltaArray, ABCDatetimeArray, Timestamp)
):
# TimedeltaArray, DatetimeArray, and Timestamp are included here
# because they have `freq` attribute which is handled correctly
# by dispatch_to_extension_op.
res_values = dispatch_to_ex... | 153 | 153 | 512 | 35 | 117 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | comparison_op | comparison_op | 200 | 260 | 200 | 202 | 2ac15d6eed2a620b057caff684435bcc70a7cff1 | bigcode/the-stack | train |
cdd0defda16c92211e52db96 | train | function | def arithmetic_op(
left: Union[np.ndarray, ABCExtensionArray], right: Any, op, str_rep: str
):
"""
Evaluate an arithmetic operation `+`, `-`, `*`, `/`, `//`, `%`, `**`, ...
Parameters
----------
left : np.ndarray or ExtensionArray
right : object
Cannot be a DataFrame or Index. Seri... | def arithmetic_op(
left: Union[np.ndarray, ABCExtensionArray], right: Any, op, str_rep: str
):
| """
Evaluate an arithmetic operation `+`, `-`, `*`, `/`, `//`, `%`, `**`, ...
Parameters
----------
left : np.ndarray or ExtensionArray
right : object
Cannot be a DataFrame or Index. Series is *not* excluded.
op : {operator.add, operator.sub, ...}
Or one of the reversed var... |
------
TypeError : invalid operation
"""
import pandas.core.computation.expressions as expressions
try:
result = expressions.evaluate(op, str_rep, left, right)
except TypeError:
result = masked_arith_op(left, right, op)
return missing.dispatch_fill_zeros(op, left, right, r... | 103 | 103 | 345 | 29 | 74 | raghavgai/mypandas | pandas/core/ops/array_ops.py | Python | arithmetic_op | arithmetic_op | 155 | 197 | 155 | 157 | c097a74c9758eb3dacbfd5095cc48ff5ff6208a8 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.