code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# count all the tile types and name them for readability
counts = {tile_type: 0 for tile_type in base.Tile._all_types}
standard_wildcard_type = '2'
for p, tile in state.board.positions_with_tile():
# count all wildcards as one value
tile_type = tile._type... | def _is_impossible_by_count(self, state) | Disallow any board that has insufficient tile count to solve. | 5.367386 | 5.215793 | 1.029064 |
is_duplicate_board = True # assume same until find a difference
# compare each position
node = self
for p, new_tile in board.positions_with_tile():
found_tile = False # assume no tile in same position until found
for child in node.children:
... | def find_or_graft(self, board) | Build a tree with each level corresponding to a fixed position on
board. A path of tiles is stored for each board. If any two boards
have the same path, then they are the same board. If there is any
difference, a new branch will be created to store that path.
Return: True if board alrea... | 7.007988 | 6.90276 | 1.015244 |
# game
game_image = self._game_image_from_screen('capture')
if game_image is None:
return
# board
board = self._board_from_game_image(game_image)
if board is None:
return
if board.is_empty():
return
return board | def get_capture(self) | Return the capture board or None if can't find it. | 4.230143 | 3.894994 | 1.086046 |
# game
game_image = self._game_image_from_screen('versus')
if game_image is None:
return None, None, None, None # nothing else will work
# board
board = self._board_from_game_image(game_image) # may be None
# safety check. there should be no blanks ... | def get_versus(self) | Return the versus board, player, opponent and extra actions.
Return None for any parts that can't be found. | 4.373188 | 3.557446 | 1.229305 |
# screen
screen_img = self._screen_shot()
# game image
game_rect = self._game_finders[game_type].locate_in(screen_img)
if game_rect is None:
return
t, l, b, r = game_rect
game_img = screen_img[t:b, l:r]
return game_img | def _game_image_from_screen(self, game_type) | Return the image of the given game type from the screen.
Return None if no game is found. | 3.577016 | 3.344997 | 1.069363 |
# board image
board_rect = self._board_tools['board_region'].region_in(game_image)
t, l, b, r = board_rect
board_image = game_image[t:b, l:r]
# board grid and tiles --> fill in a Board object
board = Board()
grid = self._board_tools['grid']
tile_i... | def _board_from_game_image(self, game_image) | Return a board object matching the board in the game image.
Return None if any tiles are not identified. | 4.9041 | 4.505221 | 1.088537 |
HEALTH_MAX = 100
MANA_MAX = 40
# get the set of tools for investigating this actor
tools = {'player': self._player_tools,
'opponent': self._oppnt_tools}[name]
# setup the arguments to be set:
args = [name]
# health:
t, l, b, r =... | def _actor_from_game_image(self, name, game_image) | Return an actor object matching the one in the game image.
Note:
Health and mana are based on measured percentage of a fixed maximum
rather than the actual maximum in the game.
Arguments:
name: must be 'player' or 'opponent'
game_image: opencv image of the main game are... | 3.744901 | 3.559244 | 1.052162 |
proportional = self._bonus_tools['extra_action_region']
# Use ProportionalRegion to isolate the extra actions area
t, l, b, r = proportional.region_in(game_image)
token_region = game_image[t:b, l:r]
# Use TemplateFinder (multiple) to check for extra actions
game_... | def _count_extra_actions(self, game_image) | Count the number of extra actions for player in this turn. | 7.721578 | 7.593761 | 1.016832 |
# basic confirmation of valid arguments
self._argument_gauntlet(root_eot, root)
# setup the starting state
if root:
start_state = root
else:
start_state = State(root_eot.parent.board.copy(),
root_eot.parent.player.c... | def ends_of_one_state(self, root=None, root_eot=None) | Simulate a complete turn from one state only and generate each
end of turn reached in the simulation.
Arguments:
Exactly one of:
root: a start state with no parent
or
root_eot: an EOT or ManaDrain transition in the simulation | 5.230191 | 4.793666 | 1.091063 |
# simple confirmation that the root is actually a root.
# otherwise it may seem to work but would be totally out of spec
if root.parent:
raise ValueError('Unexpectedly received a node with a parent for'
' root:\n{}'.format(root))
# build ... | def ends_of_next_whole_turn(self, root) | Simulate one complete turn to completion and generate each end of
turn reached during the simulation.
Note on mana drain:
Generates but does not continue simulation of mana drains.
Arguments:
root: a start state with no parent | 8.457305 | 7.637367 | 1.107359 |
# simple confirmation that the root is actually a root.
# otherwise it may seem to work but would be totally out of spec
if root.parent:
raise ValueError('Unexpectedly received a node with a parent for'
' root:\n{}'.format(root))
# run a ... | def all_ends_of_turn(self, root) | Simulate the root and continue generating ends of turn until
everything has reached mana drain.
Warning on random fill:
If random fill is used together with this method, it will generate
basically forever due to the huge number of possibilities it
introduces.
Arguments:... | 7.203487 | 5.938931 | 1.212927 |
while potential_chain:
# hook for capture game optimizations. no effect in base
# warning: only do this ONCE for any given state or it will
# always filter the second time
if self._disallow_state(potential_chain):
potential_chain.graft_chi... | def _simulated_chain_result(self, potential_chain, already_used_bonus) | Simulate any chain reactions.
Arguments:
potential_chain: a state to be tested for chain reactions
already_used_bonus: boolean indicating whether a bonus turn was already
applied during this action
Return: final result state or None (if state is filtered out in capture)
... | 7.661951 | 7.353114 | 1.042001 |
# determine if this is a manadrain or just end of turn
is_manadrain = True # default mana drain until valid swap found
for swap_pair in state.board.potential_swaps():
result_board, destroyed_groups = \
state.board.execute_once(swap=swap_pair,
... | def _simulated_EOT(self, state) | Simulate a normal or mana drain EOT and return it. | 9.64222 | 8.66328 | 1.112999 |
# clear all mana
mana_drain_state.player.apply_mana_drain()
mana_drain_state.opponent.apply_mana_drain()
# force change of turn
mana_drain_state.actions_remaining = 0
# randomize the board if this game uses random fill
if self.random_fill:
ran... | def _simulated_mana_drain(self, mana_drain_state) | Apply mana drain effects to this state, attach a mana drain EOT
and return the mana drain EOT. | 5.216633 | 4.074225 | 1.280399 |
board = cls()
board._random_fill()
destructions = True # prime the loop
while destructions:
board, destructions = board.execute_once()
board._random_fill()
return board | def random_start_board(cls) | Produce a full, stable start board with random tiles. | 10.504736 | 8.874775 | 1.183662 |
bcopy = self.copy() # work with a copy, not self
total_destroyed_tile_groups = list()
# swap if any
bcopy._swap(swap)
# spell changes if any
bcopy._change(spell_changes)
# spell destructions and record if any
# first convert simple positions to g... | def execute_once(self, swap=None,
spell_changes=None, spell_destructions=None,
random_fill=False) | Execute the board only one time. Do not execute chain reactions.
Arguments:
swap - pair of adjacent positions
spell_changes - sequence of (position, tile) changes
spell_destructions - sequence of positions to be destroyed
Return: (copy of the board, destroyed tile groups) | 3.986187 | 3.452725 | 1.154505 |
if swap is None:
return
p1, p2 = swap
square_distance = abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
if square_distance != 1:
raise ValueError('Positions unexpectedly not adjacent: square'
' distance between {} and {} is'
... | def _swap(self, swap) | Simulate swapping as in PQ.
swap should be a sequence of two positions with a square distance of
exactly 1.
Non-adjacent swaps cause a ValueError. | 3.425904 | 2.823706 | 1.213265 |
if changes is None:
return
for position, new_tile in changes:
self._array[position] = new_tile | def _change(self, changes) | Apply the given changes to the board.
changes: sequence of (position, new tile) pairs or None | 6.659726 | 3.797513 | 1.753707 |
#disable optimized matching
optimized_rows = None
optimized_columns = None
for match in self.__match_rows(optimized_rows):
#match in rows
yield match
for match in self.__match_rows(optimized_columns,
transpos... | def _match(self) | Find all matches and generate a position group for each match. | 8.457895 | 8.20693 | 1.03058 |
MIN_LENGTH = 3
a = self._array
if transpose:
a = a.T
rows = optimized_lines or range(8)
# check for matches in each row separately
for row in rows:
NUM_COLUMNS = 8
match_length = 1
start_position = 0 # next tile po... | def __match_rows(self, optimized_lines=None, transpose=False) | Main functionality of _match, but works only on rows.
Full matches are found by running this once with original board and
once with a transposed board.
Arguments:
optimized_lines is an optional argument that identifies the lines
that need to be matched.
transpose indica... | 4.413443 | 4.425618 | 0.997249 |
target_position_groups = list(target_position_groups) # work on a copy
destroyed_tile_groups = list()
blank = Tile.singleton('.')
a = self._array
while target_position_groups: # continue as long as more targets exist
# delay actual clearing of destroyed til... | def _destroy(self, target_position_groups) | Destroy indicated position groups, handle any chain destructions,
and return all destroyed groups. | 4.272902 | 4.161289 | 1.026822 |
#get the boundaries of the explosion
sb_row, sb_col = position
left = max(sb_row - 1, 0) # standard radius or 0 if out of bounds
right = min(sb_row + 1, 7) # standard radius or 7 if out of bounds
top = max(sb_col - 1, 0)
bottom = min(sb_col + 1, 7)
for ... | def __skullbomb_radius(self, position) | Generate all valid positions in the square around position. | 2.829614 | 2.646566 | 1.069164 |
a = self._array
for column in [a[:, c] for c in range(a.shape[1])]:
# find blanks and fill them with tiles above them
target_p = column.shape[0] - 1 # start at the bottom
fall_distance = 1 # increases every time a new gap is found
while target_p... | def _fall(self) | Cause tiles to fall down to fill blanks below them. | 4.404441 | 3.909805 | 1.126512 |
a = self._array
for p, tile in self.positions_with_tile():
if tile.is_blank():
a[p] = Tile.random_tile() | def _random_fill(self) | Fill the board with random tiles based on the Tile class. | 9.755491 | 7.104955 | 1.373055 |
a = self._array
rows, cols = a.shape
for this_position, tile in self.positions_with_tile():
#produce horizontal swap for this position
r, c = this_position
if c < cols - 1:
other_position = (r, c + 1)
if self._swap_opti... | def potential_swaps(self) | Generate a sequence of at least all valid swaps for this board.
The built-in optimizer filters out many meaningless swaps, but not all. | 3.830738 | 3.607977 | 1.061741 |
# setup local shortcuts
a = self._array
tile1 = a[p1]
tile2 = a[p2]
# 1) disallow same tiles
if tile1 == tile2:
return False
# 2) disallow matches unless a wildcard is involved
if tile1.matches(tile2) and not any(t.is_wildcard()
... | def _swap_optimizer_allows(self, p1, p2) | Identify easily discarded meaningless swaps.
This is motivated by the cost of millions of swaps being simulated. | 3.511749 | 3.475667 | 1.010381 |
for p, tile in numpy.ndenumerate(self._array):
yield p, tile | def positions_with_tile(self) | Generate all positions and tiles as tuples of (row,col), tile.
docstring to make my IDE stop assuming tile is a standard dtype. sorry!
:rtype : tuple | 11.432076 | 9.413426 | 1.214444 |
health = self.health, self.health_max
r = self.r, self.r_max
g = self.g, self.g_max
b = self.b, self.b_max
y = self.y, self.y_max
x = self.x, self.x_max
m = self.m, self.m_max
h = self.h, self.h_max
c = self.c, self.c_max
return se... | def copy(self) | Return a copy of this actor with the same attribute values. | 2.063317 | 1.971108 | 1.04678 |
self.r = self.g = self.b = self.y = 0 | def apply_mana_drain(self) | Clear current mana values. | 9.991381 | 6.990858 | 1.429207 |
self_increase_types = ('r', 'g', 'b', 'y', 'x', 'm', 'h', 'c')
attack_types = ('s', '*')
total_attack = 0
for tile_group in tile_groups:
group_type = None
type_count = 0
type_multiplier = 1
for tile in tile_group:
#... | def apply_tile_groups(self, tile_groups) | Increase mana, xp, money, anvils and scrolls based on tile groups. | 4.185295 | 4.134244 | 1.012348 |
if ignore_list is None:
ignore_list = []
if debug:
print('copytree {} to {}'.format(src, dst))
for child in Path(src).iterdir():
if debug:
print(" on file {}".format(child))
if child.name not in ignore_list:
if child.is_dir():
new... | def copytree(src, dst, overwrite=False, ignore_list=None, debug=False) | Copy a tree of files over.
Ignores a file if it already exists at the destination. | 1.962374 | 1.976834 | 0.992686 |
requirements = []
for line in read(*parts).splitlines():
new_line = re.sub(r'(\s*)?#.*$', # the space immediately before the
# hash mark, the hash mark, and
# anything that follows it
'', ... | def read_requirements(*parts) | Given a requirements.txt (or similar style file), returns a list of requirements.
Assumes anything after a single '#' on a line is a comment, and ignores
empty lines. | 6.006459 | 5.818087 | 1.032377 |
if path.startswith("http"):
if headers:
request = Request(url=path, headers=headers)
else:
request = Request(url=path, headers={})
fp = urlopen(request) # 打开在线PDF文档
else:
fp = open(path, 'rb')
parser = PDFParser(fp)
doc = PDFDocument()
p... | def pdf2text(path, password="", headers=None) | 从pdf文件中提取文本
:param path: str
pdf文件在本地的地址或者url地址
:param password: str
pdf文件的打开密码,默认为空
:param headers: dict
请求url所需要的 header,默认值为 None
:return: text | 2.021478 | 2.026909 | 0.99732 |
merger = PyPDF2.PdfFileMerger()
for file in pdf_files:
f = open(file, 'rb')
file_rd = PyPDF2.PdfFileReader(f)
# use file name as bookmark
bookmark = os.path.basename(os.path.splitext(file)[0])
if file_rd.isEncrypted:
print('%s is encrypted, not supported!... | def merge_pdf(pdf_files, output_file) | 合并多个pdf文件
:param pdf_files: list
需要合并的pdf文件列表
:param output_file: str
合并后的pdf文件路径 | 2.591506 | 2.684211 | 0.965463 |
if timeout is not None:
endtime = time.time() + timeout
me = threading.currentThread()
self.__condition.acquire()
try:
if self.__writer is me:
self.__writer_lock_count += 1
return True
while True:
... | def acquire_read(self, timeout=None) | Acquire a read lock for the current thread, waiting at most
timeout seconds or doing a non-blocking check in case timeout
is <= 0.
In case timeout is None, the call to acquire_read blocks until
the lock request can be serviced.
If the lock has been successfully acquired, this f... | 3.855267 | 3.892443 | 0.990449 |
if timeout is not None:
endtime = time.time() + timeout
me = threading.currentThread()
self.__condition.acquire()
try:
if self.__writer is me:
self.__writer_lock_count += 1
return True
if me in self.__readers:
... | def acquire_write(self, timeout=None) | Acquire a write lock for the current thread, waiting at most
timeout seconds or doing a non-blocking check in case timeout
is <= 0.
In case timeout is None, the call to acquire_write blocks until
the lock request can be serviced.
If the lock has been successfully acquired, this... | 2.76115 | 2.641781 | 1.045185 |
me = threading.currentThread()
self.__condition.acquire()
try:
if self.__writer is me:
self.__writer_lock_count -= 1
if self.__writer_lock_count == 0:
self.__writer = None
self.__condition.notifyAll()
... | def release(self) | Release the currently held lock.
In case the current thread holds no lock, a thread.error
is thrown. | 2.521031 | 2.271753 | 1.109729 |
me = threading.currentThread()
self.lock.acquire()
try:
if elt not in self.locked:
self.locked[elt] = [me, 1]
return True
elif self.locked[elt][0] == me:
self.locked[elt][1] += 1
return True
... | def try_acquire(self, elt) | elt must be hashable.
If not yet locked, elt is captured for the current thread and
True is returned.
If already locked by the current thread its recursive counter
is incremented and True is returned.
If already locked by another thread False is returned. | 2.309114 | 2.283918 | 1.011032 |
self.lock.acquire()
try:
if elt not in self.locked:
raise thread.error, "release unlocked lock for %s" % `elt`
self.locked[elt][1] -= 1
if not self.locked[elt][1]:
del self.locked[elt]
finally:
self.lock.rel... | def release(self, elt) | elt must be already locked (if it is not a thread.error
exception will be raised)
The recursive counter for elt is decremented and when it
reaches zero the lock is released. | 3.047672 | 2.610014 | 1.167684 |
return self._component.get(key, raw=raw, fallback=fallback) | def get(self, key, raw=False, fallback=None) | Get a string value from the componnet.
Arguments:
key - the key to retrieve
raw - Control whether the value is interpolated or returned raw. By
default, values are interpolated.
fallback - The return value if key isn't in the component. | 5.719428 | 6.088155 | 0.939435 |
fallback = fallback or []
raw = self.get(key, None)
if raw:
return [value.strip() for value in raw.split(split)]
return fallback | def get_list(self, key, fallback=None, split=",") | Retrieve a value in list form.
The interpolated value will be split on some key (by default, ',') and
the resulting list will be returned.
Arguments:
key - the key to return
fallback - The result to return if key isn't in the component. By
default, this will... | 3.166574 | 6.178828 | 0.512488 |
if self._component.get(key, raw=True) != value:
self._component[key] = value
self._main_config.dirty = True | def set(self, key, value) | Set a value in the component.
Arguments:
key - the key to set
value - the new value | 6.767004 | 8.052267 | 0.840385 |
if self.dirty:
with open(self._cache_path, "w") as output_file:
self._config.write(output_file) | def write(self) | Write the configuration. | 4.873643 | 4.33132 | 1.12521 |
'''
Return list of spec files. `args` may be filenames which are passed right
through, or directories in which case they are searched recursively for
*._spec.py
'''
files_or_dirs = args or ['.']
filenames = []
for f in files_or_dirs:
if path.isdir(f):
filenames.extend... | def find_files(args) | Return list of spec files. `args` may be filenames which are passed right
through, or directories in which case they are searched recursively for
*._spec.py | 4.53418 | 2.281886 | 1.987032 |
if COOKIE_KEY in request.COOKIES and \
request.COOKIES[COOKIE_KEY] == COOKIE_SPAM:
# Is a known spammer.
response = HttpResponse("")
# We do not reveal why it has been forbbiden:
response.status_code = 404
... | def process_request(self, request) | Discovers if a request is from a knwon spam bot and denies access. | 4.743837 | 4.607539 | 1.029582 |
if COOKIE_KEY not in request.COOKIES:
# Unknown user, set cookie and go on...
response.set_cookie(COOKIE_KEY, COOKIE_PASS, httponly=True,
expires=datetime.now()+timedelta(days=30))
# Only logged if we have to set the PASS cookie
... | def process_response(self, request, response) | Sets "Ok" cookie on unknown users. | 7.801418 | 7.096912 | 1.099269 |
version_file = os.path.join("paps_settings", "__init__.py")
initfile_lines = open(version_file, 'rt').readlines()
version_reg = r"^__version__ = ['\"]([^'\"]*)['\"]"
for line in initfile_lines:
mo = re.search(version_reg, line, re.M)
if mo:
return mo.group(1)
raise R... | def get_version() | Parse the version information from the init file | 2.019172 | 1.92458 | 1.049149 |
puri = urisup.uri_help_split(uri)
params = __dict_from_query(puri[QUERY])
if puri[AUTHORITY]:
user, passwd, host, port = puri[AUTHORITY]
if user:
params['user'] = user
if passwd:
params['passwd'] = passwd
if host:
params['host'] = host... | def connect_by_uri(uri) | General URI syntax:
mysql://user:passwd@host:port/db?opt1=val1&opt2=val2&...
where opt_n is in the list of options supported by MySQLdb:
host,user,passwd,db,compress,connect_timeout,read_default_file,
read_default_group,unix_socket,port
NOTE: the authority and the path parts of the URI h... | 6.376189 | 6.314671 | 1.009742 |
return string and ' '.join(word[0].upper() + word[1:]
for word in (string.split() if cleanse else string.split(' '))) | def inicap_string(string,
cleanse=False) | Convert the first letter of each word to capital letter without
touching the rest of the word.
@param string: a string.
@param cleanse: ``True`` to remove any separator character from the
string, such as comma; ``False`` to keeps any character but space.
@return: a string for which the first ... | 3.865633 | 4.980528 | 0.776149 |
return string and isinstance(string, base_string) \
and REGEX_PATTERN_EMAIL_ADDRESS.match(string.strip().lower()) | def is_email_address(string) | Check whether the specified string corresponds to an email address.
@param string: a string that is expected to be an email address.
@return: ``True`` if the string corresponds to an email address,
``False`` otherwise. | 5.529682 | 10.795295 | 0.512231 |
# Convert the string to ASCII lower characters.
ascii_string = unidecode.unidecode(string).lower()
# Replace any punctuation character with space.
punctuationless_string = re.sub(r, ' ', ascii_string)
# Remove any double space character.
cleansed_string = re.sub(r'\s{2,}', ' ', punctuatio... | def string_to_keywords(string,
keyword_minimal_length=1) | Remove any punctuation character from the specified list of keywords,
remove any double or more space character and represent Unicode
characters in ASCII.
@param keywords: a list of keywords strip out any punctuation characters.
@param keyword_minimal_length: minimal number of characters of the
... | 3.657066 | 3.59427 | 1.017471 |
''' Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page.
'''
previews = []
if sketch.is_sketchfile(src_path):
previews = sketch.preview(src_path)
if not previews:
previews = quicklook.preview(src_path)
previews = [safely_decode(preview) ... | def preview(src_path) | Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page. | 5.299692 | 3.484544 | 1.520914 |
if obj.__class__ == Section:
return reverse('section_view', kwargs={'full_slug': obj.full_slug})
if obj.__class__ == Article:
return reverse('article_detail', kwargs={'slug': obj.slug}) | def get_url_for_model(obj) | The get_url_for_model function is necessary because Armstrong has no
preconceptions about what your url schema actually looks like.
get_url_for_model is called whenever a BaseContent subclass has it's
get_absolute_url function calle_url_for_model is called whenever a
BaseContent subclass has it's get_ab... | 3.298604 | 3.289325 | 1.002821 |
self._call_helper("Checking out", self.real.checkout, *args, **kwargs) | def checkout(self, *args, **kwargs) | This function checks out source code. | 12.569267 | 10.79634 | 1.164216 |
self._call_helper("Updating", self.real.update, *args, **kwargs) | def update(self, *args, **kwargs) | This funcion updates a checkout of source code. | 17.007074 | 14.747783 | 1.153195 |
layer = 0
expected_count = len(tasks)
counts = {}
def _add_layer(resolved, dep_fn):
nonlocal layer
nonlocal counts
nonlocal expected_count
really_resolved = []
for resolved_task in resolved:
resolved_component_tasks = counts.get(resolved_task[0]... | def _print_layers(targets, components, tasks) | Print dependency information, grouping components based on their position
in the dependency graph. Components with no dependnecies will be in layer
0, components that only depend on layer 0 will be in layer 1, and so on.
If there's a circular dependency, those nodes and their dependencies will
be colo... | 3.241319 | 3.525023 | 0.919517 |
indentation = " " * 4
_do_dot(
targets,
components,
tasks,
lambda resolved, dep_fn: dep_fn(indentation, resolved),
) | def _print_graph(targets, components, tasks) | Print dependency information using a dot directed graph. The graph will
contain explicitly requested targets plus any dependencies.
If there's a circular dependency, those nodes and their dependencies will
be colored red.
Arguments
targets - the targets explicitly requested
components - full ... | 11.821945 | 16.546545 | 0.714466 |
print("Warning: dot option is deprecated. Use graph instead.", file=sys.stderr)
_print_graph(targets, components, tasks) | def _print_dot(targets, components, tasks) | Deprecated function; use print_graph.
Arguments
targets - the targets explicitly requested
components - full configuration for all components in a project | 5.768356 | 7.86844 | 0.7331 |
selection = self.get_selection()
if selection.get_mode() != gtk.SELECTION_SINGLE:
raise AttributeError('selected_item not valid for select_multiple')
model, selected = selection.get_selected()
if selected is not None:
return self._object_at_sort_iter(sele... | def _get_selected_item(self) | The currently selected item | 5.935935 | 5.445328 | 1.090097 |
selection = self.get_selection()
if selection.get_mode() != gtk.SELECTION_MULTIPLE:
raise AttributeError('selected_items only valid for '
'select_multiple')
model, selected_paths = selection.get_selected_rows()
result = []
for... | def _get_selected_items(self) | List of currently selected items | 3.237393 | 3.047708 | 1.062239 |
selection = self.get_selection()
if selection.get_mode() != gtk.SELECTION_MULTIPLE:
raise AttributeError('selected_ids only valid for select_multiple')
model, selected_paths = selection.get_selected_rows()
if selected_paths:
return zip(*selected_paths)[0]... | def _get_selected_ids(self) | List of currently selected ids | 4.085072 | 3.775162 | 1.082092 |
self.model.set(self._iter_for(item), 0, item) | def update(self, item) | Manually update an item's display in the list
:param item: The item to be updated. | 13.094708 | 15.457865 | 0.847123 |
next_iter = self._next_iter_for(item)
if next_iter is not None:
self.model.swap(self._iter_for(item), next_iter) | def move_item_down(self, item) | Move an item down in the list.
Essentially swap it with the item below it.
:param item: The item to be moved. | 4.900121 | 5.564314 | 0.880633 |
prev_iter = self._prev_iter_for(item)
if prev_iter is not None:
self.model.swap(prev_iter, self._iter_for(item)) | def move_item_up(self, item) | Move an item up in the list.
Essentially swap it with the item above it.
:param item: The item to be moved. | 4.777822 | 5.564364 | 0.858647 |
next_iter = self._next_iter_for(item)
if next_iter is not None:
return self._object_at_iter(next_iter) | def item_after(self, item) | The item after an item | 4.626018 | 4.429788 | 1.044298 |
prev_iter = self._prev_iter_for(item)
if prev_iter is not None:
return self._object_at_iter(prev_iter) | def item_before(self, item) | The item before an item
:param item: The item to get the previous item relative to | 4.829391 | 6.502968 | 0.742644 |
self.model_filter.set_visible_func(
self._internal_visible_func,
visible_func,
)
self._visible_func = visible_func
self.model_filter.refilter() | def set_visible_func(self, visible_func) | Set the function to decide visibility of an item
:param visible_func: A callable that returns a boolean result to
decide if an item should be visible, for
example::
def is_visible(item):
... | 5.02422 | 5.906032 | 0.850693 |
# work out the direction
if direction in ('+', 'asc', gtk.SORT_ASCENDING):
direction = gtk.SORT_ASCENDING
elif direction in ('-', 'desc', gtk.SORT_DESCENDING):
direction = gtk.SORT_DESCENDING
else:
raise AttributeError('unrecognised direction'... | def sort_by(self, attr_or_key, direction='asc') | Sort the view by an attribute or key
:param attr_or_key: The attribute or key to sort by
:param direction: Either `asc` or `desc` indicating the direction of
sorting | 2.740371 | 2.994739 | 0.915062 |
if item not in self:
raise ValueError('objectlist.remove(item) failed, item not in list')
item_id = int(self._view_path_for(item))
giter = self._iter_for(item)
del self[giter]
self.emit('item-removed', item, item_id) | def remove(self, item) | Remove an item from the list
:param item: The item to remove from the list.
:raises ValueError: If the item is not present in the list. | 6.837307 | 7.168089 | 0.953854 |
if item in self:
raise ValueError("item %s already in list" % item)
modeliter = self.model.insert(position, (item,))
self._id_to_iter[id(item)] = modeliter
if select:
self.selected_item = item
self.emit('item-inserted', item, position) | def insert(self, position, item, select=False) | Insert an item at the specified position in the list.
:param position: The position to insert the item at
:param item: The item to be added
:param select: Whether the item should be selected after adding | 3.751582 | 4.934896 | 0.760215 |
if item in self:
raise ValueError("item %s already in list" % item)
modeliter = self.model.append((item,))
self._id_to_iter[id(item)] = modeliter
if select:
self.selected_item = item
self.emit('item-added', item) | def append(self, item, select=False) | Add an item to the end of the list.
:param item: The item to be added
:param select: Whether the item should be selected after adding | 4.289866 | 5.225883 | 0.820888 |
if item in self:
raise ValueError("item %s already in list" % item)
if parent is not None:
giter = self._iter_for(parent)
else:
giter = None
modeliter = self.model.append(giter, (item,))
self._id_to_iter[id(item)] = modeliter
i... | def append(self, item, parent=None, select=False) | Add an item to the end of the list.
:param item: The item to be added
:param parent: The parent item to add this as a child of, or None for
a top-level node
:param select: Whether the item should be selected after adding | 4.067939 | 4.891744 | 0.831593 |
for item in iter:
self.append(item, parent) | def extend(self, iter, parent=None) | Add a sequence of items to the end of the list
:param iter: The iterable of items to add.
:param parent: The node to add the items as a child of, or None for
top-level nodes. | 5.189296 | 7.300693 | 0.710795 |
self.expand_row(self._view_path_for(item), open_all) | def expand_item(self, item, open_all=True) | Display a node as expanded
:param item: The item to show expanded
:param open_all: Whether all child nodes should be recursively
expanded. | 12.846789 | 16.754877 | 0.766749 |
if item not in self:
raise ValueError('objectlist.remove(item) failed, item not in list')
item_path = self._view_path_for(item)
giter = self._iter_for(item)
del self[giter]
self.emit('item-removed', item, item_path) | def remove(self, item) | Remove an item from the list
:param item: The item to remove from the list.
:raises ValueError: If the item is not present in the list. | 6.010479 | 6.361125 | 0.944877 |
# def jsonify_ex(obj, trimmable=False):
# if obj is None:
# return None
# elif isinstance(obj, (basestring, bool, int, long, float, complex)):
# return obj
# elif isinstance(obj, (list, set, tuple)):
# return [jsonify_ex(item, trimmable=trimmable) for... | def jsonify(obj, trimmable=False) | Serialize an object to a JSON formatted string.
@param obj: an instance to convert to a JSON formatted string.
@param trimmable: indicate whether null attributes of this object
need to be stripped out the JSON formatted string.
@return: a JSON formatted string. | 1.980644 | 1.979366 | 1.000646 |
if obj is None:
return None
elif isinstance(obj, (basestring, bool, int, long, float, complex)):
return obj
elif isinstance(obj, (list, set, tuple)):
return [stringify(item, trimmable=trimmable) for item in obj]
elif isinstance(obj, dict):
return dict([(unicode(key),... | def stringify(obj, trimmable=False) | Convert an object to a stringified version of this object where the
initial object's attribute values have been stringified when these
values are not native Python types.
This function differs from the standard Python ``str`` as the latter
returns a string version of object, while this function returns... | 2.027466 | 2.062838 | 0.982853 |
shallow_object = copy.copy(obj)
shallow_object.__dict__ = {}
for attribute_name in attribute_names:
try:
setattr(shallow_object, attribute_name, getattr(obj, attribute_name))
except KeyError, error:
if not ignore_missing_attributes:
raise error
... | def shallow_copy(obj, attribute_names,
ignore_missing_attributes=True) | Return a shallow copy of the given object, including only the
specified attributes of this object.
@param obj: an object to copy.
@param attribute_names: a list of names of the attributes to copy.
@param ignore_missing_attributes: ``False`` indicates that the function
can ignore attributes t... | 1.962414 | 3.077614 | 0.637641 |
if payload is None:
return None
if isinstance(payload, dict):
return Object(**dict([(k, v if not isinstance(v, (dict, list)) else Object.from_json(v))
for (k, v) in payload.iteritems()]))
elif isinstance(payload, list):
return pa... | def from_json(payload) | Build an object from a JSON dictionary.
@param payload: a JSON dictionary which key/value pairs represent
the members of the Python object to build, or ``None``.
@return: an instance ``Object`` with members built from the key/value
pairs of the given JSON dictionary, or ``Non... | 3.422224 | 2.798191 | 1.223013 |
try:
proxies = {
'http': 'http://%s:%s' % (host, port),
'https': 'https://%s:%s' % (host, port)
}
requests.get('http://www.baidu.com/', proxies=proxies, timeout=timeout)
except HTTPError:
print('failed: ', host, port)
return False
else:
... | def is_usable(host, port, timeout=3) | 测试代理是否可用
params
----------
host ip地址
port 端口号
timeout 默认值为3,通过设置这个参数可以过滤掉一些速度慢的代理
example
----------
is_usable('222.180.24.13', '808', timeout=3) | 2.004579 | 1.94948 | 1.028263 |
# Tests for cookie:
if settings.COOKIE_KEY not in request.COOKIES \
and (settings.DISCARD_SPAM or settings.DISCARD_NO_COOKIE):
return False
elif settings.COOKIE_KEY not in request.COOKIES:
comment.is_removed = True
comment.is_public = ... | def allow(self, comment, content_object, request) | Tests comment post requests for the djangospam cookie. | 5.891062 | 5.052642 | 1.165937 |
cast_callback = self.cast_callback if self.cast_callback else self.cast_type
try:
return value if isinstance(value, self.cast_type) else cast_callback(value)
except Exception:
raise NodeTypeError('Invalid value `{}` for {}.'.format(value, self.cast_type)) | def validate(self, value) | Base validation method. Check if type is valid, or try brute casting.
Args:
value (object): A value for validation.
Returns:
Base_type instance.
Raises:
SchemaError, if validation or type casting fails. | 4.475558 | 4.790751 | 0.934208 |
# Postgresql / MySQL drivers change the format on 'TIMESTAMP' columns;
if 'T' in value:
value = value.replace('T', ' ')
return datetime.strptime(value.split('.')[0], '%Y-%m-%d %H:%M:%S') | def cast_callback(value) | Override `cast_callback` method. | 7.653247 | 7.346521 | 1.041751 |
global na3x_cfg
with open(cfg[NA3X_DB]) as db_cfg_file:
na3x_cfg[NA3X_DB] = json.load(db_cfg_file, strict=False)
with open(cfg[NA3X_TRIGGERS]) as triggers_cfg_file:
na3x_cfg[NA3X_TRIGGERS] = json.load(triggers_cfg_file, strict=False)
with open(cfg[NA3X_ENV]) as env_cfg_file:
... | def init(cfg) | Initialiaze na3x
:param cfg: db, triggers, environment variables configuration | 2.21675 | 1.733988 | 1.278411 |
if os.path.exists(cache_dir):
files = os.listdir(cache_dir)
if cache_file in files:
return True
return not bool(files)
return True | def _is_cache_dir_appropriate(cache_dir, cache_file) | Determine if a directory is acceptable for building.
A directory is suitable if any of the following are true:
- it doesn't exist
- it is empty
- it contains an existing build cache | 3.383273 | 3.525221 | 0.959734 |
config = _create_cache(raw_path, cache_dir, cache_file)
for modifier in _CONFIG_MODIFIERS:
modifier(config, **kwargs)
# pylint: disable=protected-access
cache = devpipeline_configure.cache._CachedConfig(
config, os.path.join(cache_dir, cache_file)
)
_handle_value_modifiers(c... | def process_config(raw_path, cache_dir, cache_file, **kwargs) | Read a build configuration and create it, storing the result in a build
cache.
Arguments
raw_path -- path to a build configuration
cache_dir -- the directory where cache should be written
cache_file -- The filename to write the cache. This will live inside
cache_dir.
**kwargs... | 4.682023 | 4.917617 | 0.952092 |
for k in kwargs:
assert k in self._keys, 'Invalid key: %s' % k
d = self.values()
d.update(kwargs)
return self.__class__(**d) | def copy(self, **kwargs) | :param kwargs:
:return: copy of this object modifying the kwargs | 3.876382 | 3.876423 | 0.99999 |
return dict((k, getattr(self, k)) for k in self._keys) | def values(self) | :return: key-value dict : { string: any } | 5.902503 | 3.776161 | 1.563096 |
urls = super(IPAdmin, self).get_urls()
my_urls = patterns(
'',
url(r'^batch_process_ips/$', self.admin_site.admin_view(self.batch_process_ips_view), name='batch_process_ips_view')
)
return my_urls + urls | def get_urls(self) | Returns the urls for the model. | 2.750276 | 2.622158 | 1.048859 |
phase = unwrap.unwrap_phase(np.angle(field), seed=47)
samples = []
samples.append(phase[:, :3].flatten())
samples.append(phase[:, -3:].flatten())
samples.append(phase[:3, 3:-3].flatten())
samples.append(phase[-3:, 3:-3].flatten())
pha_offset = np.median(np.hstack(samples))
num_2pi =... | def field2ap_corr(field) | Determine amplitude and offset-corrected phase from a field
The phase jumps sometimes appear after phase unwrapping.
Parameters
----------
field: 2d complex np.ndarray
Complex input field
Returns
-------
amp: 2d real np.ndarray
Amplitude data
pha: 2d real np.ndarray
... | 3.966939 | 3.849851 | 1.030414 |
# simulation parameters
radius_um = radius * 1e6 # radius of sphere in um
propd_um = radius_um # simulate propagation through full sphere
propd_lamd = radius / wavelength # radius in wavelengths
wave_nm = wavelength * 1e9
# Qpsphere models define the position of the sphere with an index ... | def mie(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5), focus=0, arp=True) | Mie-simulated field behind a dielectric sphere
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index: float
Refractive index of the sphere
medium_index: float
Refractive index of the surrounding medium
wavelength: float
Vacuum wavelength of th... | 5.660809 | 5.274608 | 1.073219 |
return Popen(
command,
stdout=PIPE,
stderr=STDOUT,
start_new_session=True
) | def execute_command(cls, command) | :return: Popen object with stderr redirected to stdout | 4.171213 | 3.053195 | 1.36618 |
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)
return next(six.iteritems(d)) | def get_single_item(d) | Get an item from a dict which contains just one item. | 4.942065 | 4.024574 | 1.227972 |
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)
return next(six.iterkeys(d)) | def get_single_key(d) | Get a key from a dict which contains just one item. | 4.899115 | 3.952958 | 1.239354 |
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)
return next(six.itervalues(d)) | def get_single_value(d) | Get a value from a dict which contains just one item. | 4.940285 | 4.04686 | 1.22077 |
# don't use collections.OrderedDict because we do support Python 2.6
seen = set()
return [x for x in xs if x not in seen and not seen.add(x)] | def distinct(xs) | Get the list of distinct values with preserving order. | 4.589701 | 4.659538 | 0.985012 |
# type: () -> None
for i in vars(self):
if i.startswith("_"):
continue
val = self.__get(i, return_type=type(getattr(self, i)))
if val is not None:
setattr(self, i, val) | def configure(self) | Configures object based on its initialization | 4.317954 | 4.346091 | 0.993526 |
logger.info('UpdateLocationsIfNecessaryTask was called')
# read last ip count
try:
with open(app_settings.IP_ASSEMBLER_IP_CHANGED_FILE, 'r') as f:
content_list = f.readlines()
if len(content_list) == 0:
ip_count_old = -1
... | def run(self, **kwargs) | Does the magic! | 2.769562 | 2.735428 | 1.012478 |
try:
# connect to server and login
box = imaplib.IMAP4_SSL(settings.IMAP_SERVER)
box.login(settings.IMAP_USERNAME, settings.IMAP_PASSWORD)
box.select()
# search for all mails in the mailbox
result, mail_indices = box.search(None, ... | def run(self, **kwargs) | Checks the IMAP mailbox for new mails and tries to handle them. | 2.960017 | 2.821853 | 1.048962 |
for regex in self.regex_expressions:
ips = regex.findall(text)
if len(ips) > 0:
return ips
return [] | def find_ips(self, text) | Uses some regex to find IPs within the text.
:param text: the text to search in
:type text: str
:return: list of ips
:rtype: list | 3.475236 | 3.757073 | 0.924985 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.