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
416231aabc0114ea0b89c700
train
function
def sendUndeployToOtherSystemManagers(node_name, node_names, sysmgr_address, type): """ Handles a message from the rest server to the active system manager to distribute an egg to other system managers. :param node_name: The name of this node :type node_name: str :param node_names: The list of ...
def sendUndeployToOtherSystemManagers(node_name, node_names, sysmgr_address, type):
""" Handles a message from the rest server to the active system manager to distribute an egg to other system managers. :param node_name: The name of this node :type node_name: str :param node_names: The list of nodes in the system, so that the active system manager can send a deploy egg message...
], shell=True) if return_code != 0: logging.error("Unable to install egg %s", type) else: logging.debug("Installed egg %s", type) # delete the temporary egg file os.remove(egg_file_path) return return_code == 0 def sendUndeployToOtherSystemManagers(node_name, node_names, sysmgr_addre...
84
84
282
21
62
Brewgarten/c4-system-manager
c4/system/egg.py
Python
sendUndeployToOtherSystemManagers
sendUndeployToOtherSystemManagers
81
104
81
81
ab6b040285720163ca910388608a6344c7f30671
bigcode/the-stack
train
d32d3a20b2a487af1315a202
train
function
def deployEgg(type, file_name, data): """ Deploys the egg to the system. Assumes system manager is run as root. :param type: Type is the dotted module names for the custom device manager class. e.g. c4.devices.mydm.MyDM :type type: str :param file_name: The file name of the egg e.g. MyCustomDM-0....
def deployEgg(type, file_name, data):
""" Deploys the egg to the system. Assumes system manager is run as root. :param type: Type is the dotted module names for the custom device manager class. e.g. c4.devices.mydm.MyDM :type type: str :param file_name: The file name of the egg e.g. MyCustomDM-0.1-py2.7.egg :type file_name: str ...
_name) # distribute to other system managers, if any for a_node_name in node_names: # but skip ourself if a_node_name != node_name: # send to node logging.debug("Sending deploy device manager request to %s", a_node_name) new_message = DeployDeviceManager("syst...
125
125
419
10
115
Brewgarten/c4-system-manager
c4/system/egg.py
Python
deployEgg
deployEgg
46
79
46
46
e24be350508e05543e37237db405729fc5cbbb47
bigcode/the-stack
train
bd90d3f051e6e788ec41a669
train
function
def undeployEgg(type): """ Undeploys the egg from the system. Assumes system manager is run as root. :param type: Type is the dotted module names for the custom device manager class. e.g. c4.devices.mydm.MyDM :type type: str """ # uninstall egg # assuming we, the system manager, is runnin...
def undeployEgg(type):
""" Undeploys the egg from the system. Assumes system manager is run as root. :param type: Type is the dotted module names for the custom device manager class. e.g. c4.devices.mydm.MyDM :type type: str """ # uninstall egg # assuming we, the system manager, is running as root return_co...
# send to node logging.debug("Sending undeploy device manager request to %s", a_node_name) new_message = UndeployDeviceManager("system-manager", a_node_name) new_message.Message["type"] = type client.forwardMessage(new_message) def undeployEgg(type):
64
64
160
6
58
Brewgarten/c4-system-manager
c4/system/egg.py
Python
undeployEgg
undeployEgg
106
121
106
106
09dd8994c88ecd92a8737799d71b5bd2396f8a35
bigcode/the-stack
train
e4f3c9c876916dd6b290bd8b
train
function
def make_circuit(n:int) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) # number=1 prog.y(input_qubit[2]) # number=9 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.x(input_qubit[...
def make_circuit(n:int) -> QuantumCircuit: # circuit begin
input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) # number=1 prog.y(input_qubit[2]) # number=9 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.x(input_qubit[2]) # number=6 prog.h(input_qubit[3]) # number=4 for ...
networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def make_circuit(n:int) -> QuantumCircuit: # circuit begin
76
76
255
16
60
UCLA-SEAL/QDiff
data/p4VQE/R4/benchmark/startQiskit756.py
Python
make_circuit
make_circuit
18
45
18
19
154da4ce05493b69a8f288e6b762036b5511b08d
bigcode/the-stack
train
09af7b9b1ae2e683e825606a
train
class
class AdminModelConverter(SQLAAdminConverter): @converts("Geography", "Geometry") def convert_geom(self, column, field_args, **extra): field_args["geometry_type"] = column.type.geometry_type field_args["srid"] = column.type.srid field_args["session"] = self.session field_args["ti...
class AdminModelConverter(SQLAAdminConverter): @converts("Geography", "Geometry")
def convert_geom(self, column, field_args, **extra): field_args["geometry_type"] = column.type.geometry_type field_args["srid"] = column.type.srid field_args["session"] = self.session field_args["tile_layer_url"] = self.view.tile_layer_url field_args["tile_layer_attribution"]...
from flask_admin.model.form import converts from flask_admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter from .fields import GeoJSONField class AdminModelConverter(SQLAAdminConverter): @converts("Geography", "Geometry")
54
64
111
20
33
aitoehigie/britecore_flask
venv/lib/python3.6/site-packages/flask_admin/contrib/geoa/form.py
Python
AdminModelConverter
AdminModelConverter
6
14
6
7
4ef7af719a2ee102c46e528450c4aa8385bff2b9
bigcode/the-stack
train
b92aa7cbe881fa3d8da6475e
train
function
def test_check_013(mada_ttFonts): """ Fonts have equal unicode encodings ? """ from fontbakery.specifications.cmap import com_google_fonts_check_013 as check from fontbakery.constants import WindowsEncodingID print('Test PASS with good family.') # our reference Mada family is know to be good here. status, ...
def test_check_013(mada_ttFonts):
""" Fonts have equal unicode encodings ? """ from fontbakery.specifications.cmap import com_google_fonts_check_013 as check from fontbakery.constants import WindowsEncodingID print('Test PASS with good family.') # our reference Mada family is know to be good here. status, message = list(check(mada_ttFonts)...
data/test/mada/Mada-Bold.ttf", "data/test/mada/Mada-Light.ttf", "data/test/mada/Mada-Regular.ttf", ] @pytest.fixture def mada_ttFonts(): return [TTFont(path) for path in mada_fonts] def test_check_013(mada_ttFonts):
64
64
207
10
54
m4rc1e/fontbakery
tests/specifications/cmap_test.py
Python
test_check_013
test_check_013
31
51
31
31
ae18168e3e660c34e258ff2ff21c35b8f0bff1af
bigcode/the-stack
train
e691977b78173be392c46b3d
train
function
@pytest.fixture def mada_ttFonts(): return [TTFont(path) for path in mada_fonts]
@pytest.fixture def mada_ttFonts():
return [TTFont(path) for path in mada_fonts]
/mada/Mada-Medium.ttf", "data/test/mada/Mada-SemiBold.ttf", "data/test/mada/Mada-Bold.ttf", "data/test/mada/Mada-Light.ttf", "data/test/mada/Mada-Regular.ttf", ] @pytest.fixture def mada_ttFonts():
64
64
21
8
56
m4rc1e/fontbakery
tests/specifications/cmap_test.py
Python
mada_ttFonts
mada_ttFonts
26
28
26
27
931c37e934de3f4ffba7d57ec32d291aa7ddc9cd
bigcode/the-stack
train
2c109c6b77398c49f699d06f
train
function
def NOT_IMPLEMENTED_test_check_077(): """ Check all glyphs have codepoints assigned. """
def NOT_IMPLEMENTED_test_check_077():
""" Check all glyphs have codepoints assigned. """
# from fontbakery.specifications.googlefonts import com_google_fonts_check_076 as check # TODO: Implement-me! # # code-paths: # - FAIL, "Some glyphs carry the same unicode value." # - PASS def NOT_IMPLEMENTED_test_check_077():
64
64
21
9
54
m4rc1e/fontbakery
tests/specifications/cmap_test.py
Python
NOT_IMPLEMENTED_test_check_077
NOT_IMPLEMENTED_test_check_077
64
65
64
64
f5dda89995009f38b10900a1b1a62947a0329fbe
bigcode/the-stack
train
0b87ba58067ae11c63f8d84c
train
function
def NOT_IMPLEMENTED_test_check_076(): """ Check glyphs have unique unicode codepoints. """
def NOT_IMPLEMENTED_test_check_076():
""" Check glyphs have unique unicode codepoints. """
'].tables: if table.format == 4: table.platEncID = encoding print('Test FAIL with fonts that diverge on unicode encoding.') status, message = list(check(bad_ttFonts))[-1] assert status == FAIL def NOT_IMPLEMENTED_test_check_076():
64
64
21
9
54
m4rc1e/fontbakery
tests/specifications/cmap_test.py
Python
NOT_IMPLEMENTED_test_check_076
NOT_IMPLEMENTED_test_check_076
54
55
54
54
d1dc2f1c7be865803795596dee11a59a7d6221ae
bigcode/the-stack
train
640f87ae00a55a83a174d365
train
class
class IsolationPlayer: """Base class for minimax and alphabeta agents -- this class is never constructed or tested directly. ******************** DO NOT MODIFY THIS CLASS ******************** Parameters ---------- search_depth : int (optional) A strictly positive integer (i.e., 1, 2,...
class IsolationPlayer:
"""Base class for minimax and alphabeta agents -- this class is never constructed or tested directly. ******************** DO NOT MODIFY THIS CLASS ******************** Parameters ---------- search_depth : int (optional) A strictly positive integer (i.e., 1, 2, 3,...) for the number ...
_loser(player): return float("-inf") if game.is_winner(player): return float("inf") my_moves = len(game.get_legal_moves(player)) opp_moves = len(game.get_legal_moves(game.get_opponent(player))) return float(my_moves**2 + opp_moves**2) class IsolationPlayer:
69
69
233
4
65
escofresco/AIND-Isolation
game_agent.py
Python
IsolationPlayer
IsolationPlayer
127
153
127
127
aa4032384586063882a0c236c5ca4a3ba9584e0e
bigcode/the-stack
train
6b83ef445f7d1b3ac4eb72d7
train
function
def custom_score_3(game, player): """Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- g...
def custom_score_3(game, player):
"""Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An...
if game.is_winner(player): return float("inf") # Manhattan distance D = 1 # cost my_moves = len(game.get_legal_moves()) opp_moves = len(game.get_legal_moves(game.get_opponent(player))) return float(D * (my_moves+opp_moves)) def custom_score_3(game, player):
75
75
250
9
66
escofresco/AIND-Isolation
game_agent.py
Python
custom_score_3
custom_score_3
92
123
92
92
7b8c16caf6a00d7f0984e56dc0e405ba9e5913c8
bigcode/the-stack
train
f6196d5e473a59ebe09f64a7
train
class
class MinimaxPlayer(IsolationPlayer): """Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires. """ def get_move(self, game, time_left): ...
class MinimaxPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires. """ def get_move(self, game, time_left): """Search for the best move from the ...
(player))) return float(my_moves**2 + opp_moves**2) class IsolationPlayer: """Base class for minimax and alphabeta agents -- this class is never constructed or tested directly. ******************** DO NOT MODIFY THIS CLASS ******************** Parameters ---------- search_depth : int ...
256
256
1,376
8
247
escofresco/AIND-Isolation
game_agent.py
Python
MinimaxPlayer
MinimaxPlayer
156
327
156
156
4feaf9048a4f0b35dcecfa4af267a191276b8a6e
bigcode/the-stack
train
c74ccdf8c93aff001cd2ecc5
train
class
class AlphaBetaPlayer(IsolationPlayer): """Game-playing agent that chooses a move using iterative deepening minimax search with alpha-beta pruning. You must finish and test this player to make sure it returns a good move before the search time limit expires. """ def get_move(self, game, time_left):...
class AlphaBetaPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using iterative deepening minimax search with alpha-beta pruning. You must finish and test this player to make sure it returns a good move before the search time limit expires. """ def get_move(self, game, time_left): """Search for the best move fro...
if depth <= 0: # Return score as is when depth is 0 return self.score(game, self) #depth v = float('-inf') for move in legal_moves: v = max(v, self.min_value(game.forecast_move(move), depth - 1)) return v def min_value(self, game, depth): ...
256
256
1,210
8
247
escofresco/AIND-Isolation
game_agent.py
Python
AlphaBetaPlayer
AlphaBetaPlayer
329
484
329
329
860738a9d30dee0a4cfdf40b20b5f392bfeb6a13
bigcode/the-stack
train
335192e82e1a743bf12e6428
train
function
def custom_score(game, player): """Calculate the heuristic value of a game state from the point of view of the given player. This should be the best heuristic function for your project submission. Note: this function should be called from within a Player instance as `self.score()` -- you should no...
def custom_score(game, player):
"""Calculate the heuristic value of a game state from the point of view of the given player. This should be the best heuristic function for your project submission. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function dir...
"""Finish all TODO items in this file to complete the isolation project, then test your agent's strength against a set of known agents using tournament.py and include the results in your report. """ import random from math import sqrt class SearchTimeout(Exception): """Subclass base exception for code clarity. """...
73
118
394
7
65
escofresco/AIND-Isolation
game_agent.py
Python
custom_score
custom_score
13
54
13
13
c5fb0390b23aa0b034ac4f9e6155784f5dcd96f7
bigcode/the-stack
train
4111dcdffeb622db95363ed5
train
class
class SearchTimeout(Exception): """Subclass base exception for code clarity. """ pass
class SearchTimeout(Exception):
"""Subclass base exception for code clarity. """ pass
"""Finish all TODO items in this file to complete the isolation project, then test your agent's strength against a set of known agents using tournament.py and include the results in your report. """ import random from math import sqrt class SearchTimeout(Exception):
53
64
18
5
47
escofresco/AIND-Isolation
game_agent.py
Python
SearchTimeout
SearchTimeout
8
10
8
8
e63ef35334cf87c73b9aaa0749c0c920eb49caae
bigcode/the-stack
train
60826f1c7b1137ad174b134f
train
function
def custom_score_2(game, player): """Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- g...
def custom_score_2(game, player):
"""Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An...
len(game.get_legal_moves(game.get_opponent(player))) # return float(D * (my_moves+opp_moves) + (D2 - (2*D)) * min(my_moves, opp_moves)) return float(D * (dx + dy) + (D2 - 2*D) * min(dx, dy)) def custom_score_2(game, player):
78
78
261
9
69
escofresco/AIND-Isolation
game_agent.py
Python
custom_score_2
custom_score_2
57
90
57
57
7bc7c5fd35c7eec51b1d1b8321345e39b271e67d
bigcode/the-stack
train
f2922afb4a2e129903e2666b
train
class
class MyDataset(Dataset): def __init__(self, file_path, dataset_split, view_size=2,): super(MyDataset, self).__init__() self.file_path = file_path self.view_size = view_size self.dataset_split = dataset_split def __len__(self): return len(self.dataset_split) def __g...
class MyDataset(Dataset):
def __init__(self, file_path, dataset_split, view_size=2,): super(MyDataset, self).__init__() self.file_path = file_path self.view_size = view_size self.dataset_split = dataset_split def __len__(self): return len(self.dataset_split) def __getitem__(self, item): ...
import numpy as np import scipy.sparse as sp import torch import json import urllib.request from torch.utils.data import Dataset # # def to_sparse(x): # """ converts dense tensor x to sparse format """ # x_typename = torch.typename(x).split('.')[-1] # sparse_tensortype = getattr(torch.sparse, x_typename) ...
169
249
833
6
163
cheunglei/AAAI-20-Co-GCN
Co-GCN/utils.py
Python
MyDataset
MyDataset
23
112
23
23
8dbf61d31576ce88836ca6f736253e7841ae007f
bigcode/the-stack
train
f7fd3e1395676230a67ab1a6
train
class
class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '--language', help='Only build docs for this specific language', ) parser.add_argument( '--force', action='store_true', default=False, hel...
class Command(BaseCommand):
def add_arguments(self, parser): parser.add_argument( '--language', help='Only build docs for this specific language', ) parser.add_argument( '--force', action='store_true', default=False, help="Force docs update even if...
""" Update and build the documentation into files for display with the djangodocs app. """ import json import os import shutil import subprocess import sys import zipfile from contextlib import closing from datetime import datetime from pathlib import Path from django.conf import settings from django.core.management i...
92
256
2,091
5
86
Venus9023/django_for_beginer
docs/management/commands/update_docs.py
Python
Command
Command
22
255
22
22
3b67a659093f56432878d75204a57bc3d5f67fe3
bigcode/the-stack
train
0e8232126f1d7397a1ee7195
train
function
def gen_decoded_documents(directory): """ Walk the given directory looking for fjson files and yield their data. """ for root, dirs, files in os.walk(str(directory)): for f in files: f = Path(root, f) if not f.suffix == '.fjson': continue with...
def gen_decoded_documents(directory):
""" Walk the given directory looking for fjson files and yield their data. """ for root, dirs, files in os.walk(str(directory)): for f in files: f = Path(root, f) if not f.suffix == '.fjson': continue with f.open() as fp: yield...
', 'merge', branch_with_remote, quiet], stderr=sys.stdout) finally: os.chdir(cwd) else: subprocess.check_call(['git', 'clone', '--branch', branch, repo, str(destdir), quiet], stderr=sys.stdout) return True def gen_decoded_documents(directory):
64
64
81
7
56
Venus9023/django_for_beginer
docs/management/commands/update_docs.py
Python
gen_decoded_documents
gen_decoded_documents
258
269
258
258
c2a393d897a5cf449afe5d26abdd5f7d0ff0cba1
bigcode/the-stack
train
ec5a7b86b033dd34feec1b25
train
function
def load_json_file(filepath): with open(filepath, "r") as f: mod_set = json.loads(f.read()) print("File read successfully") return mod_set
def load_json_file(filepath):
with open(filepath, "r") as f: mod_set = json.loads(f.read()) print("File read successfully") return mod_set
import os import json # Loads and returns a dictionary, created by a JSON file # filepath is the path to the JSON file def load_json_file(filepath):
35
64
38
6
28
DanPerry1808/ModuleTracker
file_io.py
Python
load_json_file
load_json_file
6
10
6
6
869fc37d7fac4559e169816033b5b2370267e087
bigcode/the-stack
train
209510e1af057a73c5a18657
train
function
def list_saves(): print() print("List of all module sets") print("----------") for file in os.listdir("saves/"): if file.endswith(".json"): print(file[:-5])
def list_saves():
print() print("List of all module sets") print("----------") for file in os.listdir("saves/"): if file.endswith(".json"): print(file[:-5])
also be used to update a JSON file by overwriting it def write_json_file(filepath, mod_set): with open(filepath, "w") as f: f.write(json.dumps(mod_set)) print("File created successfully") # Lists all the JSON files in the saves directory def list_saves():
64
64
46
5
58
DanPerry1808/ModuleTracker
file_io.py
Python
list_saves
list_saves
20
26
20
20
c31074802ef0b75ea6c6ed7932f9c38b8f1a3e82
bigcode/the-stack
train
7cf885615d9e67a101f71c17
train
function
def write_json_file(filepath, mod_set): with open(filepath, "w") as f: f.write(json.dumps(mod_set)) print("File created successfully")
def write_json_file(filepath, mod_set):
with open(filepath, "w") as f: f.write(json.dumps(mod_set)) print("File created successfully")
r") as f: mod_set = json.loads(f.read()) print("File read successfully") return mod_set # Creates a JSON file from the dictionary provided at the given filepath # Can also be used to update a JSON file by overwriting it def write_json_file(filepath, mod_set):
64
64
35
9
54
DanPerry1808/ModuleTracker
file_io.py
Python
write_json_file
write_json_file
14
17
14
14
2c62f68265e49e27fb56080d6de9f129fd5c00e9
bigcode/the-stack
train
01001051e66935ce513f4526
train
function
def get_filepath(name): return os.path.join("saves/", name + ".json")
def get_filepath(name):
return os.path.join("saves/", name + ".json")
def list_saves(): print() print("List of all module sets") print("----------") for file in os.listdir("saves/"): if file.endswith(".json"): print(file[:-5]) # Generates the filepath to the json file with this name def get_filepath(name):
64
64
19
5
58
DanPerry1808/ModuleTracker
file_io.py
Python
get_filepath
get_filepath
29
30
29
29
762d0f4f62f8e4e03c1850fe0dfc6f41d534aab1
bigcode/the-stack
train
9e08a865038e2151e0566e4c
train
class
class NUEnterpriseProfile(NURESTObject): """ Represents a EnterpriseProfile in the VSD Notes: Enterprise profile, used to store an enterprise's policies, quota etc. """ __rest_name__ = "enterpriseprofile" __resource_name__ = "enterpriseprofiles" ## Constants CONS...
class NUEnterpriseProfile(NURESTObject):
""" Represents a EnterpriseProfile in the VSD Notes: Enterprise profile, used to store an enterprise's policies, quota etc. """ __rest_name__ = "enterpriseprofile" __resource_name__ = "enterpriseprofiles" ## Constants CONST_ENCRYPTION_MANAGEMENT_MODE_MANAGED = "M...
from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED...
256
256
3,253
9
246
cldelcourt/vspk-python
vspk/v4_0/nuenterpriseprofile.py
Python
NUEnterpriseProfile
NUEnterpriseProfile
50
560
50
50
1f90943ff2888c35400af415b04656959ecaa8f3
bigcode/the-stack
train
1535bef1d30bc48a3c533254
train
class
class poloniex(Exchange): def describe(self): return self.deep_extend(super(poloniex, self).describe(), { 'id': 'poloniex', 'name': 'Poloniex', 'countries': ['US'], 'rateLimit': 1000, # up to 6 calls per second 'certified': True, # 2019-06-07 ...
class poloniex(Exchange):
def describe(self): return self.deep_extend(super(poloniex, self).describe(), { 'id': 'poloniex', 'name': 'Poloniex', 'countries': ['US'], 'rateLimit': 1000, # up to 6 calls per second 'certified': True, # 2019-06-07 'has': { ...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import hashlib import math from ccxt.base.errors import ExchangeError from ccxt.base.errors import ...
198
256
10,911
7
190
Krestol/ccxt
python/ccxt/poloniex.py
Python
poloniex
poloniex
24
1,243
24
25
4f1ee3e5210fbb9692ad11b7e2c71280b9abb4ff
bigcode/the-stack
train
6f7b529664a0eb48ed44be49
train
function
def test_iter_bytes(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = b"" for part in response.iter_bytes(): content += part assert content == b"Hello, world!"
def test_iter_bytes():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = b"" for part in response.iter_bytes(): content += part assert content == b"Hello, world!"
aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) raw = b"" async for part in response.aiter_raw(): raw += part assert raw == b"Hello, world!" def test_iter_bytes():
63
64
54
5
58
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_iter_bytes
test_iter_bytes
178
184
178
178
85b6178c1e8c740516e44b3b30b1ddcb7bd06e48
bigcode/the-stack
train
d0876a5aeece07c3b371aca4
train
function
def test_read(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert response.status_code == 200 assert response.text == "Hello, world!" assert response.encoding == "ascii" assert response.is_closed content = response.read() assert content == b"Hello, world!" ...
def test_read():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert response.status_code == 200 assert response.text == "Hello, world!" assert response.encoding == "ascii" assert response.is_closed content = response.read() assert content == b"Hello, world!" assert respon...
) response.encoding = "iso-8859-1" assert response.status_code == 200 assert response.reason_phrase == "OK" assert response.text == "Snowman: â\x98\x83" assert response.encoding == "iso-8859-1" def test_read():
64
64
90
4
60
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_read
test_read
126
138
126
126
f2ad1213279998e4ebc216239c9249280311244d
bigcode/the-stack
train
a7d3611264443db0235d72e7
train
function
def test_response(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert response.status_code == 200 assert response.reason_phrase == "OK" assert response.text == "Hello, world!" assert response.request is REQUEST assert response.elapsed >= datetime.timedelta(0) ...
def test_response():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert response.status_code == 200 assert response.reason_phrase == "OK" assert response.text == "Hello, world!" assert response.request is REQUEST assert response.elapsed >= datetime.timedelta(0) assert not response....
AsyncIteratorStream, IteratorStream REQUEST = httpx.Request("GET", "https://example.org") def streaming_body(): yield b"Hello, " yield b"world!" async def async_streaming_body(): yield b"Hello, " yield b"world!" def test_response():
63
64
76
4
59
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response
test_response
23
31
23
23
bd0ce3de2bfc616d98ed9604c3132a766b062db5
bigcode/the-stack
train
13be110c494048392317a5af
train
function
def test_response_force_encoding(): response = httpx.Response( 200, content="Snowman: ☃".encode("utf-8"), request=REQUEST ) response.encoding = "iso-8859-1" assert response.status_code == 200 assert response.reason_phrase == "OK" assert response.text == "Snowman: â\x98\x83" assert re...
def test_response_force_encoding():
response = httpx.Response( 200, content="Snowman: ☃".encode("utf-8"), request=REQUEST ) response.encoding = "iso-8859-1" assert response.status_code == 200 assert response.reason_phrase == "OK" assert response.text == "Snowman: â\x98\x83" assert response.encoding == "iso-8859-1"
200, content="Latin 1: ÿ".encode("latin-1"), headers=headers, request=REQUEST, ) response.encoding = "latin-1" assert response.text == "Latin 1: ÿ" assert response.encoding == "latin-1" def test_response_force_encoding():
64
64
95
6
58
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_force_encoding
test_response_force_encoding
115
123
115
115
0d9fe21733a14b8430d71538941e4fa96561b62b
bigcode/the-stack
train
3466c5733ff31386aaae8657
train
function
def test_iter_raw(): stream = IteratorStream(iterator=streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) raw = b"" for part in response.iter_raw(): raw += part assert raw == b"Hello, world!"
def test_iter_raw():
stream = IteratorStream(iterator=streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) raw = b"" for part in response.iter_raw(): raw += part assert raw == b"Hello, world!"
assert response.text == "Hello, world!" assert response.encoding == "ascii" assert response.is_closed content = await response.aread() assert content == b"Hello, world!" assert response.content == b"Hello, world!" assert response.is_closed def test_iter_raw():
64
64
62
5
58
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_iter_raw
test_iter_raw
157
164
157
157
8e4a19f4481642f6e627df3ca0fc376cae0ec7e8
bigcode/the-stack
train
43d656cb183ff05178b62cdd
train
function
@pytest.mark.asyncio async def test_async_streaming_response(): stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) assert response.status_code == 200 assert not response.is_closed content = await response.aread() asser...
@pytest.mark.asyncio async def test_async_streaming_response():
stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) assert response.status_code == 200 assert not response.is_closed content = await response.aread() assert content == b"Hello, world!" assert response.content == b"H...
REQUEST) assert response.status_code == 200 assert not response.is_closed content = response.read() assert content == b"Hello, world!" assert response.content == b"Hello, world!" assert response.is_closed @pytest.mark.asyncio async def test_async_streaming_response():
64
64
97
13
50
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_async_streaming_response
test_async_streaming_response
249
261
249
250
540e0fe4892dbddb28221a52060489a160f0d36a
bigcode/the-stack
train
62baafb54d3402f647cf2ea5
train
function
def test_response_non_text_encoding(): """ Default to apparent encoding for non-text content-type headers. """ headers = {"Content-Type": "image/png"} response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST) assert response.text == "xyz" assert response.encoding == "a...
def test_response_non_text_encoding():
""" Default to apparent encoding for non-text content-type headers. """ headers = {"Content-Type": "image/png"} response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST) assert response.text == "xyz" assert response.encoding == "ascii"
, world!" def test_response_default_encoding(): """ Default to utf-8 if all else fails. """ response = httpx.Response(200, content=b"", request=REQUEST) assert response.text == "" assert response.encoding == "utf-8" def test_response_non_text_encoding():
64
64
71
7
57
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_non_text_encoding
test_response_non_text_encoding
93
100
93
93
f6775d18505130d739ad3306f778b4da272c8949
bigcode/the-stack
train
2631b7b95e16f9ff6e3171a8
train
function
def test_iter_lines(): response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST) content = [] for line in response.iter_lines(): content.append(line) assert content == ["Hello,\n", "world!"]
def test_iter_lines():
response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST) content = [] for line in response.iter_lines(): content.append(line) assert content == ["Hello,\n", "world!"]
async def test_aiter_text(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = "" async for part in response.aiter_text(): content += part assert content == "Hello, world!" def test_iter_lines():
63
64
56
5
58
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_iter_lines
test_iter_lines
216
222
216
216
575d386dece1007bb0379dab9349d13df1b6568b
bigcode/the-stack
train
2c47a0f090aaa5c8b20e22c3
train
function
def test_response_fallback_to_autodetect(): """ Fallback to autodetection if we get an invalid charset in the Content-Type header. """ headers = {"Content-Type": "text-plain; charset=invalid-codec-name"} content = "おはようございます。".encode("EUC-JP") response = httpx.Response(200, content=content, head...
def test_response_fallback_to_autodetect():
""" Fallback to autodetection if we get an invalid charset in the Content-Type header. """ headers = {"Content-Type": "text-plain; charset=invalid-codec-name"} content = "おはようございます。".encode("EUC-JP") response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert res...
"おはようございます。".encode("EUC-JP") response = httpx.Response(200, content=content, request=REQUEST) assert response.text == "おはようございます。" assert response.encoding == "EUC-JP" def test_response_fallback_to_autodetect():
64
64
111
10
54
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_fallback_to_autodetect
test_response_fallback_to_autodetect
60
68
60
60
85e9acf992c0448c678787f533c52a74f2a061ab
bigcode/the-stack
train
657a6383cc882ce22f7dbf5d
train
function
def test_response_autodetect_encoding(): """ Autodetect encoding if there is no charset info in a Content-Type header. """ content = "おはようございます。".encode("EUC-JP") response = httpx.Response(200, content=content, request=REQUEST) assert response.text == "おはようございます。" assert response.encoding ==...
def test_response_autodetect_encoding():
""" Autodetect encoding if there is no charset info in a Content-Type header. """ content = "おはようございます。".encode("EUC-JP") response = httpx.Response(200, content=content, request=REQUEST) assert response.text == "おはようございます。" assert response.encoding == "EUC-JP"
Latin 1: ÿ".encode("latin-1") response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.text == "Latin 1: ÿ" assert response.encoding == "latin-1" def test_response_autodetect_encoding():
64
64
86
8
56
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_autodetect_encoding
test_response_autodetect_encoding
50
57
50
50
ab661a934c29a3ce54c74a91c77ac4a42ef58506
bigcode/the-stack
train
3edeefbd0d111a9863f6d130
train
function
@pytest.mark.asyncio async def test_aiter_bytes(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = b"" async for part in response.aiter_bytes(): content += part assert content == b"Hello, world!"
@pytest.mark.asyncio async def test_aiter_bytes():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = b"" async for part in response.aiter_bytes(): content += part assert content == b"Hello, world!"
(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = b"" for part in response.iter_bytes(): content += part assert content == b"Hello, world!" @pytest.mark.asyncio async def test_aiter_bytes():
63
64
65
13
50
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_aiter_bytes
test_aiter_bytes
187
194
187
188
894ff9b4611046903938f2678068619014c36619
bigcode/the-stack
train
9cddb3df4387a9664cbba235
train
function
@pytest.mark.asyncio async def test_cannot_aread_after_response_closed(): is_closed = False async def close_func(): nonlocal is_closed is_closed = True stream = AsyncIteratorStream( aiterator=async_streaming_body(), close_func=close_func ) response = httpx.Response(200, str...
@pytest.mark.asyncio async def test_cannot_aread_after_response_closed():
is_closed = False async def close_func(): nonlocal is_closed is_closed = True stream = AsyncIteratorStream( aiterator=async_streaming_body(), close_func=close_func ) response = httpx.Response(200, stream=stream, request=REQUEST) await response.aclose() assert is_cl...
ing_body(), close_func=close_func) response = httpx.Response(200, stream=stream, request=REQUEST) response.close() assert is_closed with pytest.raises(httpx.ResponseClosed): response.read() @pytest.mark.asyncio async def test_cannot_aread_after_response_closed():
64
64
107
16
48
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_cannot_aread_after_response_closed
test_cannot_aread_after_response_closed
306
323
306
307
9a4b3f3008cc6aacff596d745b63c66f84853347
bigcode/the-stack
train
bf3562515e0722c77f129826
train
function
@pytest.mark.asyncio async def test_aiter_text(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = "" async for part in response.aiter_text(): content += part assert content == "Hello, world!"
@pytest.mark.asyncio async def test_aiter_text():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = "" async for part in response.aiter_text(): content += part assert content == "Hello, world!"
test_iter_text(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = "" for part in response.iter_text(): content += part assert content == "Hello, world!" @pytest.mark.asyncio async def test_aiter_text():
63
64
62
13
50
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_aiter_text
test_aiter_text
206
213
206
207
05cd407b31a0b271cbcf9235b96532907b0d2c54
bigcode/the-stack
train
47d8508037ac0939a1dd5f24
train
function
def test_json_with_specified_encoding(): data = {"greeting": "hello", "recipient": "world"} content = json.dumps(data).encode("utf-16") headers = {"Content-Type": "application/json, charset=utf-16"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.jso...
def test_json_with_specified_encoding():
data = {"greeting": "hello", "recipient": "world"} content = json.dumps(data).encode("utf-16") headers = {"Content-Type": "application/json, charset=utf-16"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.json() == data
=REQUEST) with pytest.raises(RuntimeError): response.elapsed def test_unknown_status_code(): response = httpx.Response(600, request=REQUEST) assert response.status_code == 600 assert response.reason_phrase == "" assert response.text == "" def test_json_with_specified_encoding():
63
64
81
8
55
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_json_with_specified_encoding
test_json_with_specified_encoding
342
347
342
342
28e625594d013c4ba10ddd3b36fa065b957d528b
bigcode/the-stack
train
e525bf8ef08bc7d4cdd3e371
train
function
def test_response_default_encoding(): """ Default to utf-8 if all else fails. """ response = httpx.Response(200, content=b"", request=REQUEST) assert response.text == "" assert response.encoding == "utf-8"
def test_response_default_encoding():
""" Default to utf-8 if all else fails. """ response = httpx.Response(200, content=b"", request=REQUEST) assert response.text == "" assert response.encoding == "utf-8"
": "text/plain"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.status_code == 200 assert response.encoding == "iso-8859-1" assert response.text == "Hello, world!" def test_response_default_encoding():
63
64
53
6
57
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_default_encoding
test_response_default_encoding
84
90
84
84
16e213ec838a6548a0a0fcd256aa40f513ba2cb1
bigcode/the-stack
train
e1672e757995d2c6ceab2383
train
function
@pytest.mark.asyncio async def test_elapsed_not_available_until_closed(): stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) with pytest.raises(RuntimeError): response.elapsed
@pytest.mark.asyncio async def test_elapsed_not_available_until_closed():
stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) with pytest.raises(RuntimeError): response.elapsed
_func=close_func ) response = httpx.Response(200, stream=stream, request=REQUEST) await response.aclose() assert is_closed with pytest.raises(httpx.ResponseClosed): await response.aread() @pytest.mark.asyncio async def test_elapsed_not_available_until_closed():
64
64
58
14
50
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_elapsed_not_available_until_closed
test_elapsed_not_available_until_closed
326
332
326
327
7da79d5fb8e790e5bd8028623d0425c8b4653ad7
bigcode/the-stack
train
e4309880d694ffc4f1606ad8
train
function
@pytest.mark.parametrize( "headers, expected", [ ( {"Link": "<https://example.com>; rel='preload'"}, {"preload": {"rel": "preload", "url": "https://example.com"}}, ), ( {"Link": '</hub>; rel="hub", </resource>; rel="self"'}, { ...
@pytest.mark.parametrize( "headers, expected", [ ( {"Link": "<https://example.com>; rel='preload'"}, {"preload": {"rel": "preload", "url": "https://example.com"}}, ), ( {"Link": '</hub>; rel="hub", </resource>; rel="self"'}, { ...
response = httpx.Response(200, content=None, headers=headers, request=REQUEST) assert response.links == expected
@pytest.mark.parametrize( "headers, expected", [ ( {"Link": "<https://example.com>; rel='preload'"}, {"preload": {"rel": "preload", "url": "https://example.com"}}, ), ( {"Link": '</hub>; rel="hub", </resource>; rel="self"'}, { ...
123
64
149
123
0
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_link_headers
test_link_headers
379
397
379
395
9c9a657f392cbd36de2c2dd361c4a03342584c72
bigcode/the-stack
train
997407b4c91ce61078d572dc
train
function
def test_response_repr(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert repr(response) == "<Response [200 OK]>"
def test_response_repr():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert repr(response) == "<Response [200 OK]>"
, world!", request=REQUEST) assert response.status_code == 200 assert response.reason_phrase == "OK" assert response.text == "Hello, world!" assert response.request is REQUEST assert response.elapsed >= datetime.timedelta(0) assert not response.is_error def test_response_repr():
64
64
38
5
58
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_repr
test_response_repr
34
36
34
34
6d6d3b1e1897f52c43947a6470cce229bb683cbe
bigcode/the-stack
train
c1b753e7c915804d73b9fce2
train
function
def test_json_without_specified_encoding(): data = {"greeting": "hello", "recipient": "world"} content = json.dumps(data).encode("utf-32-be") headers = {"Content-Type": "application/json"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.json() == dat...
def test_json_without_specified_encoding():
data = {"greeting": "hello", "recipient": "world"} content = json.dumps(data).encode("utf-32-be") headers = {"Content-Type": "application/json"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.json() == data
encode("utf-16") headers = {"Content-Type": "application/json, charset=utf-16"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.json(parse_int=str)["amount"] == "1" def test_json_without_specified_encoding():
64
64
77
8
56
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_json_without_specified_encoding
test_json_without_specified_encoding
358
363
358
358
b89ee1370ecd50041d7cf2ecf35d66004a4937d9
bigcode/the-stack
train
00bc4a81be77786ef141eb10
train
function
def streaming_body(): yield b"Hello, " yield b"world!"
def streaming_body():
yield b"Hello, " yield b"world!"
import datetime import json from unittest import mock import pytest import httpx from httpx._content_streams import AsyncIteratorStream, IteratorStream REQUEST = httpx.Request("GET", "https://example.org") def streaming_body():
51
64
17
4
47
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
streaming_body
streaming_body
13
15
13
13
40654da1b6094429af20fb439ffbcd67608fc938
bigcode/the-stack
train
8a4f9c9e01e3ea637c138333
train
function
@pytest.mark.asyncio async def test_aiter_raw(): stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) raw = b"" async for part in response.aiter_raw(): raw += part assert raw == b"Hello, world!"
@pytest.mark.asyncio async def test_aiter_raw():
stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) raw = b"" async for part in response.aiter_raw(): raw += part assert raw == b"Hello, world!"
streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) raw = b"" for part in response.iter_raw(): raw += part assert raw == b"Hello, world!" @pytest.mark.asyncio async def test_aiter_raw():
63
64
78
13
50
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_aiter_raw
test_aiter_raw
167
175
167
168
6a3c9beeb1f10723fd44a9d58ab6519e04c52a70
bigcode/the-stack
train
3f188047cbbdd6cb3c3fff45
train
function
def test_json_without_specified_encoding_decode_error(): data = {"greeting": "hello", "recipient": "world"} content = json.dumps(data).encode("utf-32-be") headers = {"Content-Type": "application/json"} # force incorrect guess from `guess_json_utf` to trigger error with mock.patch("httpx._models.gues...
def test_json_without_specified_encoding_decode_error():
data = {"greeting": "hello", "recipient": "world"} content = json.dumps(data).encode("utf-32-be") headers = {"Content-Type": "application/json"} # force incorrect guess from `guess_json_utf` to trigger error with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"): response = h...
"} content = json.dumps(data).encode("utf-32-be") headers = {"Content-Type": "application/json"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.json() == data def test_json_without_specified_encoding_decode_error():
64
64
124
10
53
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_json_without_specified_encoding_decode_error
test_json_without_specified_encoding_decode_error
366
376
366
366
ee86c4bd3ab6bbfc38c43aca96dd777a22e6451d
bigcode/the-stack
train
9eb44d3859b18faf0d92b84a
train
function
def test_response_default_text_encoding(): """ A media type of 'text/*' with no charset should default to ISO-8859-1. See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 """ content = b"Hello, world!" headers = {"Content-Type": "text/plain"} response = httpx.Response(200, co...
def test_response_default_text_encoding():
""" A media type of 'text/*' with no charset should default to ISO-8859-1. See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 """ content = b"Hello, world!" headers = {"Content-Type": "text/plain"} response = httpx.Response(200, content=content, headers=headers, request=REQ...
"おはようございます。".encode("EUC-JP") response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.text == "おはようございます。" assert response.encoding == "EUC-JP" def test_response_default_text_encoding():
64
64
135
7
57
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_default_text_encoding
test_response_default_text_encoding
71
81
71
71
6ba274d2874d3144c631dc0cc4f99735a8310c32
bigcode/the-stack
train
f02e06395309da36a11ae5f9
train
function
def test_response_set_explicit_encoding(): headers = { "Content-Type": "text-plain; charset=utf-8" } # Deliberately incorrect charset response = httpx.Response( 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers, request=REQUEST, ) response.encoding = "latin-1" assert ...
def test_response_set_explicit_encoding():
headers = { "Content-Type": "text-plain; charset=utf-8" } # Deliberately incorrect charset response = httpx.Response( 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers, request=REQUEST, ) response.encoding = "latin-1" assert response.text == "Latin 1: ÿ" assert re...
non-text content-type headers. """ headers = {"Content-Type": "image/png"} response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST) assert response.text == "xyz" assert response.encoding == "ascii" def test_response_set_explicit_encoding():
64
64
104
8
56
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_set_explicit_encoding
test_response_set_explicit_encoding
103
112
103
103
5164e87c62d2033b95e77c2d385c9dde5b0f5714
bigcode/the-stack
train
f08aecca81f6876cf493ce49
train
function
@pytest.mark.asyncio async def test_aread(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert response.status_code == 200 assert response.text == "Hello, world!" assert response.encoding == "ascii" assert response.is_closed content = await response.aread() ...
@pytest.mark.asyncio async def test_aread():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert response.status_code == 200 assert response.text == "Hello, world!" assert response.encoding == "ascii" assert response.is_closed content = await response.aread() assert content == b"Hello, world!" assert...
== "Hello, world!" assert response.encoding == "ascii" assert response.is_closed content = response.read() assert content == b"Hello, world!" assert response.content == b"Hello, world!" assert response.is_closed @pytest.mark.asyncio async def test_aread():
64
64
99
11
52
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_aread
test_aread
141
154
141
142
386c96238f5d1d2b316bb8bdbdd395ec26ef8745
bigcode/the-stack
train
e853ea5f1e651e3d32322ded
train
function
def test_unknown_status_code(): response = httpx.Response(600, request=REQUEST) assert response.status_code == 600 assert response.reason_phrase == "" assert response.text == ""
def test_unknown_status_code():
response = httpx.Response(600, request=REQUEST) assert response.status_code == 600 assert response.reason_phrase == "" assert response.text == ""
@pytest.mark.asyncio async def test_elapsed_not_available_until_closed(): stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) with pytest.raises(RuntimeError): response.elapsed def test_unknown_status_code():
64
64
41
6
57
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_unknown_status_code
test_unknown_status_code
335
339
335
335
5997bfbed6ac89828c83a400c58da1965ee1145e
bigcode/the-stack
train
9af3f477fb744f3691488193
train
function
@pytest.mark.asyncio async def test_cannot_aread_after_stream_consumed(): stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) content = b"" async for part in response.aiter_bytes(): content += part with pytest.raises...
@pytest.mark.asyncio async def test_cannot_aread_after_stream_consumed():
stream = AsyncIteratorStream(aiterator=async_streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) content = b"" async for part in response.aiter_bytes(): content += part with pytest.raises(httpx.StreamConsumed): await response.aread()
= httpx.Response(200, stream=stream, request=REQUEST) content = b"" for part in response.iter_bytes(): content += part with pytest.raises(httpx.StreamConsumed): response.read() @pytest.mark.asyncio async def test_cannot_aread_after_stream_consumed():
64
64
87
17
47
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_cannot_aread_after_stream_consumed
test_cannot_aread_after_stream_consumed
276
286
276
277
26251f38e1db7ea88b09923081f62e58c7c1c5f2
bigcode/the-stack
train
978ea9797087118cb426c287
train
function
async def async_streaming_body(): yield b"Hello, " yield b"world!"
async def async_streaming_body():
yield b"Hello, " yield b"world!"
import mock import pytest import httpx from httpx._content_streams import AsyncIteratorStream, IteratorStream REQUEST = httpx.Request("GET", "https://example.org") def streaming_body(): yield b"Hello, " yield b"world!" async def async_streaming_body():
63
64
20
7
56
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
async_streaming_body
async_streaming_body
18
20
18
18
2a460b8dc086baef7910d32e52bb92aa6d1bbc54
bigcode/the-stack
train
5a07f135cb668bb6b8b6d6fc
train
function
def test_iter_text(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = "" for part in response.iter_text(): content += part assert content == "Hello, world!"
def test_iter_text():
response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = "" for part in response.iter_text(): content += part assert content == "Hello, world!"
test_aiter_bytes(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) content = b"" async for part in response.aiter_bytes(): content += part assert content == b"Hello, world!" def test_iter_text():
63
64
51
5
58
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_iter_text
test_iter_text
197
203
197
197
b9b7a3cb4b042943400d416dea5253c5a4237096
bigcode/the-stack
train
1aeebc4a7f8737f1c86fa730
train
function
def test_sync_streaming_response(): stream = IteratorStream(iterator=streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) assert response.status_code == 200 assert not response.is_closed content = response.read() assert content == b"Hello, world!" assert respon...
def test_sync_streaming_response():
stream = IteratorStream(iterator=streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) assert response.status_code == 200 assert not response.is_closed content = response.read() assert content == b"Hello, world!" assert response.content == b"Hello, world!" a...
_lines(): response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST) content = [] async for line in response.aiter_lines(): content.append(line) assert content == ["Hello,\n", "world!"] def test_sync_streaming_response():
63
64
84
7
56
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_sync_streaming_response
test_sync_streaming_response
235
246
235
235
8bd07410960eff4651a0688d8810aa29a1aaee74
bigcode/the-stack
train
c21929c9fc4e4f5b92fd14d8
train
function
def test_json_with_options(): data = {"greeting": "hello", "recipient": "world", "amount": 1} content = json.dumps(data).encode("utf-16") headers = {"Content-Type": "application/json, charset=utf-16"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.j...
def test_json_with_options():
data = {"greeting": "hello", "recipient": "world", "amount": 1} content = json.dumps(data).encode("utf-16") headers = {"Content-Type": "application/json, charset=utf-16"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.json(parse_int=str)["amount"] =...
"} content = json.dumps(data).encode("utf-16") headers = {"Content-Type": "application/json, charset=utf-16"} response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.json() == data def test_json_with_options():
64
64
91
6
57
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_json_with_options
test_json_with_options
350
355
350
350
3a5e24968fed2baba488d107828889140d677dc7
bigcode/the-stack
train
ca03e5a400e3416b1475633b
train
function
def test_cannot_read_after_response_closed(): is_closed = False def close_func(): nonlocal is_closed is_closed = True stream = IteratorStream(iterator=streaming_body(), close_func=close_func) response = httpx.Response(200, stream=stream, request=REQUEST) response.close() asser...
def test_cannot_read_after_response_closed():
is_closed = False def close_func(): nonlocal is_closed is_closed = True stream = IteratorStream(iterator=streaming_body(), close_func=close_func) response = httpx.Response(200, stream=stream, request=REQUEST) response.close() assert is_closed with pytest.raises(httpx.Resp...
()) response = httpx.Response(200, stream=stream, request=REQUEST) content = b"" async for part in response.aiter_bytes(): content += part with pytest.raises(httpx.StreamConsumed): await response.aread() def test_cannot_read_after_response_closed():
64
64
88
9
55
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_cannot_read_after_response_closed
test_cannot_read_after_response_closed
289
303
289
289
f5b7f5f042aa98d61196a6421d076c9ec26ac165
bigcode/the-stack
train
bf79a9cc7b5becc1544a70d4
train
function
@pytest.mark.asyncio async def test_aiter_lines(): response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST) content = [] async for line in response.aiter_lines(): content.append(line) assert content == ["Hello,\n", "world!"]
@pytest.mark.asyncio async def test_aiter_lines():
response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST) content = [] async for line in response.aiter_lines(): content.append(line) assert content == ["Hello,\n", "world!"]
response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST) content = [] for line in response.iter_lines(): content.append(line) assert content == ["Hello,\n", "world!"] @pytest.mark.asyncio async def test_aiter_lines():
63
64
67
13
50
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_aiter_lines
test_aiter_lines
225
232
225
226
7f9961cddbf30cfa111b914655f50f2805fdb1ce
bigcode/the-stack
train
0cb6608666f49376d65f600f
train
function
def test_cannot_read_after_stream_consumed(): stream = IteratorStream(iterator=streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) content = b"" for part in response.iter_bytes(): content += part with pytest.raises(httpx.StreamConsumed): response.read()...
def test_cannot_read_after_stream_consumed():
stream = IteratorStream(iterator=streaming_body()) response = httpx.Response(200, stream=stream, request=REQUEST) content = b"" for part in response.iter_bytes(): content += part with pytest.raises(httpx.StreamConsumed): response.read()
=REQUEST) assert response.status_code == 200 assert not response.is_closed content = await response.aread() assert content == b"Hello, world!" assert response.content == b"Hello, world!" assert response.is_closed def test_cannot_read_after_stream_consumed():
64
64
70
10
53
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_cannot_read_after_stream_consumed
test_cannot_read_after_stream_consumed
264
273
264
264
c74b2ac1332faadf6b008f3c2165b3b9e0fcce4c
bigcode/the-stack
train
eeb211cd03004b5f89d004f5
train
function
def test_response_content_type_encoding(): """ Use the charset encoding in the Content-Type header if possible. """ headers = {"Content-Type": "text-plain; charset=latin-1"} content = "Latin 1: ÿ".encode("latin-1") response = httpx.Response(200, content=content, headers=headers, request=REQUEST)...
def test_response_content_type_encoding():
""" Use the charset encoding in the Content-Type header if possible. """ headers = {"Content-Type": "text-plain; charset=latin-1"} content = "Latin 1: ÿ".encode("latin-1") response = httpx.Response(200, content=content, headers=headers, request=REQUEST) assert response.text == "Latin 1: ÿ" ...
assert response.elapsed >= datetime.timedelta(0) assert not response.is_error def test_response_repr(): response = httpx.Response(200, content=b"Hello, world!", request=REQUEST) assert repr(response) == "<Response [200 OK]>" def test_response_content_type_encoding():
63
64
102
7
56
TheMrinalSinha/httpx
tests/models/test_responses.py
Python
test_response_content_type_encoding
test_response_content_type_encoding
39
47
39
39
f7840ca8ba7d7ea062931e874b9f2d9128b6f2db
bigcode/the-stack
train
f6ed57d728e13a832741204e
train
class
class RocmDbgapi(CMakePackage): """The AMD Debugger API is a library that provides all the support necessary for a debugger and other tools to perform low level control of the execution and inspection of execution state of AMD's commercially available GPU architectures.""" homepage = "http...
class RocmDbgapi(CMakePackage):
"""The AMD Debugger API is a library that provides all the support necessary for a debugger and other tools to perform low level control of the execution and inspection of execution state of AMD's commercially available GPU architectures.""" homepage = "https://github.com/ROCm-Developer-To...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RocmDbgapi(CMakePackage):
63
256
936
9
54
pbrady/spack
var/spack/repos/builtin/packages/rocm-dbgapi/package.py
Python
RocmDbgapi
RocmDbgapi
10
46
10
10
bbe45c6b22db06558e18c9ca8b54ec82cd0965e9
bigcode/the-stack
train
c239b2e183dd52d69cccf38b
train
class
@attr.s(auto_attribs=True) class DeploymentRequest: """ """ mz_version: str size: Union[Unset, DeploymentRequestSize] = UNSET additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: mz_version = self.mz_version size: Union[Uns...
@attr.s(auto_attribs=True) class DeploymentRequest:
""" """ mz_version: str size: Union[Unset, DeploymentRequestSize] = UNSET additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: mz_version = self.mz_version size: Union[Unset, str] = UNSET if not isinstance(self.size...
from typing import Any, Dict, Type, TypeVar, Tuple, Optional, BinaryIO, TextIO from typing import List import attr from ..types import UNSET, Unset from ..types import UNSET, Unset from typing import Union from ..models.deployment_request_size import DeploymentRequestSize T = TypeVar("T", bound="DeploymentRequ...
92
120
402
13
79
benesch/cloud-sdks
python/mzcloud/models/deployment_request.py
Python
DeploymentRequest
DeploymentRequest
19
83
19
20
6c1c2d508390cedc05eaedbaed350d1c74661f02
bigcode/the-stack
train
ba2d3cdf3fad1f7fac2b02a0
train
function
def get_pruning_model(model, begin_step, end_step): import tensorflow.compat.v1 as tf if tf.__version__.startswith('2'): # model pruning API is not supported in TF 2.0 yet raise Exception('model pruning is not fully supported in TF 2.x, Please switch env to TF 1.x for this feature') pruning...
def get_pruning_model(model, begin_step, end_step):
import tensorflow.compat.v1 as tf if tf.__version__.startswith('2'): # model pruning API is not supported in TF 2.0 yet raise Exception('model pruning is not fully supported in TF 2.x, Please switch env to TF 1.x for this feature') pruning_params = { 'pruning_schedule': sparsity.Polyn...
, just use # "metrics_names" and "metrics_tensors" as follow: # #model.metrics_names.append(name) #model.metrics_tensors.append(loss) model.add_metric(metric, name=name, aggregation='mean') def get_pruning_model(model, begin_step, end_step):
64
64
155
13
51
xanderdavies/keras-YOLOv3-model-set
common/model_utils.py
Python
get_pruning_model
get_pruning_model
25
40
25
25
e621fc0b7d9edb737796d5ea08128fda3cceb987
bigcode/the-stack
train
4d03c4720e20e0ee690d9060
train
function
def add_metrics(model, metric_dict): ''' add metric scalar tensor into model, which could be tracked in training log and tensorboard callback ''' for (name, metric) in metric_dict.items(): # seems add_metric() is newly added in tf.keras. So if you # want to customize metrics on raw k...
def add_metrics(model, metric_dict):
''' add metric scalar tensor into model, which could be tracked in training log and tensorboard callback ''' for (name, metric) in metric_dict.items(): # seems add_metric() is newly added in tf.keras. So if you # want to customize metrics on raw keras model, just use # "metri...
from tensorflow.keras.optimizers import Adam, RMSprop, SGD from tensorflow.keras.optimizers.schedules import ExponentialDecay, PolynomialDecay, PiecewiseConstantDecay from tensorflow.keras.experimental import CosineDecay from tensorflow_model_optimization.sparsity import keras as sparsity def add_metrics(model, metric_...
64
64
124
8
55
xanderdavies/keras-YOLOv3-model-set
common/model_utils.py
Python
add_metrics
add_metrics
10
22
10
10
08ebf164cc65fad0cdd5c4e0799716e501bc9df2
bigcode/the-stack
train
7b424a22c0c2ad40394306a8
train
function
def get_lr_scheduler(learning_rate, decay_type, decay_steps): if decay_type: decay_type = decay_type.lower() if decay_type == None: lr_scheduler = learning_rate elif decay_type == 'cosine': lr_scheduler = CosineDecay(initial_learning_rate=learning_rate, decay_steps=decay_steps) ...
def get_lr_scheduler(learning_rate, decay_type, decay_steps):
if decay_type: decay_type = decay_type.lower() if decay_type == None: lr_scheduler = learning_rate elif decay_type == 'cosine': lr_scheduler = CosineDecay(initial_learning_rate=learning_rate, decay_steps=decay_steps) elif decay_type == 'exponential': lr_scheduler = Expon...
0.001 #elif epoch > 0.5 * total_epochs: #lr = 0.01 #else: #lr = 0.1 #print('learning_rate change to: {}'.format(lr)) #return lr def get_lr_scheduler(learning_rate, decay_type, decay_steps):
73
73
246
14
58
xanderdavies/keras-YOLOv3-model-set
common/model_utils.py
Python
get_lr_scheduler
get_lr_scheduler
100
120
100
100
6bd7170fb34ff3e1a30ab34e1de0c9d9237558a1
bigcode/the-stack
train
5f76649387361565ef42e72d
train
function
def get_optimizer(optim_type, learning_rate, decay_type='cosine', decay_steps=100000): optim_type = optim_type.lower() lr_scheduler = get_lr_scheduler(learning_rate, decay_type, decay_steps) if optim_type == 'adam': optimizer = Adam(learning_rate=lr_scheduler, amsgrad=False) elif optim_type ==...
def get_optimizer(optim_type, learning_rate, decay_type='cosine', decay_steps=100000):
optim_type = optim_type.lower() lr_scheduler = get_lr_scheduler(learning_rate, decay_type, decay_steps) if optim_type == 'adam': optimizer = Adam(learning_rate=lr_scheduler, amsgrad=False) elif optim_type == 'rmsprop': optimizer = RMSprop(learning_rate=lr_scheduler, rho=0.9, momentum=0...
., learning_rate/100.] lr_scheduler = PiecewiseConstantDecay(boundaries=boundaries, values=values) else: raise ValueError('Unsupported lr decay type') return lr_scheduler def get_optimizer(optim_type, learning_rate, decay_type='cosine', decay_steps=100000):
64
64
155
22
41
xanderdavies/keras-YOLOv3-model-set
common/model_utils.py
Python
get_optimizer
get_optimizer
123
137
123
123
d68bbdfd1ba34cb127b003d5cd22a53a8d3fee55
bigcode/the-stack
train
18c3d9a12dc731b82fb88ea9
train
function
def euler_to_Rot(yaw, pitch, roll): Y = np.array([[math.cos(yaw), 0, math.sin(yaw)], [0, 1, 0], [-math.sin(yaw), 0, math.cos(yaw)]]) P = np.array([[1, 0, 0], [0, math.cos(pitch), -math.sin(pitch)], [0, math.sin(pitch), math.cos(pitch)]]) ...
def euler_to_Rot(yaw, pitch, roll):
Y = np.array([[math.cos(yaw), 0, math.sin(yaw)], [0, 1, 0], [-math.sin(yaw), 0, math.cos(yaw)]]) P = np.array([[1, 0, 0], [0, math.cos(pitch), -math.sin(pitch)], [0, math.sin(pitch), math.cos(pitch)]]) R = np.array([[math.cos(roll), -ma...
_transform(center, scale, rot, output_size) dst_img = cv2.warpAffine(img, trans, (int(output_size[0]), int(output_size[1])), flags=cv2.INTER_LINEAR) return dst_img def euler_to_Rot(yaw, pitch, roll):
64
64
159
13
50
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
euler_to_Rot
euler_to_Rot
89
99
89
89
096b9eb9d5cb61b5448907c8dd370116e3ae960d
bigcode/the-stack
train
c08e850f8db625b863bd6d10
train
function
def draw_msra_gaussian(heatmap, center, sigma): tmp_size = sigma * 3 mu_x = int(center[0] + 0.5) mu_y = int(center[1] + 0.5) w, h = heatmap.shape[0], heatmap.shape[1] ul = [int(mu_x - tmp_size), int(mu_y - tmp_size)] br = [int(mu_x + tmp_size + 1), int(mu_y + tmp_size + 1)] if ul[0] >= h or ...
def draw_msra_gaussian(heatmap, center, sigma):
tmp_size = sigma * 3 mu_x = int(center[0] + 0.5) mu_y = int(center[1] + 0.5) w, h = heatmap.shape[0], heatmap.shape[1] ul = [int(mu_x - tmp_size), int(mu_y - tmp_size)] br = [int(mu_x + tmp_size + 1), int(mu_y + tmp_size + 1)] if ul[0] >= h or ul[1] >= w or br[0] < 0 or br[1] < 0: re...
(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug idx = (masked_gaussian >= masked_heatmap).reshape( 1, masked_gaussian.shape[0], masked_gaussian.shape[1]) masked_regmap = (1 - idx) * masked_regmap + idx * masked_reg regmap[:, y - top:y + bottom, x - left:x + r...
120
120
401
14
105
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
draw_msra_gaussian
draw_msra_gaussian
216
237
216
216
9b9982af441dd90d954c6d82ad7d7022510f9daf
bigcode/the-stack
train
c0dca88b590ed9876c7e94a8
train
function
def get_dir(src_point, rot_rad): sn, cs = np.sin(rot_rad), np.cos(rot_rad) src_result = [0, 0] src_result[0] = src_point[0] * cs - src_point[1] * sn src_result[1] = src_point[0] * sn + src_point[1] * cs return src_result
def get_dir(src_point, rot_rad):
sn, cs = np.sin(rot_rad), np.cos(rot_rad) src_result = [0, 0] src_result[0] = src_point[0] * cs - src_point[1] * sn src_result[1] = src_point[0] * sn + src_point[1] * cs return src_result
new_pt = np.dot(t, new_pt) return new_pt[:2] def get_3rd_point(a, b): direct = a - b return b + np.array([-direct[1], direct[0]], dtype=np.float32) def get_dir(src_point, rot_rad):
64
64
85
9
55
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
get_dir
get_dir
68
75
68
68
af8f15f04f85e7ea378b9b6a67ebe37e65bb1b57
bigcode/the-stack
train
86f2e82f4abaa652d90d8c15
train
function
def affine_transform(pt, t): new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T new_pt = np.dot(t, new_pt) return new_pt[:2]
def affine_transform(pt, t):
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T new_pt = np.dot(t, new_pt) return new_pt[:2]
0, :], dst[1, :]) if inv: trans = cv2.getAffineTransform(np.float32(dst), np.float32(src)) else: trans = cv2.getAffineTransform(np.float32(src), np.float32(dst)) return trans def affine_transform(pt, t):
64
64
51
7
56
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
affine_transform
affine_transform
57
60
57
57
c7273e0ee4b4719040c38aabc217eae2c860cca3
bigcode/the-stack
train
6ad445b94d84eeee2546a8be
train
function
def draw_umich_gaussian(heatmap, center, radius, k=1): 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(...
def draw_umich_gaussian(heatmap, center, radius, k=1):
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) masked_hea...
] h = np.exp(-(x * x + y * y) / (2 * sigma * sigma)) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_umich_gaussian(heatmap, center, radius, k=1):
64
64
216
18
45
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
draw_umich_gaussian
draw_umich_gaussian
164
180
164
164
f423cada4d772a633f1bc1dc9911af8fc3f1f115
bigcode/the-stack
train
3ceda20f5954c552d44d8f31
train
function
def get_3rd_point(a, b): direct = a - b return b + np.array([-direct[1], direct[0]], dtype=np.float32)
def get_3rd_point(a, b):
direct = a - b return b + np.array([-direct[1], direct[0]], dtype=np.float32)
return trans def affine_transform(pt, t): new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T new_pt = np.dot(t, new_pt) return new_pt[:2] def get_3rd_point(a, b):
64
64
37
10
54
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
get_3rd_point
get_3rd_point
63
65
63
63
bec8dca893ae38581853584e70636505be5c7df5
bigcode/the-stack
train
67fb934045e7aa8b03d8ca28
train
function
def get_affine_transform(center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=0): if not isinstance(scale, np.ndarray) and not isinstance(scale, list): scale...
def get_affine_transform(center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=0):
if not isinstance(scale, np.ndarray) and not isinstance(scale, list): scale = np.array([scale, scale], dtype=np.float32) scale_tmp = scale src_w = scale_tmp[0] dst_w = output_size[0] dst_h = output_size[1] rot_rad = np.pi * rot / 180 src_dir = get_dir([0, src_w * -0.5], rot_rad) ...
, scale, output_size): target_coords = np.zeros(coords.shape) trans = get_affine_transform(center, scale, 0, output_size, inv=1) for p in range(coords.shape[0]): target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans) return target_coords def get_affine_transform(center, ...
111
111
370
37
73
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
get_affine_transform
get_affine_transform
21
54
21
26
2cddfe5215e7bb3c510f029fcb6ae65bcc641161
bigcode/the-stack
train
89a51006cca9252858732f3a
train
function
def flip(img): return img[:, :, ::-1].copy()
def flip(img):
return img[:, :, ::-1].copy()
import numpy as np import cv2 import random import math from .utils import convert_3d_to_2d def flip(img):
32
64
15
4
27
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
flip
flip
9
10
9
9
80298f294b041ab8d95abf74a7ef9d20a7fc92ed
bigcode/the-stack
train
3913aabf6275a2a62f103a9f
train
function
def get_bbox(yaw, pitch, roll, x, y, z, width, height, output_w, output_h, car_hw=1.02, car_hh=0.80, car_hl=2.31): Rt = np.eye(4) t = np.array([x, y, z]) Rt[:3, 3] = t Rt[:3, :3] = euler_to_Rot(-yaw, -pitch, -roll).T Rt = Rt[:3, :] P = np.array([ [-car_hw, ...
def get_bbox(yaw, pitch, roll, x, y, z, width, height, output_w, output_h, car_hw=1.02, car_hh=0.80, car_hl=2.31):
Rt = np.eye(4) t = np.array([x, y, z]) Rt[:3, 3] = t Rt[:3, :3] = euler_to_Rot(-yaw, -pitch, -roll).T Rt = Rt[:3, :] P = np.array([ [-car_hw, 0, 0, 1], [ car_hw, 0, 0, 1], [ 0, car_hh, 0, 1], [ 0, -car_hh, 0, 1], ...
.cos(roll), -math.sin(roll), 0], [math.sin(roll), math.cos(roll), 0], [0, 0, 1]]) return np.dot(Y, np.dot(P, R)) def get_bbox(yaw, pitch, roll, x, y, z, width, height, output_w, output_h, car_hw=1.02, car_hh=0.80, car_hl=2.31):
101
101
337
51
50
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
get_bbox
get_bbox
102
128
102
104
546c44e206fe041f5b80d24cf52b062376a6f984
bigcode/the-stack
train
49cdffe642679afe103f88de
train
function
def draw_dense_reg(regmap, heatmap, center, value, radius, is_offset=False): diameter = 2 * radius + 1 gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6) value = np.array(value, dtype=np.float32).reshape(-1, 1, 1) dim = value.shape[0] reg = np.ones((dim, diameter * 2 + 1, diameter * 2 +...
def draw_dense_reg(regmap, heatmap, center, value, radius, is_offset=False):
diameter = 2 * radius + 1 gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6) value = np.array(value, dtype=np.float32).reshape(-1, 1, 1) dim = value.shape[0] reg = np.ones((dim, diameter * 2 + 1, diameter * 2 + 1), dtype=np.float32) * value if is_offset and dim == ...
(y, radius), min(height - y, radius + 1) masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right] masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug ...
133
133
446
20
112
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
draw_dense_reg
draw_dense_reg
183
213
183
183
0cbce9e7f5e5a0c882678d603ee322b38a2382d7
bigcode/the-stack
train
dd2ccd87ed6fe3b3d6688b81
train
function
def gaussian_radius(det_size, min_overlap=0.7): height, width = det_size a1 = 1 b1 = (height + width) c1 = width * height * (1 - min_overlap) / (1 + min_overlap) sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1) r1 = (b1 + sq1) / 2 a2 = 4 b2 = 2 * (height + width) c2 = (1 - min_overlap) ...
def gaussian_radius(det_size, min_overlap=0.7):
height, width = det_size a1 = 1 b1 = (height + width) c1 = width * height * (1 - min_overlap) / (1 + min_overlap) sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1) r1 = (b1 + sq1) / 2 a2 = 4 b2 = 2 * (height + width) c2 = (1 - min_overlap) * width * height sq2 = np.sqrt(b2 ** 2 - 4 *...
]) bbox = [xs.min(), ys.min(), xs.max(), ys.max()] bbox[0] *= output_w / width bbox[1] *= output_h / height bbox[2] *= output_w / width bbox[3] *= output_h / height return bbox def gaussian_radius(det_size, min_overlap=0.7):
79
79
265
13
65
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
gaussian_radius
gaussian_radius
131
152
131
131
0c404ede5743b5fe603e9e9930f7a7f9cdcfb61d
bigcode/the-stack
train
777061a76217dd50162f3818
train
function
def crop(img, center, scale, output_size, rot=0): trans = get_affine_transform(center, scale, rot, output_size) dst_img = cv2.warpAffine(img, trans, (int(output_size[0]), int(output_size[1])), flags=cv2.INTER_LINEAR) re...
def crop(img, center, scale, output_size, rot=0):
trans = get_affine_transform(center, scale, rot, output_size) dst_img = cv2.warpAffine(img, trans, (int(output_size[0]), int(output_size[1])), flags=cv2.INTER_LINEAR) return dst_img
_result[0] = src_point[0] * cs - src_point[1] * sn src_result[1] = src_point[0] * sn + src_point[1] * cs return src_result def crop(img, center, scale, output_size, rot=0):
64
64
72
15
48
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
crop
crop
78
86
78
78
5e80c4c28968f0bce272213f9e747b85b420152e
bigcode/the-stack
train
5bbba2ab9d9ef3624b5d9bc3
train
function
def transform_preds(coords, center, scale, output_size): target_coords = np.zeros(coords.shape) trans = get_affine_transform(center, scale, 0, output_size, inv=1) for p in range(coords.shape[0]): target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans) return target_coords
def transform_preds(coords, center, scale, output_size):
target_coords = np.zeros(coords.shape) trans = get_affine_transform(center, scale, 0, output_size, inv=1) for p in range(coords.shape[0]): target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans) return target_coords
import numpy as np import cv2 import random import math from .utils import convert_3d_to_2d def flip(img): return img[:, :, ::-1].copy() def transform_preds(coords, center, scale, output_size):
55
64
80
12
43
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
transform_preds
transform_preds
13
18
13
13
543f64c6938922aad085e941c9f60cf9bf179ad1
bigcode/the-stack
train
5223d0601fcd2a92263514a8
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
* width * height sq3 = np.sqrt(b3 ** 2 - 4 * a3 * c3) r3 = (b3 + sq3) / 2 return min(r1, r2, r3) def gaussian2D(shape, sigma=1):
64
64
98
10
54
iShohei220/kaggle-pku-autonomous-driving
lib/utils/image.py
Python
gaussian2D
gaussian2D
155
161
155
155
6492beda349b2c11a100f6ca88e8df1fb04d6bb4
bigcode/the-stack
train
3ddd89fc746fa97e5149d198
train
function
def test_pretty_print_array_of_tuple(): t = m.Tuple(a=m.Bit, b=m.Bit, c=m.Bit) u = m.Array[3, t] assert m.util.pretty_str(u) == """\ Array[3, Tuple( a = Bit, b = Bit, c = Bit )]\ """
def test_pretty_print_array_of_tuple():
t = m.Tuple(a=m.Bit, b=m.Bit, c=m.Bit) u = m.Array[3, t] assert m.util.pretty_str(u) == """\ Array[3, Tuple( a = Bit, b = Bit, c = Bit )]\ """
.pretty_str(u) == """\ Tuple( x = Tuple( a = Bit, b = Bit, c = Bit ), y = Tuple( a = Bit, b = Bit, c = Bit ) )\ """ def test_pretty_print_array_of_tuple():
64
64
71
9
55
gitter-badger/magma
tests/test_type/test_pretty_print.py
Python
test_pretty_print_array_of_tuple
test_pretty_print_array_of_tuple
34
43
34
34
4c85cac16962b6af5f36f5f5f924c4a7e2472233
bigcode/the-stack
train
246987db73caceb9f6e57e35
train
function
def test_pretty_print_tuple_recursive(): t = m.Tuple(a=m.Bit, b=m.Bit, c=m.Bit) u = m.Tuple(x=t, y=t) assert m.util.pretty_str(u) == """\ Tuple( x = Tuple( a = Bit, b = Bit, c = Bit ), y = Tuple( a = Bit, b = Bit, c = Bit ) )\ """
def test_pretty_print_tuple_recursive():
t = m.Tuple(a=m.Bit, b=m.Bit, c=m.Bit) u = m.Tuple(x=t, y=t) assert m.util.pretty_str(u) == """\ Tuple( x = Tuple( a = Bit, b = Bit, c = Bit ), y = Tuple( a = Bit, b = Bit, c = Bit ) )\ """
m def test_pretty_print_tuple(): t = m.Tuple(a=m.Bit, b=m.Bit, c=m.Bit) assert m.util.pretty_str(t) == """\ Tuple( a = Bit, b = Bit, c = Bit )\ """ def test_pretty_print_tuple_recursive():
64
64
95
8
56
gitter-badger/magma
tests/test_type/test_pretty_print.py
Python
test_pretty_print_tuple_recursive
test_pretty_print_tuple_recursive
15
31
15
15
89e422d3eb7174f5d502e525785bacc906fe5a37
bigcode/the-stack
train
995757721d2d9e06b283ee24
train
function
def test_pretty_print_array_of_nested_tuple(): t = m.Tuple(a=m.Bits[5], b=m.UInt[3], c=m.SInt[4]) u = m.Tuple(x=t, y=t) v = m.Array[3, u] assert m.util.pretty_str(v) == """\ Array[3, Tuple( x = Tuple( a = Bits[5], b = UInt[3], c = SInt[4] ), y = Tuple( a = Bit...
def test_pretty_print_array_of_nested_tuple():
t = m.Tuple(a=m.Bits[5], b=m.UInt[3], c=m.SInt[4]) u = m.Tuple(x=t, y=t) v = m.Array[3, u] assert m.util.pretty_str(v) == """\ Array[3, Tuple( x = Tuple( a = Bits[5], b = UInt[3], c = SInt[4] ), y = Tuple( a = Bits[5], b = UInt[3], c = SInt[4] ...
, b=m.Bit, c=m.Bit) u = m.Array[3, t] assert m.util.pretty_str(u) == """\ Array[3, Tuple( a = Bit, b = Bit, c = Bit )]\ """ def test_pretty_print_array_of_nested_tuple():
64
64
134
10
54
gitter-badger/magma
tests/test_type/test_pretty_print.py
Python
test_pretty_print_array_of_nested_tuple
test_pretty_print_array_of_nested_tuple
46
63
46
46
5e1204df7d8a8ef98da7b405c470387114a92c06
bigcode/the-stack
train
2cbbacdbf23e806d066122c9
train
function
def test_pretty_print_tuple(): t = m.Tuple(a=m.Bit, b=m.Bit, c=m.Bit) assert m.util.pretty_str(t) == """\ Tuple( a = Bit, b = Bit, c = Bit )\ """
def test_pretty_print_tuple():
t = m.Tuple(a=m.Bit, b=m.Bit, c=m.Bit) assert m.util.pretty_str(t) == """\ Tuple( a = Bit, b = Bit, c = Bit )\ """
import magma as m def test_pretty_print_tuple():
12
64
54
7
4
gitter-badger/magma
tests/test_type/test_pretty_print.py
Python
test_pretty_print_tuple
test_pretty_print_tuple
4
12
4
4
af2609773060970a15a5da9f8a686321a442af7f
bigcode/the-stack
train
8b4360824e562cecad5be46f
train
function
def _check_ibmqe_version(): """Check if the available IBMQuantumExperience version is the required one. Check that the version of the available "IBMQuantumExperience" package matches the version required by the package, emitting a warning if it is not present. """ try: # Use a local imp...
def _check_ibmqe_version():
"""Check if the available IBMQuantumExperience version is the required one. Check that the version of the available "IBMQuantumExperience" package matches the version required by the package, emitting a warning if it is not present. """ try: # Use a local import, as in very specific env...
2017 IBM RESEARCH. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
175
175
585
8
167
ishandutta2007/qiskit-sdk-py
qiskit/_util.py
Python
_check_ibmqe_version
_check_ibmqe_version
26
93
26
26
6f50a4780d42dfc36ede8f25530eeacc15f2726e
bigcode/the-stack
train
c69557e2a5cbf2779957707a
train
class
class Layer: """ Class representing a layer, for which we have a set of macro sequences or keycodes""" def __init__(self, layerdata): self.name = layerdata['name'] self.macros = layerdata['macros']
class Layer:
""" Class representing a layer, for which we have a set of macro sequences or keycodes""" def __init__(self, layerdata): self.name = layerdata['name'] self.macros = layerdata['macros']
.D6), column_pins=(board.D7, board.D8, board.D9, board.D10, board.D0, board.D1), columns_to_anodes=True, ) # CONFIGURABLES ------------------------ MACRO_FOLDER = '/layers' # CLASSES AND FUNCTIONS ---------------- class Layer:
64
64
55
3
60
Mindplague/pykey
examples/Gherkin-Xiao/code.py
Python
Layer
Layer
25
30
25
25
af6d0a023587557fafc0d2ea3e60e924d7a75787
bigcode/the-stack
train
51d6160d637f002cfbebdd31
train
function
def create_apps(): app = Flask(__name__) app.config.from_object(config) app.register_blueprint(cms_bp) app.register_blueprint(common_bp) app.register_blueprint(front_bp) db.init_app(app) mail.init_app(app) CSRFProtect(app) return app
def create_apps():
app = Flask(__name__) app.config.from_object(config) app.register_blueprint(cms_bp) app.register_blueprint(common_bp) app.register_blueprint(front_bp) db.init_app(app) mail.init_app(app) CSRFProtect(app) return app
from flask import Flask from flask_wtf import CSRFProtect from apps.cms import bp as cms_bp from apps.common import bp as common_bp from apps.front import bp as front_bp import config from exts import db,mail def create_apps():
56
64
66
4
51
XmlinX/Flask_cms
app.py
Python
create_apps
create_apps
10
22
10
10
1322f87253ddb55f587fa06b93b5ffe64ae0d52e
bigcode/the-stack
train
ce044aa7a0867321da0888b0
train
class
class d190118(File): def __init__(self): super().__init__() self.directory = get_checs("d190118_trigger_stability") self.spoi = [ 17, # 296, 297, # 298, 372, 408, 412, 415, 503 ...
class d190118(File):
def __init__(self): super().__init__() self.directory = get_checs("d190118_trigger_stability") self.spoi = [ 17, # 296, 297, # 298, 372, 408, 412, 415, 503 ]
__init__(self): super().__init__() self.directory = get_checs("d190111_trigger_stability/d190111") self.spoi = [ 151, 101, 399, # 296, 145, ] class d190118(File):
63
64
79
6
57
watsonjj/CHECLabPySB
sstcam_sandbox/d190117_trigger_stability/__init__.py
Python
d190118
d190118
44
58
44
44
6c64c10904cf450e246a480f71da9f67e53abdb1
bigcode/the-stack
train
cb196f3f5c821e81b6c804db
train
class
class d190111(File): def __init__(self): super().__init__() self.directory = get_checs("d190111_trigger_stability/d190111") self.spoi = [ 151, 101, 399, # 296, 145, ]
class d190111(File):
def __init__(self): super().__init__() self.directory = get_checs("d190111_trigger_stability/d190111") self.spoi = [ 151, 101, 399, # 296, 145, ]
.tio_paths] @property def trigger_path(self): return os.path.join(self.directory, "trigger.dat") @property def monitor_paths(self): return [path.replace("_r1.tio", ".mon") for path in self.tio_paths] class d190111(File):
64
64
65
6
58
watsonjj/CHECLabPySB
sstcam_sandbox/d190117_trigger_stability/__init__.py
Python
d190111
d190111
31
41
31
31
0bbfd858586a098c8a8f5330666fbfd8af0537a0
bigcode/the-stack
train
ddc1f31d19ea3d4a91152660
train
class
class File: def __init__(self): super().__init__() self.directory = None @property def tio_paths(self): return sort_file_list(glob(os.path.join(self.directory, "Run*_r1.tio"))) @property def tio_readers(self): return [TIOReader(path) for path in self.tio_paths] ...
class File:
def __init__(self): super().__init__() self.directory = None @property def tio_paths(self): return sort_file_list(glob(os.path.join(self.directory, "Run*_r1.tio"))) @property def tio_readers(self): return [TIOReader(path) for path in self.tio_paths] @property ...
from sstcam_sandbox import get_checs from glob import glob import re from CHECLabPy.core.io import TIOReader from CHECLabPy.utils.files import sort_file_list import os class File:
49
64
134
3
45
watsonjj/CHECLabPySB
sstcam_sandbox/d190117_trigger_stability/__init__.py
Python
File
File
9
28
9
9
76e9b5f04c2d3f3f953fb2b12de685433a863da5
bigcode/the-stack
train
c1c25886d96b0e063b7c0416
train
class
class d190121(File): def __init__(self): super().__init__() self.directory = get_checs("d190121_trigger_stability") self.spoi = [ 17, # 296, 297, # 298, 372, 408, 412, 415, 503 ...
class d190121(File):
def __init__(self): super().__init__() self.directory = get_checs("d190121_trigger_stability") self.spoi = [ 17, # 296, 297, # 298, 372, 408, 412, 415, 503 ]
= get_checs("d190118_trigger_stability") self.spoi = [ 17, # 296, 297, # 298, 372, 408, 412, 415, 503 ] class d190121(File):
64
64
79
6
58
watsonjj/CHECLabPySB
sstcam_sandbox/d190117_trigger_stability/__init__.py
Python
d190121
d190121
60
74
60
60
a6efa30c7e406c4e68ed42f03b19bb3eb192d4b1
bigcode/the-stack
train
d9cb72e7197596d9109795ff
train
function
@register.filter def split(value, arg): return value.split(arg)
@register.filter def split(value, arg):
return value.split(arg)
from ..views.utils import model_filter register = template.Library() @register.filter def url_resolve(request, arg): return resolve(request.path_info).url_name @register.filter def percent(value, arg): return int(value / 100) @register.filter def split(value, arg):
64
64
16
10
54
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
split
split
26
28
26
27
16777fce6568735bd998e3a4389cf52750c16a01
bigcode/the-stack
train
f6f3c61cd24e3d034a8a30a7
train
function
@register.filter def percent(value, arg): return int(value / 100)
@register.filter def percent(value, arg):
return int(value / 100)
import ThreadedComments from ..choices import * from ..models import Content, UTopic from ..views.utils import model_filter register = template.Library() @register.filter def url_resolve(request, arg): return resolve(request.path_info).url_name @register.filter def percent(value, arg):
64
64
18
10
53
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
percent
percent
21
23
21
22
33d52faf5b890b46c7558cfb0943e79e39d2677f
bigcode/the-stack
train
e9faa26b9ebd7629675fee83
train
function
@register.filter def json(value, arg): return value[arg]
@register.filter def json(value, arg):
return value[arg]
.filter def url_resolve(request, arg): return resolve(request.path_info).url_name @register.filter def percent(value, arg): return int(value / 100) @register.filter def split(value, arg): return value.split(arg) @register.filter def json(value, arg):
64
64
15
10
54
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
json
json
31
33
31
32
f6d50d292e1a947b5b0265c362334b8c854e751a
bigcode/the-stack
train
5b3f16a55de4d6b8db582ae8
train
function
@register.simple_tag def get_random(start, stop, step): return random.randrange(start, stop, step)
@register.simple_tag def get_random(start, stop, step):
return random.randrange(start, stop, step)
return UTopic.objects.filter(user=user).count() elif name == "comments": return ThreadedComments.objects.filter(to=user).exclude(user=user).count() elif name == "bookmark": return Bookmark.objects.filter(user=user).count() @register.simple_tag def get_random(start, stop, step):
64
64
24
14
50
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
get_random
get_random
60
62
60
61
8f448e2acc48d763bd0fe21eb102a5271f661db8
bigcode/the-stack
train
04e75c1c7f2b264bcd248329
train
function
@register.filter def url_resolve(request, arg): return resolve(request.path_info).url_name
@register.filter def url_resolve(request, arg):
return resolve(request.path_info).url_name
from django.urls import resolve from django_bookmark.models import Bookmark from ...threaded_comment.models import ThreadedComments from ..choices import * from ..models import Content, UTopic from ..views.utils import model_filter register = template.Library() @register.filter def url_resolve(request, arg):
64
64
22
12
52
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
url_resolve
url_resolve
16
18
16
17
b61fd8440d9e3a715d0cead1efe26548b075f42f
bigcode/the-stack
train
2142e596b9cf030acb4e844f
train
function
@register.filter def hmanycontent(user): if user.is_anonymous: return 0 obj = Content.objects.filter(user=user, status="ready") return obj.count()
@register.filter def hmanycontent(user):
if user.is_anonymous: return 0 obj = Content.objects.filter(user=user, status="ready") return obj.count()
_info).url_name @register.filter def percent(value, arg): return int(value / 100) @register.filter def split(value, arg): return value.split(arg) @register.filter def json(value, arg): return value[arg] @register.filter def hmanycontent(user):
64
64
40
10
54
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
hmanycontent
hmanycontent
36
41
36
37
db0a012389413598836316ed1d361791ca456e8b
bigcode/the-stack
train
1d69fafb0fbea0380e08c5f7
train
function
@register.filter def get_count(user, name): if name == "utopic": return UTopic.objects.filter(user=user).count() elif name == "comments": return ThreadedComments.objects.filter(to=user).exclude(user=user).count() elif name == "bookmark": return Bookmark.objects.filter(user=user).coun...
@register.filter def get_count(user, name):
if name == "utopic": return UTopic.objects.filter(user=user).count() elif name == "comments": return ThreadedComments.objects.filter(to=user).exclude(user=user).count() elif name == "bookmark": return Bookmark.objects.filter(user=user).count()
obj.count() @register.simple_tag def content_count(username, value, key): obj = Content.objects.filter(user__username=username, status="ready") return model_filter({str(value): key}.items(), obj).get("queryset").count() @register.filter def get_count(user, name):
64
64
70
11
53
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
get_count
get_count
50
57
50
51
19841fcb0e755df2813922c9e79aeb7374a8d5c3
bigcode/the-stack
train
58e7d3679278bdec247c8248
train
function
@register.simple_tag def content_count(username, value, key): obj = Content.objects.filter(user__username=username, status="ready") return model_filter({str(value): key}.items(), obj).get("queryset").count()
@register.simple_tag def content_count(username, value, key):
obj = Content.objects.filter(user__username=username, status="ready") return model_filter({str(value): key}.items(), obj).get("queryset").count()
json(value, arg): return value[arg] @register.filter def hmanycontent(user): if user.is_anonymous: return 0 obj = Content.objects.filter(user=user, status="ready") return obj.count() @register.simple_tag def content_count(username, value, key):
64
64
50
14
50
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
content_count
content_count
44
47
44
45
04283fe2fadfa3ebdb97254e7b1ac2236ea7ab49
bigcode/the-stack
train
3e66e30536503dd75208c79f
train
function
@register.filter def calculate_percent_utopic(utopic, choice): contents = Content.objects.filter(utopic=utopic, status="ready") how_many_content = utopic.how_many corl = dict() for content in contents: try: corl[getattr(content, choice)] += 1 except KeyError: corl...
@register.filter def calculate_percent_utopic(utopic, choice):
contents = Content.objects.filter(utopic=utopic, status="ready") how_many_content = utopic.how_many corl = dict() for content in contents: try: corl[getattr(content, choice)] += 1 except KeyError: corl[getattr(content, choice)] = 1 context = list() for mod...
=user).exclude(user=user).count() elif name == "bookmark": return Bookmark.objects.filter(user=user).count() @register.simple_tag def get_random(start, stop, step): return random.randrange(start, stop, step) @register.filter def calculate_percent_utopic(utopic, choice):
64
64
146
15
49
emregeldegul/coogger
core/cooggerapp/templatetags/coogger_tags.py
Python
calculate_percent_utopic
calculate_percent_utopic
65
84
65
66
3e5d858732d1bed8b112692475b5ee58795963ed
bigcode/the-stack
train