code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def back_propagation(self, delta_arr):
'''
Back propagation.
Args:
delta_output_arr: Delta.
Returns:
Tuple data.
- decoder's `list` of gradations,
- encoder's `np.ndarray` of Delta,
- encoder's `list` of... | Back propagation.
Args:
delta_output_arr: Delta.
Returns:
Tuple data.
- decoder's `list` of gradations,
- encoder's `np.ndarray` of Delta,
- encoder's `list` of gradations. | null | null | null | |
def optimize(
self,
re_encoder_grads_list,
decoder_grads_list,
encoder_grads_list,
learning_rate,
epoch
):
'''
Back propagation.
Args:
re_encoder_grads_list: re-encoder's `list` of graduations.
dec... | Back propagation.
Args:
re_encoder_grads_list: re-encoder's `list` of graduations.
decoder_grads_list: decoder's `list` of graduations.
encoder_grads_list: encoder's `list` of graduations.
learning_rate: Learning rate.
... | null | null | null | |
def __change_inferencing_mode(self, inferencing_mode):
'''
Change dropout rate in Encoder/Decoder.
Args:
dropout_rate: The probalibity of dropout.
'''
self.__encoder_decoder_controller.decoder.opt_params.inferencing_mode = inferencing_mode
s... | Change dropout rate in Encoder/Decoder.
Args:
dropout_rate: The probalibity of dropout. | null | null | null | |
def __remember_best_params(self, encoder_best_params_list, decoder_best_params_list, re_encoder_best_params_list):
'''
Remember best parameters.
Args:
encoder_best_params_list: `list` of encoder's parameters.
decoder_best_params_list: `list` of decode... | Remember best parameters.
Args:
encoder_best_params_list: `list` of encoder's parameters.
decoder_best_params_list: `list` of decoder's parameters.
re_encoder_best_params_list: `list` of re-decoder's parameters. | null | null | null | |
'''
Entry Point.
Args:
url: PDF url.
'''
# The object of Web-scraping.
web_scrape = WebScraping()
# Set the object of reading PDF files.
web_scrape.readable_web_pdf = WebPDFReading()
# Execute Web-scraping.
document = web_scrape.scrape(url)
if similarity_mode... | def Main(url, similarity_mode="TfIdfCosine", similarity_limit=0.75) | Entry Point.
Args:
url: PDF url. | 3.909132 | 3.688243 | 1.05989 |
def generate(self):
'''
Generate noise samples.
Returns:
`np.ndarray` of samples.
'''
observed_arr = None
for row in range(self.__batch_size):
arr = None
for d in range(self.__dim):
_arr = self.__gene... | Generate noise samples.
Returns:
`np.ndarray` of samples. | null | null | null | |
'''
Entry Point.
Args:
url: target url.
'''
# The object of Web-Scraping.
web_scrape = WebScraping()
# Execute Web-Scraping.
document = web_scrape.scrape(url)
# The object of NLP.
nlp_base = NlpBase()
# Set tokenizer. This is japanese tokenizer with MeCab.
... | def Main(url) | Entry Point.
Args:
url: target url. | 5.043251 | 4.753647 | 1.060922 |
''' getter '''
if isinstance(self.__var_arr, np.ndarray):
return self.__var_arr
else:
raise TypeError() | def get_var_arr(self) | getter | 5.231487 | 4.770946 | 1.09653 |
''' setter '''
if isinstance(value, np.ndarray):
self.__var_arr = value
else:
raise TypeError() | def set_var_arr(self, value) | setter | 5.06493 | 5.136888 | 0.985992 |
''' getter '''
if isinstance(self.__predicted_log_arr, np.ndarray):
return self.__predicted_log_arr
else:
raise TypeError() | def get_predicted_log_arr(self) | getter | 4.519621 | 4.028389 | 1.121943 |
''' setter '''
if isinstance(value, np.ndarray):
self.__predicted_log_arr = value
else:
raise TypeError() | def set_predicted_log_arr(self, value) | setter | 4.343719 | 4.297626 | 1.010725 |
''' getter '''
if isinstance(self.__var_log_arr, np.ndarray):
return self.__var_log_arr
else:
raise TypeError() | def get_var_log_arr(self) | getter | 4.355944 | 3.946895 | 1.103638 |
''' setter '''
if isinstance(value, np.ndarray):
self.__var_log_arr = value
else:
raise TypeError() | def set_var_log_arr(self, value) | setter | 4.537316 | 4.577607 | 0.991198 |
''' getter '''
if isinstance(self.__computed_cost_arr, np.ndarray):
return self.__computed_cost_arr
else:
raise TypeError() | def get_computed_cost_arr(self) | getter | 4.524843 | 4.158702 | 1.088042 |
''' setter '''
if isinstance(value, np.ndarray):
self.__computed_cost_arr = value
else:
raise TypeError() | def set_computed_cost_arr(self, value) | setter | 4.48319 | 4.518554 | 0.992174 |
def tokenize(self, vector_list):
'''
Tokenize vector.
Args:
vector_list: The list of vector of one token.
Returns:
token
'''
if self.computable_distance is None:
self.computable_distance = EuclidDistance()
... | Tokenize vector.
Args:
vector_list: The list of vector of one token.
Returns:
token | null | null | null | |
def set_computable_distance(self, value):
''' setter '''
if isinstance(value, ComputableDistance) is False:
raise TypeError()
self.__computable_distance = value | setter | null | null | null | |
def write_stream(self, stream, left_chunk, right_chunk, volume):
'''
具象メソッド
モノラルビートを生成する
Args:
stream: PyAudioのストリーム
left_chunk: 左音源に対応するチャンク
right_chunk: 右音源に対応するチャンク
volume: 音量
Returns:
... | 具象メソッド
モノラルビートを生成する
Args:
stream: PyAudioのストリーム
left_chunk: 左音源に対応するチャンク
right_chunk: 右音源に対応するチャンク
volume: 音量
Returns:
void | null | null | null | |
def read_stream(self, left_chunk, right_chunk, volume, bit16=32767.0):
'''
具象メソッド
wavファイルに保存するモノラルビートを読み込む
Args:
left_chunk: 左音源に対応するチャンク
right_chunk: 右音源に対応するチャンク
volume: 音量
bit16: 整数化の条件
Return... | 具象メソッド
wavファイルに保存するモノラルビートを読み込む
Args:
left_chunk: 左音源に対応するチャンク
right_chunk: 右音源に対応するチャンク
volume: 音量
bit16: 整数化の条件
Returns:
フレームのlist | null | null | null | |
'''
Tokenize str.
Args:
sentence_str: tokenized string.
Returns:
[token, token, token, ...]
'''
mt = MeCab.Tagger("-Owakati")
wordlist = mt.parse(sentence_str)
token_list = wordlist.rstrip(" \n").split(" ")
... | def tokenize(self, sentence_str) | Tokenize str.
Args:
sentence_str: tokenized string.
Returns:
[token, token, token, ...] | 4.810791 | 2.825212 | 1.702807 |
def train(
self,
true_sampler,
generative_model,
discriminative_model,
iter_n=100,
k_step=10
):
'''
Train.
Args:
true_sampler: Sampler which draws samples from the `true` distribution.
generative_... | Train.
Args:
true_sampler: Sampler which draws samples from the `true` distribution.
generative_model: Generator which draws samples from the `fake` distribution.
discriminative_model: Discriminator which discriminates `true` from `fake`.
... | null | null | null | |
def train_auto_encoder(self, generative_model, a_logs_list):
'''
Train the generative model as the Auto-Encoder.
Args:
generative_model: Generator which draws samples from the `fake` distribution.
a_logs_list: `list` of the reconstruction errors.
... | Train the generative model as the Auto-Encoder.
Args:
generative_model: Generator which draws samples from the `fake` distribution.
a_logs_list: `list` of the reconstruction errors.
Returns:
The tuple data. The shape is...
- Gene... | null | null | null | |
def compute_discriminator_reward(
self,
true_posterior_arr,
generated_posterior_arr
):
'''
Compute discriminator's reward.
Args:
true_posterior_arr: `np.ndarray` of `true` posterior inferenced by the discriminator.
generated_... | Compute discriminator's reward.
Args:
true_posterior_arr: `np.ndarray` of `true` posterior inferenced by the discriminator.
generated_posterior_arr: `np.ndarray` of `fake` posterior inferenced by the discriminator.
Returns:
`np.ndarray` of ... | null | null | null | |
'''
Select action by Q(state, action).
Args:
next_action_arr: `np.ndarray` of actions.
next_q_arr: `np.ndarray` of Q-Values.
Retruns:
Tuple(`np.ndarray` of action., Q-Value)
'''
key_arr = self.select_action_key(next... | def select_action(self, next_action_arr, next_q_arr) | Select action by Q(state, action).
Args:
next_action_arr: `np.ndarray` of actions.
next_q_arr: `np.ndarray` of Q-Values.
Retruns:
Tuple(`np.ndarray` of action., Q-Value) | 3.592827 | 1.655932 | 2.169671 |
'''
Select action by Q(state, action).
Args:
next_action_arr: `np.ndarray` of actions.
next_q_arr: `np.ndarray` of Q-Values.
Retruns:
`np.ndarray` of keys.
'''
epsilon_greedy_flag = bool(np.random.binomial(n=1, p=se... | def select_action_key(self, next_action_arr, next_q_arr) | Select action by Q(state, action).
Args:
next_action_arr: `np.ndarray` of actions.
next_q_arr: `np.ndarray` of Q-Values.
Retruns:
`np.ndarray` of keys. | 2.829847 | 1.870827 | 1.512619 |
if fields is None:
fields = []
page = int(page)
pages = float('inf')
data = {
"query": query,
"page": page,
"fields": fields,
"flatten": flatten
}
count = 0
while page <= pages:
payl... | def search(self, query, fields=None, page=1, max_records=None, flatten=True) | returns iterator over all records that match the given query | 2.613912 | 2.659616 | 0.982815 |
rp = Game.__color_modes.get(mode, {})
for k, color in self.__colors.items():
self.__colors[k] = rp.get(color, color) | def adjustColors(self, mode='dark') | Change a few colors depending on the mode to use. The default mode
doesn't assume anything and avoid using white & black colors. The dark
mode use white and avoid dark blue while the light mode use black and
avoid yellow, to give a few examples. | 6.590861 | 6.832213 | 0.964674 |
try:
with open(self.scores_file, 'r') as f:
self.best_score = int(f.readline(), 10)
except:
return False
return True | def loadBestScore(self) | load local best score from the default file | 3.142979 | 2.946549 | 1.066664 |
if self.score > self.best_score:
self.best_score = self.score
try:
with open(self.scores_file, 'w') as f:
f.write(str(self.best_score))
except:
return False
return True | def saveBestScore(self) | save current best score in the default file | 2.278303 | 2.234459 | 1.019622 |
self.score += pts
if self.score > self.best_score:
self.best_score = self.score | def incScore(self, pts) | update the current score by adding it the specified number of points | 2.454606 | 2.372835 | 1.034461 |
size = self.board.SIZE
cells = []
for i in range(size):
for j in range(size):
cells.append(str(self.board.getCell(j, i)))
score_str = "%s\n%d" % (' '.join(cells), self.score)
try:
with open(self.store_file, 'w') as f:
... | def store(self) | save the current game session's score and data for further use | 3.251953 | 2.891113 | 1.12481 |
size = self.board.SIZE
try:
with open(self.store_file, 'r') as f:
lines = f.readlines()
score_str = lines[0]
self.score = int(lines[1])
except:
return False
score_str_list = score_str.split(' ')
c... | def restore(self) | restore the saved game score and data | 3.03745 | 2.680273 | 1.133261 |
pause_key = self.board.PAUSE
margins = {'left': 4, 'top': 4, 'bottom': 4}
atexit.register(self.showCursor)
try:
self.hideCursor()
while True:
self.clearScreen()
print(self.__str__(margins=margins))
if self... | def loop(self) | main game loop. returns the final score. | 5.450699 | 5.054237 | 1.078441 |
return '.' if self.__azmode else ' .'
elif self.__azmode:
az = {}
for i in range(1, int(math.log(self.board.goal(), 2))):
az[2 ** i] = chr(i + 96)
if c not in az:
return '?'
s = az[c]
elif c == 1024:
... | def getCellStr(self, x, y): # TODO: refactor regarding issue #11
c = self.board.getCell(x, y)
if c == 0 | return a string representation of the cell located at x,y. | 4.457158 | 4.650572 | 0.958411 |
if margins is None:
margins = {}
b = self.board
rg = range(b.size())
left = ' '*margins.get('left', 0)
s = '\n'.join(
[left + ' '.join([self.getCellStr(x, y) for x in rg]) for y in rg])
return s | def boardToString(self, margins=None) | return a string representation of the current board. | 4.351248 | 4.201705 | 1.035591 |
if not self.filled():
return True
for y in self.__size_range:
for x in self.__size_range:
c = self.getCell(x, y)
if (x < self.__size-1 and c == self.getCell(x+1, y)) \
or (y < self.__size-1 and c == self.getCell(x, y+1)... | def canMove(self) | test if a move is possible | 3.056662 | 2.892266 | 1.05684 |
if choices is None:
choices = [2] * 9 + [4]
if value:
choices = [value]
v = random.choice(choices)
empty = self.getEmptyCells()
if empty:
x, y = random.choice(empty)
self.setCell(x, y, v) | def addTile(self, value=None, choices=None) | add a random tile in an empty cell
value: value of the tile to add.
choices: a list of possible choices for the value of the tile. if
``None`` (the default), it uses
``[2, 2, 2, 2, 2, 2, 2, 2, 2, 4]``. | 3.884902 | 3.195222 | 1.215847 |
self.cells[y][x] = v | def setCell(self, x, y, v) | set the cell value at x,y | 5.320478 | 4.958828 | 1.072931 |
return [self.getCell(x, i) for i in self.__size_range] | def getCol(self, x) | return the x-th column, starting at 0 | 13.353764 | 12.779783 | 1.044913 |
for i in xrange(0, self.__size):
self.setCell(x, i, l[i]) | def setCol(self, x, l) | set the x-th column, starting at 0 | 4.672573 | 4.908163 | 0.952 |
return [(x, y)
for x in self.__size_range
for y in self.__size_range if self.getCell(x, y) == 0] | def getEmptyCells(self) | return a (x, y) pair for each empty cell | 5.057689 | 3.774974 | 1.339795 |
if (d == Board.LEFT or d == Board.UP):
inc = 1
rg = xrange(0, self.__size-1, inc)
else:
inc = -1
rg = xrange(self.__size-1, 0, inc)
pts = 0
for i in rg:
if line[i] == 0:
continue
if line[i] ... | def __collapseLineOrCol(self, line, d) | Merge tiles in a line or column according to a direction and return a
tuple with the new line and the score for the move on this line | 3.450751 | 3.096504 | 1.114402 |
nl = [c for c in line if c != 0]
if d == Board.UP or d == Board.LEFT:
return nl + [0] * (self.__size - len(nl))
return [0] * (self.__size - len(nl)) + nl | def __moveLineOrCol(self, line, d) | Move a line or column to a given direction (d) | 3.800576 | 3.574684 | 1.063192 |
if d == Board.LEFT or d == Board.RIGHT:
chg, get = self.setLine, self.getLine
elif d == Board.UP or d == Board.DOWN:
chg, get = self.setCol, self.getCol
else:
return 0
moved = False
score = 0
for i in self.__size_range:
... | def move(self, d, add_tile=True) | move and return the move score | 4.757124 | 4.604259 | 1.033201 |
parser = argparse.ArgumentParser(description='2048 in your terminal')
parser.add_argument('--mode', dest='mode', type=str,
default=None, help='colors mode (dark or light)')
parser.add_argument('--az', dest='azmode', action='store_true',
help='Use the lett... | def parse_cli_args() | parse args from the CLI and return a dict | 3.196184 | 3.125101 | 1.022746 |
args = parse_cli_args()
if args['version']:
print_version_and_exit()
if args['rules']:
print_rules_and_exit()
game = Game(**args)
if args['resume']:
game.restore()
if debug:
return game
return game.loop() | def start_game(debug=False) | Start a new game. If ``debug`` is set to ``True``, the game object is
returned and the game loop isn't fired. | 4.530225 | 4.182133 | 1.083233 |
message = ObjectDict(escape.json_decode(message))
if message.command == 'hello':
handshake = {
'command': 'hello',
'protocols': [
'http://livereload.com/protocols/official-7',
],
'serverName': 'liver... | def on_message(self, message) | Handshake with livereload.js
1. client send 'hello'
2. server reply 'hello'
3. client send 'info' | 4.729206 | 4.252817 | 1.112017 |
stat_result = os.stat(abspath)
modified = datetime.datetime.utcfromtimestamp(
stat_result[stat.ST_MTIME])
return modified | def get_content_modified_time(cls, abspath) | Returns the time that ``abspath`` was last modified.
May be overridden in subclasses. Should return a `~datetime.datetime`
object or None. | 3.225852 | 3.226468 | 0.999809 |
data = cls.get_content(abspath)
hasher = hashlib.md5()
mtime_data = format(cls.get_content_modified_time(abspath), "%Y-%m-%d %H:%M:%S")
hasher.update(mtime_data.encode())
if isinstance(data, bytes):
hasher.update(data)
else:
for chunk i... | def get_content_version(cls, abspath) | Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1 | 2.841367 | 2.926512 | 0.970906 |
_, ext = os.path.splitext(filename)
return ext in ['.pyc', '.pyo', '.o', '.swp'] | def ignore(self, filename) | Ignore a given filename or not. | 3.858968 | 3.861065 | 0.999457 |
self._tasks[path] = {
'func': func,
'delay': delay,
'ignore': ignore,
} | def watch(self, path, func=None, delay=0, ignore=None) | Add a task to watcher.
:param path: a filepath or directory path or glob pattern
:param func: the function to be executed when file changed
:param delay: Delay sending the reload message. Use 'forever' to
not send it. This is useful to compile sass files to
... | 3.060741 | 3.388331 | 0.903318 |
if self._changes:
return self._changes.pop()
# clean filepath
self.filepath = None
delays = set()
for path in self._tasks:
item = self._tasks[path]
if self.is_changed(path, item['ignore']):
func = item['func']
... | def examine(self) | Check if there are changes, if true, run the given task. | 4.126311 | 3.724573 | 1.107861 |
if not output:
output = os.devnull
else:
folder = os.path.dirname(output)
if folder and not os.path.isdir(folder):
os.makedirs(folder)
if not isinstance(cmd, (list, tuple)) and not shell:
cmd = shlex.split(cmd)
def run_shell():
try:
... | def shell(cmd, output=None, mode='w', cwd=None, shell=False) | Execute a shell command.
You can add a shell command::
server.watch(
'style.less', shell('lessc style.less', output='style.css')
)
:param cmd: a shell command, string or list
:param output: output stdout to the given file
:param mode: only works with output, mode ``w`` mea... | 2.692058 | 2.966066 | 0.907619 |
if isinstance(func, string_types):
cmd = func
func = shell(func)
func.name = "shell: {}".format(cmd)
self.watcher.watch(filepath, func, delay, ignore=ignore) | def watch(self, filepath, func=None, delay=None, ignore=None) | Add the given filepath for watcher list.
Once you have intialized a server, watch file changes before
serve the server::
server.watch('static/*.stylus', 'make static')
def alert():
print('foo')
server.watch('foo.txt', alert)
server.serve(... | 5.80302 | 6.212649 | 0.934065 |
host = host or '127.0.0.1'
if root is not None:
self.root = root
self._setup_logging()
logger.info('Serving on http://%s:%s' % (host, port))
self.application(
port, host, liveport=liveport, debug=debug, live_css=live_css)
# Async open w... | def serve(self, port=5500, liveport=None, host=None, root=None, debug=None,
open_url=False, restart_delay=2, open_url_delay=None,
live_css=True) | Start serve the server with the given port.
:param port: serve on this port, default is 5500
:param liveport: live reload on this port
:param host: serve on this hostname, default is 127.0.0.1
:param root: serve static on this root directory
:param debug: set debug mode, which a... | 3.48 | 3.651794 | 0.952956 |
m = re.search(self.COORD_MATCH, address)
return (m != None) | def already_coords(self, address) | test used to see if we have coordinates or address | 8.761026 | 7.372385 | 1.188357 |
lat, lon = coords.split(',')
return {"lat": lat.strip(), "lon": lon.strip(), "bounds": {}} | def coords_string_parser(self, coords) | Pareses the address string into coordinates to match address_to_coords return object | 6.728547 | 5.677551 | 1.185114 |
base_coords = self.BASE_COORDS[self.region]
get_cord = self.COORD_SERVERS[self.region]
url_options = {
"q": address,
"lang": "eng",
"origin": "livemap",
"lat": base_coords["lat"],
"lon": base_coords["lon"]
}
r... | def address_to_coords(self, address) | Convert address to coordinates | 3.520194 | 3.451403 | 1.019931 |
routing_server = self.ROUTING_SERVERS[self.region]
url_options = {
"from": "x:%s y:%s" % (self.start_coords["lon"], self.start_coords["lat"]),
"to": "x:%s y:%s" % (self.end_coords["lon"], self.end_coords["lat"]),
"at": time_delta,
"returnJSON": ... | def get_route(self, npaths=1, time_delta=0) | Get route data from waze | 3.22644 | 3.228841 | 0.999256 |
start_bounds = self.start_coords['bounds']
end_bounds = self.end_coords['bounds']
def between(target, min, max):
return target > min and target < max
time = 0
distance = 0
for segment in results:
if stop_at_bounds and segment.get('path'... | def _add_up_route(self, results, real_time=True, stop_at_bounds=False) | Calculate route time and distance. | 2.257795 | 2.139793 | 1.055146 |
route = self.get_route(1, time_delta)
results = route['results']
route_time, route_distance = self._add_up_route(results, real_time=real_time, stop_at_bounds=stop_at_bounds)
self.log.info('Time %.2f minutes, distance %.2f km.', route_time, route_distance)
return route_t... | def calc_route_info(self, real_time=True, stop_at_bounds=False, time_delta=0) | Calculate best route info. | 3.471801 | 3.434102 | 1.010978 |
routes = self.get_route(npaths, time_delta)
results = {route['routeName']: self._add_up_route(route['results'], real_time=real_time, stop_at_bounds=stop_at_bounds) for route in routes}
route_time = [route[0] for route in results.values()]
route_distance = [route[1] for route in... | def calc_all_routes_info(self, npaths=3, real_time=True, stop_at_bounds=False, time_delta=0) | Calculate all route infos. | 3.019667 | 3.006786 | 1.004284 |
self._key_prefix = self._config.get('redis', 'key_prefix')
self._job_expire_interval = int(
self._config.get('sharq', 'job_expire_interval')
)
self._default_job_requeue_limit = int(
self._config.get('sharq', 'default_job_requeue_limit')
)
... | def _initialize(self) | Read the SharQ configuration and set appropriate
variables. Open a redis connection pool and load all
the Lua scripts. | 2.326581 | 2.060877 | 1.128927 |
self._config = ConfigParser.SafeConfigParser()
self._config.read(self.config_path) | def _load_config(self) | Read the configuration file and load it into memory. | 3.978996 | 2.746223 | 1.448898 |
# load lua scripts
lua_script_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'scripts/lua'
)
with open(os.path.join(
lua_script_path,
'enqueue.lua'), 'r') as enqueue_file:
self._lua_enqueue_scr... | def _load_lua_scripts(self) | Loads all lua scripts required by SharQ. | 1.365237 | 1.357738 | 1.005523 |
# validate all the input
if not is_valid_interval(interval):
raise BadArgumentException('`interval` has an invalid value.')
if not is_valid_identifier(job_id):
raise BadArgumentException('`job_id` has an invalid value.')
if not is_valid_identifier(queue... | def enqueue(self, payload, interval, job_id,
queue_id, queue_type='default', requeue_limit=None) | Enqueues the job into the specified queue_id
of a particular queue_type | 2.284425 | 2.311676 | 0.988212 |
if not is_valid_identifier(queue_type):
raise BadArgumentException('`queue_type` has an invalid value.')
timestamp = str(generate_epoch())
keys = [
self._key_prefix,
queue_type
]
args = [
timestamp,
self._job_... | def dequeue(self, queue_type='default') | Dequeues a job from any of the ready queues
based on the queue_type. If no job is ready,
returns a failure status. | 3.411391 | 3.341038 | 1.021057 |
if not is_valid_identifier(job_id):
raise BadArgumentException('`job_id` has an invalid value.')
if not is_valid_identifier(queue_id):
raise BadArgumentException('`queue_id` has an invalid value.')
if not is_valid_identifier(queue_type):
raise BadAr... | def finish(self, job_id, queue_id, queue_type='default') | Marks any dequeued job as *completed successfully*.
Any job which gets a finish will be treated as complete
and will be removed from the SharQ. | 2.964988 | 2.905088 | 1.020619 |
# validate all the input
if not is_valid_interval(interval):
raise BadArgumentException('`interval` has an invalid value.')
if not is_valid_identifier(queue_id):
raise BadArgumentException('`queue_id` has an invalid value.')
if not is_valid_identifier(q... | def interval(self, interval, queue_id, queue_type='default') | Updates the interval for a specific queue_id
of a particular queue type. | 3.18264 | 3.229463 | 0.985501 |
timestamp = str(generate_epoch())
# get all queue_types and requeue one by one.
# not recommended to do this entire process
# in lua as it might take long and block other
# enqueues and dequeues.
active_queue_type_list = self._r.smembers(
'%s:active:q... | def requeue(self) | Re-queues any expired job (one which does not get an expire
before the job_expiry_interval) back into their respective queue.
This function has to be run at specified intervals to ensure the
expired jobs are re-queued back. | 6.258825 | 6.170113 | 1.014378 |
if queue_id is None or not is_valid_identifier(queue_id):
raise BadArgumentException('`queue_id` has an invalid value.')
if queue_type is None or not is_valid_identifier(queue_type):
raise BadArgumentException('`queue_type` has an invalid value.')
response = {
... | def clear_queue(self, queue_type=None, queue_id=None, purge_all=False) | clear the all entries in queue with particular queue_id
and queue_type. It takes an optional argument,
purge_all : if True, then it will remove the related resources
from the redis. | 3.183539 | 3.067306 | 1.037894 |
if not isinstance(identifier, basestring):
return False
if len(identifier) > 100 or len(identifier) < 1:
return False
condensed_form = set(list(identifier.lower()))
return condensed_form.issubset(VALID_IDENTIFIER_SET) | def is_valid_identifier(identifier) | Checks if the given identifier is valid or not. A valid
identifier may consists of the following characters with a
maximum length of 100 characters, minimum of 1 character.
Valid characters for an identifier,
- A to Z
- a to z
- 0 to 9
- _ (underscore)
- - (hypen) | 3.50995 | 3.750773 | 0.935794 |
if not isinstance(interval, (int, long)):
return False
if interval <= 0:
return False
return True | def is_valid_interval(interval) | Checks if the given interval is valid. A valid interval
is always a positive, non-zero integer value. | 3.396055 | 2.710551 | 1.252902 |
if not isinstance(requeue_limit, (int, long)):
return False
if requeue_limit <= -2:
return False
return True | def is_valid_requeue_limit(requeue_limit) | Checks if the given requeue limit is valid.
A valid requeue limit is always greater than
or equal to -1. | 3.354657 | 3.180445 | 1.054776 |
parts = re.split('[-_.]', name)
if len(parts) == 1:
return parts
result = set()
for i in range(len(parts) - 1, 0, -1):
for s1 in '-_.':
prefix = s1.join(parts[:i])
for s2 in '-_.':
suffix = s2.join(parts[i:])
for s3 in '-_.':
... | def get_search_names(name) | Return a list of values to search on when we are looking for a package
with the given name.
This is required to search on both pyramid_debugtoolbar and
pyramid-debugtoolbar. | 2.536337 | 2.585189 | 0.981103 |
# We first need to retrieve the body before accessing POST or FILES since
# it can only be read once.
body = request.body
if request.POST or request.FILES:
return
new_body = BytesIO()
# Split the response in the various parts based on the boundary string
content_type, opts = p... | def alter_old_distutils_request(request: WSGIRequest) | Alter the request body for compatibility with older distutils clients
Due to a bug in the Python distutils library, the request post is sent
using \n as a separator instead of the \r\n that the HTTP spec demands.
This breaks the Django form parser and therefore we have to write a
custom parser.
Th... | 2.677828 | 2.598912 | 1.030365 |
instance = kwargs['instance']
if not hasattr(instance.distribution, 'path'):
return
if not os.path.exists(instance.distribution.path):
return
# Check if there are other instances which reference this fle
is_referenced = (
instance.__class__.objects
.filter(dis... | def delete_files(sender, **kwargs) | Signal callback for deleting old files when database item is deleted | 3.437159 | 3.373999 | 1.018719 |
md5 = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
md5.update(data)
return md5.hexdigest() | def md5_hash_file(fh) | Return the md5 hash of the given file-object | 1.533907 | 1.543516 | 0.993774 |
module_path = '.'.join(full_class_path.split('.')[0:-1])
class_name = full_class_path.split('.')[-1]
try:
module = importlib.import_module(module_path)
except ImportError:
raise RuntimeError('Invalid specified Versio schema {}'.format(full_class_path))
try:
return getat... | def get_versio_versioning_scheme(full_class_path) | Return a class based on it's full path | 2.369908 | 2.298516 | 1.03106 |
field_map = {
'name': 'name__icontains',
'summary': 'releases__summary__icontains',
}
query_filter = None
for field, values in spec.items():
for value in values:
if field not in field_map:
continue
field_filter = Q(**{field_map[field... | def search(spec, operator='and') | Implement xmlrpc search command.
This only searches through the mirrored and private packages | 2.358917 | 2.441665 | 0.96611 |
@wraps(view_func, assigned=available_attrs(view_func))
def decorator(request, *args, **kwargs):
if settings.LOCALSHOP_USE_PROXIED_IP:
try:
ip_addr = request.META['HTTP_X_FORWARDED_FOR']
except KeyError:
return HttpResponseForbidden('No permiss... | def credentials_required(view_func) | This decorator should be used with views that need simple authentication
against Django's authentication framework. | 2.583453 | 2.579412 | 1.001567 |
@wraps(function)
def wrapper(self, *args, **kwargs):
key = generate_key(function, *args, **kwargs)
try:
function(self, *args, **kwargs)
finally:
logging.info('Removing key %s', key)
cache.delete(key)
return wrapper | def no_duplicates(function, *args, **kwargs) | Makes sure that no duplicated tasks are enqueued. | 2.911433 | 2.78827 | 1.044172 |
release_file = models.ReleaseFile.objects.get(pk=pk)
logging.info("Downloading %s", release_file.url)
proxies = None
if settings.LOCALSHOP_HTTP_PROXY:
proxies = settings.LOCALSHOP_HTTP_PROXY
response = requests.get(release_file.url, stream=True, proxies=proxies)
# Write the file t... | def download_file(pk) | Download the file reference in `models.ReleaseFile` with the given pk. | 2.712385 | 2.658842 | 1.020138 |
name = post_data.get('name')
version = post_data.get('version')
if settings.LOCALSHOP_VERSIONING_TYPE:
scheme = get_versio_versioning_scheme(settings.LOCALSHOP_VERSIONING_TYPE)
try:
Version(version, scheme=scheme)
except AttributeError:
response = HttpRe... | def handle_register_or_upload(post_data, files, user, repository) | Process a `register` or `upload` comment issued via distutils.
This method is called with the authenticated user. | 3.36594 | 3.412494 | 0.986358 |
from .tasks import download_file
if not settings.LOCALSHOP_ISOLATED:
download_file.delay(pk=self.pk)
else:
download_file(pk=self.pk) | def download(self) | Start a celery task to download the release file from pypi.
If `settings.LOCALSHOP_ISOLATED` is True then download the file
in-process. | 5.902364 | 2.952648 | 1.999007 |
# type: (DataLoader) -> None
# Take the current loader queue, replacing it with an empty queue.
queue = loader._queue
loader._queue = []
# If a maxBatchSize was provided and the queue is longer, then segment the
# queue into multiple batches, otherwise treat the queue as a single batch.
... | def dispatch_queue(loader) | Given the current state of a Loader instance, perform a batch load
from its current queue. | 3.869473 | 3.617272 | 1.069721 |
# type: (DataLoader, Iterable[Loader], Exception) -> None
for l in queue:
loader.clear(l.key)
l.reject(error) | def failed_dispatch(loader, queue, error) | Do not cache individual loads if the entire batch dispatch fails,
but still reject each request so they do not hang. | 7.665972 | 8.738011 | 0.877313 |
# type: (Hashable) -> Promise
if key is None:
raise TypeError(
(
"The loader.load() function must be called with a value,"
+ "but got: {}."
).format(key)
)
cache_key = self.get_cache_key(key... | def load(self, key=None) | Loads a key, returning a `Promise` for the value represented by that key. | 3.98219 | 3.953544 | 1.007246 |
# type: (Iterable[Hashable]) -> Promise
if not isinstance(keys, Iterable):
raise TypeError(
(
"The loader.loadMany() function must be called with Array<key> "
+ "but got: {}."
).format(keys)
)
... | def load_many(self, keys) | Loads multiple keys, promising an array of values
>>> a, b = await my_loader.load_many([ 'a', 'b' ])
This is equivalent to the more verbose:
>>> a, b = await Promise.all([
>>> my_loader.load('a'),
>>> my_loader.load('b')
>>> ]) | 5.39181 | 7.234755 | 0.745265 |
# type: (Hashable) -> DataLoader
cache_key = self.get_cache_key(key)
self._promise_cache.pop(cache_key, None)
return self | def clear(self, key) | Clears the value at `key` from the cache, if it exists. Returns itself for
method chaining. | 6.334344 | 4.909282 | 1.290279 |
# type: (Hashable, Any) -> DataLoader
cache_key = self.get_cache_key(key)
# Only add the key if it does not already exist.
if cache_key not in self._promise_cache:
# Cache a rejected promise if the value is an Error, in order to match
# the behavior of l... | def prime(self, key, value) | Adds the provied key and value to the cache. If the key already exists, no
change is made. Returns itself for method chaining. | 3.930503 | 3.679384 | 1.06825 |
if version is None:
from promise import VERSION
return VERSION
else:
assert len(version) == 5
assert version[3] in ("alpha", "beta", "rc", "final")
return version | def get_complete_version(version=None) | Returns a tuple of the promise version. If version argument is non-empty,
then checks for correctness of the tuple provided. | 5.382838 | 4.596626 | 1.171041 |
# type: (Promise, Optional[List[Union[Dict[str, Optional[Callable]], Tuple[Callable, Callable], Callable]]]) -> None
if not handlers:
return
for handler in handlers:
if isinstance(handler, tuple):
s, f = handler
self.done(s, f)
... | def done_all(self, handlers=None) | :type handlers: list[(Any) -> object] | list[((Any) -> object, (Any) -> object)] | 2.736839 | 2.800417 | 0.977297 |
# type: (Promise, List[Callable]) -> List[Promise]
if not handlers:
return []
promises = [] # type: List[Promise]
for handler in handlers:
if isinstance(handler, tuple):
s, f = handler
promises.append(self.then(s, f))
... | def then_all(self, handlers=None) | Utility function which calls 'then' for each handler provided. Handler can either
be a function in which case it is used as success handler, or a tuple containing
the success and the failure handler, where each of them could be None.
:type handlers: list[(Any) -> object] | list[((Any) -> object,... | 2.399293 | 2.47701 | 0.968624 |
# type: (Dict[Hashable, Promise[S]]) -> Promise[Dict[Hashable, S]]
dict_type = type(m) # type: Type[Dict]
if not m:
return cls.resolve(dict_type())
def handle_success(resolved_values):
# type: (List[S]) -> Dict[Hashable, S]
return dict_type... | def for_dict(cls, m) | A special function that takes a dictionary of promises
and turns them into a promise for a dictionary of values.
In other words, this turns an dictionary of promises for values
into a promise for a dictionary of values. | 3.371915 | 3.239206 | 1.04097 |
# type: (Any) -> bool
_type = obj.__class__
if obj is None or _type in BASE_TYPES:
return False
return (
issubclass(_type, Promise)
or iscoroutine(obj) # type: ignore
or is_future_like(_type)
) | def is_thenable(cls, obj) | A utility function to determine if the specified
object is a promise using "duck typing". | 4.977935 | 5.092927 | 0.977421 |
if ccc.shape[0] == 1:
cc = ccc[0]
else:
cc = ccc
# Code borrowed from obspy.signal.cross_correlation.xcorr_pick_correction
cc_curvature = np.concatenate((np.zeros(1), np.diff(cc, 2), np.zeros(1)))
cc_t = np.arange(0, len(cc) * dt, dt)
peak_index = cc.argmax()
first_sampl... | def _xcorr_interp(ccc, dt) | Intrpolate around the maximum correlation value for sub-sample precision.
:param ccc: Cross-correlation array
:type ccc: numpy.ndarray
:param dt: sample interval
:type dt: float
:return: Position of interpolated maximum in seconds from start of ccc
:rtype: float | 3.004249 | 3.117203 | 0.963764 |
if len(detection_streams) == 0:
return Catalog()
if not cores:
num_cores = cpu_count()
else:
num_cores = cores
if num_cores > len(detection_streams):
num_cores = len(detection_streams)
if parallel:
pool = Pool(processes=num_cores)
debug_print('Mad... | def _day_loop(detection_streams, template, min_cc, detections,
horizontal_chans, vertical_chans, interpolate, cores, parallel,
debug=0) | Function to loop through multiple detections for one template.
Designed to run for the same day of data for I/O simplicity, but as you
are passing stream objects it could run for all the detections ever, as
long as you have the RAM!
:type detection_streams: list
:param detection_streams:
L... | 2.432038 | 2.386458 | 1.019099 |
detect_streams = []
for detection in detections:
if detection.template_name != template[0]:
continue
# Stream to be saved for new detection
detect_stream = []
max_delay = 0
for tr in detect_data:
template_tr = template[1].select(
... | def _prepare_data(detect_data, detections, template, delays,
shift_len, plot) | Prepare data for lag_calc - reduce memory here.
:type detect_data: obspy.core.stream.Stream
:param detect_data: Stream to extract detection streams from.
:type detections: list
:param detections:
List of :class:`eqcorrscan.core.match_filter.Detection` to get
data for.
:type template... | 3.20382 | 2.978208 | 1.075754 |
parameters = []
f = open(filename, 'r')
print('Reading parameters with the following header:')
for line in f:
if line[0] == '#':
print(line.rstrip('\n').lstrip('\n'))
else:
parameter_dict = ast.literal_eval(line)
# convert the dictionary to the cl... | def read_trigger_parameters(filename) | Read the trigger parameters into trigger_parameter classes.
:type filename: str
:param filename: Parameter file
:returns: List of :class:`eqcorrscan.utils.trigger.TriggerParameters`
:rtype: list
.. rubric:: Example
>>> from eqcorrscan.utils.trigger import read_trigger_parameters
>>> para... | 3.10687 | 3.831851 | 0.810802 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.