code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def on_copy_local(self, pair):
status = pair.remote_classification
self._log_action("copy", status, ">", pair.local) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content stri... | Called when the local resource should be copied to remote. |
def generate_headline_from_description(sender, instance, *args, **kwargs):
lines = instance.description.split('\n')
headline = truncatewords(lines[0], 20)
if headline[:-3] == '...':
headline = truncatechars(headline.replace(' ...', ''), 250)
else:
headline = truncatechars(headline, 250)
... | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end ... | Auto generate the headline of the node from the first lines of the description. |
def _match_excluded(self, filename, patterns):
return _wcparse._match_real(
filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks
) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Call match real directly to skip unnecessary `exists` check. |
def put_stream(self, bucket, label, stream_object, params={}):
self.claim_bucket(bucket)
self.connection.put_object(bucket, label, stream_object,
headers=self._convert_to_meta(params)) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier dictionary block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list ident... | Create a new file to swift object storage. |
def dup2(a, b, timeout=3):
dup_err = None
for i in range(int(10 * timeout)):
try:
return os.dup2(a, b)
except OSError as e:
dup_err = e
if e.errno == errno.EBUSY:
time.sleep(0.1)
else:
raise
if dup_err:
r... | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier none for_statement identifier call identifier argument_list call identifier argument_list binary_operator integer identifier block try_statement block return_state... | Like os.dup2, but retry on EBUSY |
def do_run_one(self, args):
work_spec_names = args.from_work_spec or None
worker = SingleWorker(self.config, task_master=self.task_master, work_spec_names=work_spec_names, max_jobs=args.max_jobs)
worker.register()
rc = False
starttime = time.time()
count = 0
try:
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier boolean_operator attribute identifier identifier none expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute ide... | run a single job |
def article2draft(article):
draft = Draft(article._content, article.metadata, article.settings,
article.source_path, article._context)
draft.status = 'draft'
return draft | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement ... | Transform an Article to Draft |
def print_and_exit(results):
for success, value in results:
if success:
print value.encode(locale.getpreferredencoding())
else:
value.printTraceback() | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier block if_statement identifier block print_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list else_clause block expression_statement c... | Print each result and stop the reactor. |
def show_buffer(pymux, variables):
text = get_app().clipboard.get_data().text
pymux.get_client_state().layout_manager.display_popup('show-buffer', text) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute call attribute attribute call identifier argument_list identifier identifier argument_list identifier expression_statement call attribute attribute call attribute identifier identifier argum... | Display the clipboard content. |
def txt2mecab(text, **kwargs):
mecab_out = _internal_mecab_parse(text, **kwargs).splitlines()
tokens = [MeCabToken.parse(x) for x in mecab_out]
return MeCabSent(text, tokens) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier dictionary_splat identifier identifier argument_list expression_statement assignment identifier list_comprehension call... | Use mecab to parse one sentence |
def search_fast(self, text):
resp = self.impl.get(
"{base_url}/{text}/json".format(base_url=self.base_url, text=text)
)
return resp.json()["info"]["package_url"] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute iden... | do a sloppy quick "search" via the json index |
def _cursor_forward(self, value):
if value <= 0:
value = 1
self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, value)
self._text_edit.setTextCursor(self._cursor)
self._last_cursor_pos = self._cursor.position() | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier integer block expression_statement assignment identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier... | Moves the cursor forward. |
def exec_(controller, cmd, *args):
controller.logger.info("Executing: {0} {1}", cmd, " ".join(args))
try:
subprocess.check_call([cmd] + list(args))
except (OSError, subprocess.CalledProcessError) as err:
controller.logger.error("Failed to execute process: {0}", err) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier call attribute string string_start string_content string_end id... | Executes a subprocess in the foreground, blocking until returned. |
def _ndays(self, start_date, ndays):
if not getattr(self.args, 'start-date') and not self.config.get('start-date', None):
raise Exception('start-date must be provided when ndays is used.')
d = date(*map(int, start_date.split('-')))
d += timedelta(days=ndays)
return d.strftime... | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator not_operator call identifier argument_list attribute identifier identifier string string_start string_content string_end not_operator call attribute attribute identifier identifier identifier argument_l... | Compute an end date given a start date and a number of days. |
def build_one(self, object, lines, fasta, fw, newagp=None):
components = []
total_bp = 0
for line in lines:
if line.is_gap:
seq = 'N' * line.gap_length
if newagp:
print(line, file=newagp)
else:
seq = fast... | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier list expression_statement assignment identifier integer for_statement identifier identifier block if_statement attribute identifier i... | Construct molecule using component fasta sequence |
def regularrun(
shell,
prompt_template="default",
aliases=None,
envvars=None,
extra_commands=None,
speed=1,
test_mode=False,
commentecho=False,
):
loop_again = True
command_string = regulartype(prompt_template)
if command_string == TAB:
loop_again = False
retu... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier integer default_parameter identifier false default_par... | Allow user to run their own live commands until CTRL-Z is pressed again. |
def _read(self, stream, text, byte_order):
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
m... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier eli... | Read the actual data from a PLY file. |
def stringClade(taxrefs, name, at):
string = []
for ref in taxrefs:
d = float(at-ref.level)
ident = re.sub("\s", "_", ref.ident)
string.append('{0}:{1}'.format(ident, d))
string = ','.join(string)
string = '({0}){1}'.format(string, name)
return string | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier attribute identifier identifier expression... | Return a Newick string from a list of TaxRefs |
def as_conll(self):
def get(field):
value = getattr(self, field)
if value is None:
value = '_'
elif field == 'feats':
value = '|'.join(value)
return str(value)
return '\t'.join([get(field) for field in FIELD_NAMES]) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier st... | Represent this Token as a line as a string in CoNLL-X format. |
def step(self):
op = self.code[self.instruction_pointer]
self.instruction_pointer += 1
op(self) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement call identifier argument_list iden... | Executes one instruction and stops. |
def _gc_dead_sinks(self):
deadsinks = []
for i in self._sinks:
if i() is None:
deadsinks.append(i)
for i in deadsinks:
self._sinks.remove(i) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement comparison_operator call identifier argument_list none block expression_statement call attribute identifier identifier argument_li... | Remove any dead weakrefs. |
def _clear_minimum_terms(self, match_key):
try:
del self._query_terms[match_key]['$gte']
except KeyError:
pass
try:
del self._query_terms[match_key]['$lt']
except KeyError:
pass
try:
if self._query_terms[match_key] == {}... | module function_definition identifier parameters identifier identifier block try_statement block delete_statement subscript subscript attribute identifier identifier identifier string string_start string_content string_end except_clause identifier block pass_statement try_statement block delete_statement subscript subs... | clears minimum match_key term values |
def run(self, serialized_instance, *args, **kwargs):
try:
instance = utils.deserialize_instance(serialized_instance)
except ObjectDoesNotExist:
message = ('Cannot restore instance from serialized object %s. Probably it was deleted.' %
serialized_instance)
... | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement ... | Deserialize input data and start backend operation execution |
async def pre_handle(self, request: Request, responder: 'Responder'):
responder.send([lyr.Typing()])
await responder.flush(request)
responder.clear()
await self.next(request, responder) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list call attribute identifier identifier argument_list expre... | Start typing right when the message is received. |
def removeBiosample(self):
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
biosample = dataset.getBiosampleByName(self._args.biosampleName)
def func():
self._updateRepo(self._repo.removeBiosample, biosample)
self._confirmDelete("Biosampl... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_sta... | Removes a biosample from this repo |
def contains_point(self, p):
for iv in self.s_center:
if iv.contains_point(p):
return True
branch = self[p > self.x_center]
return branch and branch.contains_point(p) | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement true expression_statement assignment identifier subscript identifier comparison_op... | Returns whether this node or a child overlaps p. |
def name2mount(self, name):
if not self.is_module(name):
raise ValueError('%r is not a supported module name' % (name, ))
return name.replace(self.module_prefix, self.mount_prefix) | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier return_statement call at... | Convert a module name to a mount name |
def _put(self, item: SQLBaseObject):
if item._dto_type in self._expirations and self._expirations[item._dto_type] == 0:
return
item.updated()
self._session().merge(item) | module function_definition identifier parameters identifier typed_parameter identifier type identifier block if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator subscript attribute identifier identifier attribute identifier identifier int... | Puts a item into the database. Updates lastUpdate column |
def getNamedActionValue(self, name):
actions = self._actions
if (type (actions) is list):
for a in actions:
if a.get('name', 'NoValue') == name:
dict =a
else:
dict = actions
return dict.get('value', 'NoValue') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement parenthesized_expression comparison_operator call identifier argument_list identifier identifier block for_statement identifier identifier block if_stateme... | Get the value of the named Tropo action. |
async def open_websocket_client(sock: anyio.abc.SocketStream,
addr,
path: str,
headers: Optional[list] = None,
subprotocols: Optional[list] = None):
ws = await create_websocket_client(
... | module function_definition identifier parameters typed_parameter identifier type attribute attribute identifier identifier identifier identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier none typed_default_parameter identifi... | Create a websocket on top of a socket. |
def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,
nofilter=0, type=ETH_P_ALL, *args, **kargs):
if iface is None and iface_hint is not None:
iface = conf.route.route(iface_hint)[0]
s = conf.L2socket(promisc=promisc, iface=iface,
filter=filter, nofilter=nofil... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier integer default_parameter identifier identifier list_splat_pattern identifier dictionary_splat_... | Send and receive packets at layer 2 |
async def getlinks(url):
page = Linkfetcher(url)
await page.linkfetch()
for i, url in enumerate(page):
return (i, url) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement await call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier bl... | Get Links from the Linkfetcher class. |
def find_in_tree(tree, key, perfect=False):
if len(key) == 0:
if tree['item'] is not None:
return tree['item'], ()
else:
for i in range(len(tree['subtrees'])):
if not perfect and tree['subtrees'][i][0] == '*':
item, trace = find_in_tree(tre... | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator subscript identifier string string_start string_content string_end none block return_st... | Helper to perform find in dictionary tree. |
def fetch_31(self):
today = datetime.datetime.today()
before = today - datetime.timedelta(days=60)
self.fetch_from(before.year, before.month)
self.data = self.data[-31:]
return self.data | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list keyword_argument i... | Fetch 31 days data |
def run(self, context=None, stdout=None, stderr=None):
"Like execute, but records a skip if the should_skip method returns True."
if self.should_skip():
self._record_skipped_example(self.formatter)
self.num_skipped += 1
else:
self.execute(context, stdout, stde... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement string string_start string_content string_end if_statement call attribute identifier identifier argument_list block expression_stat... | Like execute, but records a skip if the should_skip method returns True. |
def getData(self):
url = self.server + self.name
data = GitHubUser.__getDataFromURL(url)
web = BeautifulSoup(data, "lxml")
self.__getContributions(web)
self.__getLocation(web)
self.__getAvatar(web)
self.__getNumberOfRepositories(web)
self.__getNumberOfFoll... | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assig... | Get data of the GitHub user. |
def ThreadsWithRunningExecServers(self):
socket_dir = '/tmp/pyringe_%s' % self.inferior.pid
if os.path.isdir(socket_dir):
return [int(fname[:-9])
for fname in os.listdir(socket_dir)
if fname.endswith('.execsock')]
return [] | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier ... | Returns a list of tids of inferior threads with open exec servers. |
def checkFuelPosition(obs, agent_host):
for i in range(1,39):
key = 'InventorySlot_'+str(i)+'_item'
if key in obs:
item = obs[key]
if item == 'coal':
agent_host.sendCommand("swapInventoryItems 0 " + str(i))
return | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list integer integer block expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier stri... | Make sure our coal, if we have any, is in slot 0. |
def fetch_next_page(self):
result = self.request_handler.get(url=self.next_page_url).json()
self.__init__(self.request_handler, result,
self.data_type, self.automatic_pagination) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier identifier argument_list expression_statement call attribute ide... | Retrieves the next page of data and refreshes Pages instance. |
def ascii(graph):
from .._ascii import DAG
from .._echo import echo_via_pager
echo_via_pager(str(DAG(graph))) | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement call identifier argument_list call id... | Format graph as an ASCII art. |
def custom_field_rendering(context, field, *args, **kwargs):
if CUSTOM_FIELD_RENDERER:
mod, cls = CUSTOM_FIELD_RENDERER.rsplit(".", 1)
field_renderer = getattr(import_module(mod), cls)
if field_renderer:
return field_renderer(field, **kwargs).render()
return field | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_co... | Wrapper for rendering the field via an external renderer |
def _get_app_auth_headers(self):
now = datetime.now(timezone.utc)
expiry = now + timedelta(minutes=5)
data = {"iat": now, "exp": expiry, "iss": self.app_id}
app_token = jwt.encode(data, self.app_key, algorithm="RS256").decode("utf-8")
headers = {
"Accept": PREVIEW_JSO... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list keyword_argument identifier ... | Set the correct auth headers to authenticate against GitHub. |
def normalize(self):
error = self.a * self.b
t0 = self.a - (self.b * (0.5 * error))
t1 = self.b - (self.a * (0.5 * error))
t2 = t0 % t1
self.a = t0 * (1.0 / t0.length())
self.b = t1 * (1.0 / t1.length())
self.c = t2 * (1.0 / t2.length()) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator... | re-normalise a rotation matrix |
def intersect(self, other):
if other is FullSpace:
return self
if other is TrivialSpace:
return TrivialSpace
if isinstance(other, ProductSpace):
other_ops = set(other.operands)
else:
other_ops = {other}
return ProductSpace.create(
... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block return_statement identifier if_statement comparison_operator identifier identifier block return_statement identifier if_statement call identifier argument_list identifier identifier ... | Find the mutual tensor factors of two Hilbert spaces. |
async def authenticate(self, username: str, password: str) -> None:
self._credentials = {
'username': username,
'password': password,
}
await self._get_security_token() | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block expression_statement assignment attribute identifier identifier dictionary pair string string_start string_content string_end identifier pair string string_st... | Authenticate against the API. |
def filter_by_type():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmt_type_str = body.get('type')
stmt_type_str = stmt_type_str.capitalize()
stmt_type = getattr(sys.modules[_... | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement dictionary expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argu... | Filter to a given INDRA Statement type. |
def _set_menu_toggles(self):
toggles = [
(self.main_toolbar, "main_window_toolbar", _("Main toolbar")),
(self.macro_toolbar, "macro_toolbar", _("Macro toolbar")),
(self.macro_panel, "macro_panel", _("Macro panel")),
(self.attributes_toolbar, "attributes_toolbar",
... | module function_definition identifier parameters identifier block expression_statement assignment identifier list tuple attribute identifier identifier string string_start string_content string_end call identifier argument_list string string_start string_content string_end tuple attribute identifier identifier string s... | Enable menu bar view item checkmarks |
def put(self, publisher):
if publisher.name not in self.pools:
self.pools[publisher.name] = _Pool(logger=self.logger, name=publisher.name)
self.pools[publisher.name].put(publisher) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier call identifier argument_list keyw... | releases the Publisher instance for reuse |
def SetPercentageView(self, percentageView):
self.percentageView = percentageView
self.percentageMenuItem.Check(self.percentageView)
self.percentageViewTool.SetValue(self.percentageView)
total = self.adapter.value( self.loader.get_root( self.viewType ) )
for control in self.Profi... | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribu... | Set whether to display percentage or absolute values |
def detect_regions(bam_in, bed_file, out_dir, prefix):
bed_file = _reorder_columns(bed_file)
counts_reads_cmd = ("coverageBed -s -counts -b {bam_in} "
"-a {bed_file} | sort -k4,4 "
"> {out_dir}/loci.cov")
with utils.chdir(out_dir):
run(counts_reads_cmd... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end str... | Detect regions using first CoRaL module |
def checkout(self, *args, **kwargs):
self._call_helper("Checking out", self.real.checkout, *args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier list_splat identi... | This function checks out source code. |
def _set_lookup_prop(self, result_data):
if self._lookup_prop:
return
if result_data.get("id"):
self._lookup_prop = "id"
elif result_data.get("title"):
self._lookup_prop = "name"
else:
return
logger.debug("Setting lookup method for ... | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block return_statement if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment attribute identifier identi... | Set lookup property based on processed testcases if not configured. |
def print_context_names(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo('\n'.join(_context_names()))
ctx.exit() | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator not_operator identifier attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content e... | Print all possible types. |
def find(self, header, list_type=None):
for chunk in self:
if chunk.header == header and (list_type is None or (header in
list_headers and chunk.type == list_type)):
return chunk
elif chunk.header in list_headers:
try:
... | module function_definition identifier parameters identifier identifier default_parameter identifier none block for_statement identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier identifier parenthesized_expression boolean_operator comparison_operator identifier n... | Find the first chunk with specified header and optional list type. |
def optional_install():
print('{BOLD}Setting up Reduce (optional){END_C}'.format(**text_colours))
reduce = {}
reduce_path = get_user_path('Please provide a path to your reduce executable.', required=False)
reduce['path'] = str(reduce_path)
reduce['folder'] = str(reduce_path.parent) if reduce_path el... | module function_definition identifier parameters block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list dictionary_splat identifier expression_statement assignment identifier dictionary expression_statement assignment identifier cal... | Generates configuration settings for optional functionality of ISAMBARD. |
def _create_font_face_buttons(self):
font_face_buttons = [
(wx.FONTFLAG_BOLD, "OnBold", "FormatTextBold", _("Bold")),
(wx.FONTFLAG_ITALIC, "OnItalics", "FormatTextItalic",
_("Italics")),
(wx.FONTFLAG_UNDERLINED, "OnUnderline", "FormatTextUnderline",
... | module function_definition identifier parameters identifier block expression_statement assignment identifier list tuple attribute identifier identifier string string_start string_content string_end string string_start string_content string_end call identifier argument_list string string_start string_content string_end ... | Creates font face buttons |
def to_python(self, value: Union[Dict[str, int], int, None]) -> LocalizedIntegerValue:
db_value = super().to_python(value)
return self._convert_localized_value(db_value) | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier type identifier type none type identifier block expression_statement assignment identifier call attribute call id... | Converts the value from a database value into a Python value. |
def _insert_breaklines(self):
target_chunks = ChunkList()
for chunk in self:
if chunk.word[-1] == ' ' and chunk.has_cjk():
chunk.word = chunk.word[:-1]
target_chunks.append(chunk)
target_chunks.append(chunk.breakline())
else:
target_chunks.append(chunk)
self.list ... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block if_statement boolean_operator comparison_operator subscript attribute identifier identifier unary_operator integer string string_start stri... | Inserts a breakline instead of a trailing space if the chunk is in CJK. |
def report_and_raise(probe_name, probe_result, failure_msg):
log.info('%s? %s' % (probe_name, probe_result))
if not probe_result:
raise exceptions.ProbeException(failure_msg)
else:
return True | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier if_statement not_operator identifier block raise_statement call attrib... | Logs the probe result and raises on failure |
def do_disable_commands(self, _):
message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME,
self.CMD_CAT_APP_MGMT)
self.disable_category(self.CMD_CAT_APP_MGMT, message_to_print)
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list... | Disable the Application Management commands |
def request_error_header(exception):
from .conf import options
header = "Bearer realm=\"%s\"" % (options.realm, )
if hasattr(exception, "error"):
header = header + ", error=\"%s\"" % (exception.error, )
if hasattr(exception, "reason"):
header = header + ", error_description=\"%s\"" % (ex... | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute ide... | Generates the error header for a request using a Bearer token based on a given OAuth exception. |
def addEnvPath(env, name, value):
try:
oldval = env[name]
if not oldval.endswith(';'):
oldval = oldval + ';'
except KeyError:
oldval = ""
if not value.endswith(';'):
value = value + ';'
env[name] = oldval + value | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier subscript identifier identifier if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expressi... | concat a path for this name |
def _can_cell_be_merged(self, x, y):
value = self.grid[y][x]
if y > 0 and self.grid[y - 1][x] == value:
return True
if y < self.COUNT_Y - 1 and self.grid[y + 1][x] == value:
return True
if x > 0 and self.grid[y][x - 1] == value:
return True
if ... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier identifier identifier if_statement boolean_operator comparison_operator identifier integer comparison_operator subscript subscript attrib... | Checks if a cell can be merged, when the |
def get(self, endpoint: str, **kwargs) -> dict:
return self._request('GET', endpoint, **kwargs) | module function_definition identifier parameters identifier typed_parameter identifier type identifier dictionary_splat_pattern identifier type identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier dictionary_splat identifier | HTTP GET operation to API endpoint. |
def _SI(size, K=1024, i='i'):
if 1 < K < size:
f = float(size)
for si in iter('KMGPTE'):
f /= K
if f < K:
return ' or %.1f %s%sB' % (f, si, i)
return '' | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier string string_start string_content string_end block if_statement comparison_operator integer identifier identifier block expression_statement assignment identifier call identifier argument_list ... | Return size as SI string. |
def merge(self, paths):
topojson_binary = 'node_modules/bin/topojson'
if not os.path.exists(topojson_binary):
topojson_binary = 'topojson'
merge_cmd = '%(binary)s -o %(output_path)s --bbox -p -- %(paths)s' % {
'output_path': self.args.output_path,
'paths': ' '... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identif... | Merge data layers into a single topojson file. |
def _wl_dist(wl_a, wl_b):
if isinstance(wl_a, tuple):
wl_a = wl_a[1]
if isinstance(wl_b, tuple):
wl_b = wl_b[1]
if wl_a is None or wl_b is None:
return 1000.
return abs(wl_a - wl_b) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier integer if_statement call identifier argument_list identifier identifier block expression_statement assignme... | Return the distance between two requested wavelengths. |
def _get_xlabel(self):
if self.xlabel:
return self.xlabel
if hasattr(self.estimator, "coef_"):
if self.relative:
return "relative coefficient magnitude"
return "coefficient value"
if self.relative:
return "relative importance"
... | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block if_statement attribute iden... | Determines the xlabel based on the underlying data structure |
def create(self, *args, **kwargs):
href = self.url
if len(args) == 1:
kwargs[self.model_class.primary_key] = args[0]
href = '/'.join([href, args[0]])
model = self.model_class(self,
href=href.replace('classifications/', 'classification/'),
... | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assi... | Add a resource to this collection. |
def debug_video_writer_factory(output_dir):
if FLAGS.disable_ffmpeg:
return common_video.IndividualFrameWriter(output_dir)
else:
output_path = os.path.join(output_dir, "video.avi")
return common_video.WholeVideoWriter(
fps=10, output_path=output_path, file_format="avi"
) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argum... | Creates a VideoWriter for debug videos. |
def putsz(self, addr, s):
self.puts(addr, s)
self._buf[addr+len(s)] = 0 | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript attribute identifier identifier binary_operator identifier call identifier argument_list identif... | Put bytes string in object at addr and append terminating zero at end. |
def initialize_directories(self, root_dir):
if not root_dir:
root_dir = os.path.expanduser('~')
self.config_dir = os.path.join(root_dir, '.config/pueue')
if not os.path.exists(self.config_dir):
os.makedirs(self.config_dir) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribu... | Create all directories needed for logs and configs. |
def cannon_normalize(spec_raw):
spec = np.array([spec_raw])
wl = np.arange(0, spec.shape[1])
w = continuum_normalization.gaussian_weight_matrix(wl, L=50)
ivar = np.ones(spec.shape)*0.5
cont = continuum_normalization._find_cont_gaussian_smooth(
wl, spec, ivar, w)
norm_flux, norm_ivar ... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list identifier expression_statement assignment identifier call attribute identifier identifier argument_list integer subscript attribute identifier identifier ... | Normalize according to The Cannon |
def move_right(self):
self.at(ardrone.at.pcmd, True, self.speed, 0, 0, 0) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier true attribute identifier identifier integer integer integer | Make the drone move right. |
def _requires_login(func: Callable) -> Callable:
@wraps(func)
def call(instaloader, *args, **kwargs):
if not instaloader.context.is_logged_in:
raise LoginRequiredException("--login=USERNAME required.")
return func(instaloader, *args, **kwargs)
call.__doc__ += ":raises LoginRequir... | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statem... | Decorator to raise an exception if herewith-decorated function is called without being logged in |
def _nicetitle(coord, value, maxchar, template):
prettyvalue = format_item(value, quote_strings=False)
title = template.format(coord=coord, value=prettyvalue)
if len(title) > maxchar:
title = title[:(maxchar - 3)] + '...'
return title | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier false expression_statement assignment identifier call attribute identifier identifier argument_list keyword_a... | Put coord, value in template and truncate at maxchar |
def dict_keys_without_hyphens(a_dict):
return dict(
(key.replace('-', '_'), val) for key, val in a_dict.items()) | module function_definition identifier parameters identifier block return_statement call identifier generator_expression tuple call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier for_in_clause pattern_list identifier id... | Return the a new dict with underscores instead of hyphens in keys. |
def compile_results(self):
self._init_dataframes()
self.total_transactions = len(self.main_results['raw'])
self._init_dates() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end ... | Compile all results for the current test |
def DualDBSystemCronJob(legacy_name=None, stateful=False):
def Decorator(cls):
if not legacy_name:
raise ValueError("legacy_name has to be provided")
if stateful:
aff4_base_cls = StatefulSystemCronFlow
else:
aff4_base_cls = SystemCronFlow
if issubclass(cls, cronjobs.SystemCronJobBase... | module function_definition identifier parameters default_parameter identifier none default_parameter identifier false block function_definition identifier parameters identifier block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end if... | Decorator that creates AFF4 and RELDB cronjobs from a given mixin. |
def remove_gaps(A, B):
a_seq, b_seq = [], []
for a, b in zip(list(A), list(B)):
if a == '-' or a == '.' or b == '-' or b == '.':
continue
a_seq.append(a)
b_seq.append(b)
return ''.join(a_seq), ''.join(b_seq) | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier expression_list list list for_statement pattern_list identifier identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list ... | skip column if either is a gap |
def description(self):
lines = []
for line in self.__doc__.split('\n')[2:]:
line = line.strip()
if line:
lines.append(line)
return ' '.join(lines) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end slice integer block expression_statem... | Attribute that returns the plugin description from its docstring. |
def read_features_and_groups(features_path, groups_path):
"Reader for data and groups"
try:
if not pexists(features_path):
raise ValueError('non-existent features file')
if not pexists(groups_path):
raise ValueError('non-existent groups file')
if isinstance(featur... | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end try_statement block if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content st... | Reader for data and groups |
def batch_row_ids(data_batch):
item = data_batch.data[0]
user = data_batch.data[1]
return {'user_weight': user.astype(np.int64),
'item_weight': item.astype(np.int64)} | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier subscript attribute identifier identifier integer return_statement dictionary pair string string_start string_content ... | Generate row ids based on the current mini-batch |
def generate_schedule(today=None):
schedule_days = {}
seen_items = {}
for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'):
day = slot.get_day()
if today and day != today:
continue
schedule_day = schedule_days.get(day)
if schedule_day is None:
... | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary for_statement identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier ... | Helper function which creates an ordered list of schedule days |
def should_indent(code):
last = rem_comment(code.splitlines()[-1])
return last.endswith(":") or last.endswith("\\") or paren_change(last) < 0 | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list subscript call attribute identifier identifier argument_list unary_operator integer return_statement boolean_operator boolean_operator call attribute identifier identifier argument_... | Determines whether the next line should be indented. |
def _add_ctc_loss(pred, seq_len, num_label, loss_type):
label = mx.sym.Variable('label')
if loss_type == 'warpctc':
print("Using WarpCTC Loss")
sm = _add_warp_ctc_loss(pred, seq_len, num_label, label)
else:
print("Using MXNet CTC Loss")
assert loss_type == 'ctc'
sm = ... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier string string_st... | Adds CTC loss on top of pred symbol and returns the resulting symbol |
def _der_to_raw(self, der_signature):
r, s = decode_dss_signature(der_signature)
component_length = self._sig_component_length()
return int_to_bytes(r, component_length) + int_to_bytes(s, component_length) | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement binary_operator call ide... | Convert signature from DER encoding to RAW encoding. |
def url2fs(url):
uri, extension = posixpath.splitext(url)
return safe64.dir(uri) + extension | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement binary_operator call attribute identifier identifier argument_list identifier identifier | encode a URL to be safe as a filename |
def resize_image(image_str_tensor):
image = decode_and_resize(image_str_tensor)
image = tf.image.encode_jpeg(image, quality=100)
return image | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier integer return_s... | Decodes jpeg string, resizes it and re-encode it to jpeg. |
def types(self):
return [term for term in self._terms
if isinstance(term, (TypeIdentifier, String, Regex))] | module function_definition identifier parameters identifier block return_statement list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause call identifier argument_list identifier tuple identifier identifier identifier | Return the list of type terms in the conjunction. |
def action(self, relationship):
action_obj = FileAction(self.xid, relationship)
self._children.append(action_obj) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Add a nested File Action. |
def science_object_update(self, pid_old, path, pid_new, format_id=None):
self._queue_science_object_update(pid_old, path, pid_new, format_id) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | Obsolete a Science Object on a Member Node with a different one. |
def clean_ret_type(ret_type):
ret_type = get_printable(ret_type).strip()
if ret_type == 'LRESULT LRESULT':
ret_type = 'LRESULT'
for bad in [
'DECLSPEC_NORETURN', 'NTSYSCALLAPI', '__kernel_entry',
'__analysis_noreturn', '_Post_equals_last_error_',
'_Maybe_raises_SE... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment id... | Clean the erraneous parsed return type. |
def sanity_check_wirevector(self, w):
from .wire import WireVector
if not isinstance(w, WireVector):
raise PyrtlError(
'error attempting to pass an input of type "%s" '
'instead of WireVector' % type(w)) | module function_definition identifier parameters identifier identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator... | Check that w is a valid wirevector type. |
def can(self, action, subject, **conditions):
for rule in self.relevant_rules_for_match(action, subject):
if rule.matches_conditions(action, subject, **conditions):
return rule.base_behavior
return False | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block for_statement identifier call attribute identifier identifier argument_list identifier identifier block if_statement call attribute identifier identifier argument_list identifier identifier dictio... | Check if the user has permission to perform a given action on an object |
def make_disk(parser):
disk_parser = parser.add_subparsers(dest='subcommand')
disk_parser.required = True
disk_zap = disk_parser.add_parser(
'zap',
help='destroy existing data and filesystem on LV or partition',
)
disk_zap.add_argument(
'host',
nargs='?',
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier true expression_statem... | Manage disks on a remote host. |
def __begin_of_list(self, ast_token):
self.list_level += 1
if self.list_level == 1:
self.final_ast_tokens.append(ast_token) | module function_definition identifier parameters identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier arg... | Handle begin of a list. |
def _write_vmx_file(self):
try:
self.manager.write_vmx_file(self._vmx_path, self._vmx_pairs)
except OSError as e:
raise VMwareError('Could not write VMware VMX file "{}": {}'.format(self._vmx_path, e)) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_... | Writes pairs to the VMware VMX file corresponding to this VM. |
def pypi_release(self):
meta = self.distribution.metadata
pypi = ServerProxy(self.pypi_index_url)
releases = pypi.package_releases(meta.name)
if releases:
return next(iter(sorted(releases, reverse=True))) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attri... | Get the latest pypi release |
def _aug_op(instance, opnode, op, other, context, reverse=False):
method_name = protocols.AUGMENTED_OP_METHOD[op]
return functools.partial(
_invoke_binop_inference,
instance=instance,
op=op,
opnode=opnode,
other=other,
context=context,
method_name=method_n... | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier subscript attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier ... | Get an inference callable for an augmented binary operation. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.