nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
natashamjaques/neural_chat
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
ParlAI/parlai/core/worlds.py
python
MultiWorld.report
(self)
return metrics
Report aggregate metrics across all subworlds.
Report aggregate metrics across all subworlds.
[ "Report", "aggregate", "metrics", "across", "all", "subworlds", "." ]
def report(self): """Report aggregate metrics across all subworlds.""" metrics = aggregate_metrics(self.worlds) self.total_exs += metrics.get('exs', 0) return metrics
[ "def", "report", "(", "self", ")", ":", "metrics", "=", "aggregate_metrics", "(", "self", ".", "worlds", ")", "self", ".", "total_exs", "+=", "metrics", ".", "get", "(", "'exs'", ",", "0", ")", "return", "metrics" ]
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/core/worlds.py#L592-L596
jinfagang/alfred
dd7420d1410f82f9dadf07a30b6fad5a71168001
alfred/utils/timer.py
python
Timer.resume
(self)
Resume the timer.
Resume the timer.
[ "Resume", "the", "timer", "." ]
def resume(self): """ Resume the timer. """ if self._paused is None: raise ValueError("Trying to resume a Timer that is not paused!") self._total_paused += perf_counter() - self._paused self._paused = None
[ "def", "resume", "(", "self", ")", ":", "if", "self", ".", "_paused", "is", "None", ":", "raise", "ValueError", "(", "\"Trying to resume a Timer that is not paused!\"", ")", "self", ".", "_total_paused", "+=", "perf_counter", "(", ")", "-", "self", ".", "_paus...
https://github.com/jinfagang/alfred/blob/dd7420d1410f82f9dadf07a30b6fad5a71168001/alfred/utils/timer.py#L40-L47
GitGuardian/ggshield
94a1fa0f6402cd1df2dd3dbc5b932862e85f99e5
ggshield/status.py
python
status
(ctx: click.Context, json_output: bool)
return 0
Command to show api status.
Command to show api status.
[ "Command", "to", "show", "api", "status", "." ]
def status(ctx: click.Context, json_output: bool) -> int: """Command to show api status.""" client: GGClient = retrieve_client(ctx) response: HealthCheckResponse = client.health_check() if not isinstance(response, HealthCheckResponse): raise click.ClickException("Unexpected health check response") click.echo( response.to_json() if json_output else ( f"{format_text('API URL:', STYLE['key'])} {client.base_uri}\n" f"{format_text('Status:', STYLE['key'])} {format_healthcheck_status(response)}\n" f"{format_text('App version:', STYLE['key'])} {response.app_version or 'Unknown'}\n" f"{format_text('Secrets engine version:', STYLE['key'])} " f"{response.secrets_engine_version or 'Unknown'}\n" ) ) return 0
[ "def", "status", "(", "ctx", ":", "click", ".", "Context", ",", "json_output", ":", "bool", ")", "->", "int", ":", "client", ":", "GGClient", "=", "retrieve_client", "(", "ctx", ")", "response", ":", "HealthCheckResponse", "=", "client", ".", "health_check...
https://github.com/GitGuardian/ggshield/blob/94a1fa0f6402cd1df2dd3dbc5b932862e85f99e5/ggshield/status.py#L15-L35
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/kombu/async/http/curl.py
python
CurlClient._timeout_check
(self, _pycurl=pycurl)
[]
def _timeout_check(self, _pycurl=pycurl): while 1: try: ret, _ = self._multi.socket_all() except pycurl.error as exc: ret = exc.args[0] if ret != _pycurl.E_CALL_MULTI_PERFORM: break self._process_pending_requests()
[ "def", "_timeout_check", "(", "self", ",", "_pycurl", "=", "pycurl", ")", ":", "while", "1", ":", "try", ":", "ret", ",", "_", "=", "self", ".", "_multi", ".", "socket_all", "(", ")", "except", "pycurl", ".", "error", "as", "exc", ":", "ret", "=", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/kombu/async/http/curl.py#L100-L108
getting-things-gnome/gtg
4b02c43744b32a00facb98174f04ec5953bd055d
GTG/core/datastore.py
python
DataStore.push_task
(self, task)
Adds the given task object to the task tree. In other words, registers the given task in the GTG task set. This function is used in mutual exclusion: only a backend at a time is allowed to push tasks. @param task: A valid task object (a GTG.core.task.Task) @return bool: True if the task has been accepted
Adds the given task object to the task tree. In other words, registers the given task in the GTG task set. This function is used in mutual exclusion: only a backend at a time is allowed to push tasks.
[ "Adds", "the", "given", "task", "object", "to", "the", "task", "tree", ".", "In", "other", "words", "registers", "the", "given", "task", "in", "the", "GTG", "task", "set", ".", "This", "function", "is", "used", "in", "mutual", "exclusion", ":", "only", ...
def push_task(self, task): """ Adds the given task object to the task tree. In other words, registers the given task in the GTG task set. This function is used in mutual exclusion: only a backend at a time is allowed to push tasks. @param task: A valid task object (a GTG.core.task.Task) @return bool: True if the task has been accepted """ def adding(task): self._tasks.add_node(task) task.set_loaded() if self.is_default_backend_loaded: task.sync() if self.has_task(task.get_id()): return False else: # Thread protection adding(task) return True
[ "def", "push_task", "(", "self", ",", "task", ")", ":", "def", "adding", "(", "task", ")", ":", "self", ".", "_tasks", ".", "add_node", "(", "task", ")", "task", ".", "set_loaded", "(", ")", "if", "self", ".", "is_default_backend_loaded", ":", "task", ...
https://github.com/getting-things-gnome/gtg/blob/4b02c43744b32a00facb98174f04ec5953bd055d/GTG/core/datastore.py#L363-L384
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
enumflag
(*args)
return _idaapi.enumflag(*args)
enumflag() -> flags_t
enumflag() -> flags_t
[ "enumflag", "()", "-", ">", "flags_t" ]
def enumflag(*args): """ enumflag() -> flags_t """ return _idaapi.enumflag(*args)
[ "def", "enumflag", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "enumflag", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L22457-L22461
dit/dit
2853cb13110c5a5b2fa7ad792e238e2177013da2
dit/math/ops.py
python
set_add
(ops)
Set the add method on the LogOperations instance.
Set the add method on the LogOperations instance.
[ "Set", "the", "add", "method", "on", "the", "LogOperations", "instance", "." ]
def set_add(ops): """ Set the add method on the LogOperations instance. """ # To preserve numerical accuracy, we must make use of a logaddexp # function. These functions only exist in Numpy for base-e and base-2. # For all other bases, we must convert and then convert back. # In each case, we use default arguments to make the function that we # are calling 'local'. base = ops.base if base == 2: def add(self, x, y, func=np.logaddexp2): return func(x, y) elif base == 'e' or np.isclose(base, np.e): def add(self, x, y, func=np.logaddexp): return func(x, y) else: # No need to optimize this... def add(self, x, y): # Convert log_b probabilities to log_2 probabilities. x2 = x * np.log2(base) y2 = y * np.log2(base) z = np.logaddexp2(x2, y2) # Convert log_2 probabilities to log_b probabilities. z *= self.log(2) return z add.__doc__ = """ Add the arrays element-wise. Neither x nor y will be modified. Assumption: y <= 0. Parameters ---------- x, y : NumPy arrays, shape (n,) The arrays to add. Returns ------- z : NumPy array, shape (n,) The resultant array. """ ops.add = MethodType(add, ops)
[ "def", "set_add", "(", "ops", ")", ":", "# To preserve numerical accuracy, we must make use of a logaddexp", "# function. These functions only exist in Numpy for base-e and base-2.", "# For all other bases, we must convert and then convert back.", "# In each case, we use default arguments to make...
https://github.com/dit/dit/blob/2853cb13110c5a5b2fa7ad792e238e2177013da2/dit/math/ops.py#L467-L512
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/util/timezones/fields.py
python
TimeZoneField.get_db_prep_save
(self, value, connection=None)
return self.get_prep_value(value)
Prepares the given value for insertion into the database.
Prepares the given value for insertion into the database.
[ "Prepares", "the", "given", "value", "for", "insertion", "into", "the", "database", "." ]
def get_db_prep_save(self, value, connection=None): """ Prepares the given value for insertion into the database. """ return self.get_prep_value(value)
[ "def", "get_db_prep_save", "(", "self", ",", "value", ",", "connection", "=", "None", ")", ":", "return", "self", ".", "get_prep_value", "(", "value", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/util/timezones/fields.py#L45-L49
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cloudaudit/v20190319/models.py
python
Event.__init__
(self)
r""" :param EventId: 日志ID :type EventId: str :param Username: 用户名 :type Username: str :param EventTime: 事件时间 :type EventTime: str :param CloudAuditEvent: 日志详情 :type CloudAuditEvent: str :param ResourceTypeCn: 资源类型中文描述(此字段请按需使用,如果您是其他语言使用者,可以忽略该字段描述) :type ResourceTypeCn: str :param ErrorCode: 鉴权错误码 :type ErrorCode: int :param EventName: 事件名称 :type EventName: str :param SecretId: 证书ID 注意:此字段可能返回 null,表示取不到有效值。 :type SecretId: str :param EventSource: 请求来源 :type EventSource: str :param RequestID: 请求ID :type RequestID: str :param ResourceRegion: 资源地域 :type ResourceRegion: str :param AccountID: 主账号ID :type AccountID: int :param SourceIPAddress: 源IP 注意:此字段可能返回 null,表示取不到有效值。 :type SourceIPAddress: str :param EventNameCn: 事件名称中文描述(此字段请按需使用,如果您是其他语言使用者,可以忽略该字段描述) :type EventNameCn: str :param Resources: 资源对 :type Resources: :class:`tencentcloud.cloudaudit.v20190319.models.Resource` :param EventRegion: 事件地域 :type EventRegion: str :param Location: IP 归属地 :type Location: str
r""" :param EventId: 日志ID :type EventId: str :param Username: 用户名 :type Username: str :param EventTime: 事件时间 :type EventTime: str :param CloudAuditEvent: 日志详情 :type CloudAuditEvent: str :param ResourceTypeCn: 资源类型中文描述(此字段请按需使用,如果您是其他语言使用者,可以忽略该字段描述) :type ResourceTypeCn: str :param ErrorCode: 鉴权错误码 :type ErrorCode: int :param EventName: 事件名称 :type EventName: str :param SecretId: 证书ID 注意:此字段可能返回 null,表示取不到有效值。 :type SecretId: str :param EventSource: 请求来源 :type EventSource: str :param RequestID: 请求ID :type RequestID: str :param ResourceRegion: 资源地域 :type ResourceRegion: str :param AccountID: 主账号ID :type AccountID: int :param SourceIPAddress: 源IP 注意:此字段可能返回 null,表示取不到有效值。 :type SourceIPAddress: str :param EventNameCn: 事件名称中文描述(此字段请按需使用,如果您是其他语言使用者,可以忽略该字段描述) :type EventNameCn: str :param Resources: 资源对 :type Resources: :class:`tencentcloud.cloudaudit.v20190319.models.Resource` :param EventRegion: 事件地域 :type EventRegion: str :param Location: IP 归属地 :type Location: str
[ "r", ":", "param", "EventId", ":", "日志ID", ":", "type", "EventId", ":", "str", ":", "param", "Username", ":", "用户名", ":", "type", "Username", ":", "str", ":", "param", "EventTime", ":", "事件时间", ":", "type", "EventTime", ":", "str", ":", "param", "Clo...
def __init__(self): r""" :param EventId: 日志ID :type EventId: str :param Username: 用户名 :type Username: str :param EventTime: 事件时间 :type EventTime: str :param CloudAuditEvent: 日志详情 :type CloudAuditEvent: str :param ResourceTypeCn: 资源类型中文描述(此字段请按需使用,如果您是其他语言使用者,可以忽略该字段描述) :type ResourceTypeCn: str :param ErrorCode: 鉴权错误码 :type ErrorCode: int :param EventName: 事件名称 :type EventName: str :param SecretId: 证书ID 注意:此字段可能返回 null,表示取不到有效值。 :type SecretId: str :param EventSource: 请求来源 :type EventSource: str :param RequestID: 请求ID :type RequestID: str :param ResourceRegion: 资源地域 :type ResourceRegion: str :param AccountID: 主账号ID :type AccountID: int :param SourceIPAddress: 源IP 注意:此字段可能返回 null,表示取不到有效值。 :type SourceIPAddress: str :param EventNameCn: 事件名称中文描述(此字段请按需使用,如果您是其他语言使用者,可以忽略该字段描述) :type EventNameCn: str :param Resources: 资源对 :type Resources: :class:`tencentcloud.cloudaudit.v20190319.models.Resource` :param EventRegion: 事件地域 :type EventRegion: str :param Location: IP 归属地 :type Location: str """ self.EventId = None self.Username = None self.EventTime = None self.CloudAuditEvent = None self.ResourceTypeCn = None self.ErrorCode = None self.EventName = None self.SecretId = None self.EventSource = None self.RequestID = None self.ResourceRegion = None self.AccountID = None self.SourceIPAddress = None self.EventNameCn = None self.Resources = None self.EventRegion = None self.Location = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "EventId", "=", "None", "self", ".", "Username", "=", "None", "self", ".", "EventTime", "=", "None", "self", ".", "CloudAuditEvent", "=", "None", "self", ".", "ResourceTypeCn", "=", "None", "self", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cloudaudit/v20190319/models.py#L478-L533
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/core/worker/transformer.py
python
Enumerate.reverse
(self, transformed_point, index=None)
return self._imap(transformed_point)
Return categories corresponding to their positions inside `transformed_point`.
Return categories corresponding to their positions inside `transformed_point`.
[ "Return", "categories", "corresponding", "to", "their", "positions", "inside", "transformed_point", "." ]
def reverse(self, transformed_point, index=None): """Return categories corresponding to their positions inside `transformed_point`.""" return self._imap(transformed_point)
[ "def", "reverse", "(", "self", ",", "transformed_point", ",", "index", "=", "None", ")", ":", "return", "self", ".", "_imap", "(", "transformed_point", ")" ]
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/core/worker/transformer.py#L453-L455
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol36144.py
python
decode_replay_initdata
(contents)
return decoder.instance(replay_initdata_typeid)
Decodes and return the replay init data from the contents byte string.
Decodes and return the replay init data from the contents byte string.
[ "Decodes", "and", "return", "the", "replay", "init", "data", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_initdata(contents): """Decodes and return the replay init data from the contents byte string.""" decoder = BitPackedDecoder(contents, typeinfos) return decoder.instance(replay_initdata_typeid)
[ "def", "decode_replay_initdata", "(", "contents", ")", ":", "decoder", "=", "BitPackedDecoder", "(", "contents", ",", "typeinfos", ")", "return", "decoder", ".", "instance", "(", "replay_initdata_typeid", ")" ]
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol36144.py#L452-L455
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/networkx/algorithms/cycles.py
python
cycle_basis
(G, root=None)
return cycles
Returns a list of cycles which form a basis for cycles of G. A basis for cycles of a network is a minimal collection of cycles such that any cycle in the network can be written as a sum of cycles in the basis. Here summation of cycles is defined as "exclusive or" of the edges. Cycle bases are useful, e.g. when deriving equations for electric circuits using Kirchhoff's Laws. Parameters ---------- G : NetworkX Graph root : node, optional Specify starting node for basis. Returns ------- A list of cycle lists. Each cycle list is a list of nodes which forms a cycle (loop) in G. Examples -------- >>> G = nx.Graph() >>> nx.add_cycle(G, [0, 1, 2, 3]) >>> nx.add_cycle(G, [0, 3, 4, 5]) >>> print(nx.cycle_basis(G, 0)) [[3, 4, 5, 0], [1, 2, 3, 0]] Notes ----- This is adapted from algorithm CACM 491 [1]_. References ---------- .. [1] Paton, K. An algorithm for finding a fundamental set of cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518. See Also -------- simple_cycles
Returns a list of cycles which form a basis for cycles of G.
[ "Returns", "a", "list", "of", "cycles", "which", "form", "a", "basis", "for", "cycles", "of", "G", "." ]
def cycle_basis(G, root=None): """ Returns a list of cycles which form a basis for cycles of G. A basis for cycles of a network is a minimal collection of cycles such that any cycle in the network can be written as a sum of cycles in the basis. Here summation of cycles is defined as "exclusive or" of the edges. Cycle bases are useful, e.g. when deriving equations for electric circuits using Kirchhoff's Laws. Parameters ---------- G : NetworkX Graph root : node, optional Specify starting node for basis. Returns ------- A list of cycle lists. Each cycle list is a list of nodes which forms a cycle (loop) in G. Examples -------- >>> G = nx.Graph() >>> nx.add_cycle(G, [0, 1, 2, 3]) >>> nx.add_cycle(G, [0, 3, 4, 5]) >>> print(nx.cycle_basis(G, 0)) [[3, 4, 5, 0], [1, 2, 3, 0]] Notes ----- This is adapted from algorithm CACM 491 [1]_. References ---------- .. [1] Paton, K. An algorithm for finding a fundamental set of cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518. See Also -------- simple_cycles """ gnodes = set(G.nodes()) cycles = [] while gnodes: # loop over connected components if root is None: root = gnodes.pop() stack = [root] pred = {root: root} used = {root: set()} while stack: # walk the spanning tree finding cycles z = stack.pop() # use last-in so cycles easier to find zused = used[z] for nbr in G[z]: if nbr not in used: # new node pred[nbr] = z stack.append(nbr) used[nbr] = set([z]) elif nbr == z: # self loops cycles.append([z]) elif nbr not in zused: # found a cycle pn = used[nbr] cycle = [nbr, z] p = pred[z] while p not in pn: cycle.append(p) p = pred[p] cycle.append(p) cycles.append(cycle) used[nbr].add(z) gnodes -= set(pred) root = None return cycles
[ "def", "cycle_basis", "(", "G", ",", "root", "=", "None", ")", ":", "gnodes", "=", "set", "(", "G", ".", "nodes", "(", ")", ")", "cycles", "=", "[", "]", "while", "gnodes", ":", "# loop over connected components", "if", "root", "is", "None", ":", "ro...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/networkx/algorithms/cycles.py#L33-L105
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/requests/cookies.py
python
RequestsCookieJar.__setitem__
(self, name, value)
Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead.
Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead.
[ "Dict", "-", "like", "__setitem__", "for", "compatibility", "with", "client", "code", ".", "Throws", "exception", "if", "there", "is", "already", "a", "cookie", "of", "that", "name", "in", "the", "jar", ".", "In", "that", "case", "use", "the", "more", "e...
def __setitem__(self, name, value): """Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead. """ self.set(name, value)
[ "def", "__setitem__", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "set", "(", "name", ",", "value", ")" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/requests/cookies.py#L331-L336
TheSouthFrog/stylealign
910632d2fccc9db61b00c265ae18a88913113c1d
pytorch_code/Data/aligned_dataset.py
python
AlignedBoundaryDetection.__len__
(self)
return len(self.A_paths)
[]
def __len__(self): return len(self.A_paths)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "A_paths", ")" ]
https://github.com/TheSouthFrog/stylealign/blob/910632d2fccc9db61b00c265ae18a88913113c1d/pytorch_code/Data/aligned_dataset.py#L600-L601
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/backend/vs2010backend.py
python
Vs2010Backend.generate
(self)
[]
def generate(self): target_machine = self.interpreter.builtin['target_machine'].cpu_family_method(None, None) if target_machine == '64' or target_machine == 'x86_64': # amd64 or x86_64 self.platform = 'x64' elif target_machine == 'x86': # x86 self.platform = 'Win32' elif target_machine == 'aarch64' or target_machine == 'arm64': target_cpu = self.interpreter.builtin['target_machine'].cpu_method(None, None) if target_cpu == 'arm64ec': self.platform = 'arm64ec' else: self.platform = 'arm64' elif 'arm' in target_machine.lower(): self.platform = 'ARM' else: raise MesonException('Unsupported Visual Studio platform: ' + target_machine) build_machine = self.interpreter.builtin['build_machine'].cpu_family_method(None, None) if build_machine == '64' or build_machine == 'x86_64': # amd64 or x86_64 self.build_platform = 'x64' elif build_machine == 'x86': # x86 self.build_platform = 'Win32' elif build_machine == 'aarch64' or build_machine == 'arm64': target_cpu = self.interpreter.builtin['build_machine'].cpu_method(None, None) if target_cpu == 'arm64ec': self.build_platform = 'arm64ec' else: self.build_platform = 'arm64' elif 'arm' in build_machine.lower(): self.build_platform = 'ARM' else: raise MesonException('Unsupported Visual Studio platform: ' + build_machine) self.buildtype = self.environment.coredata.get_option(OptionKey('buildtype')) self.optimization = self.environment.coredata.get_option(OptionKey('optimization')) self.debug = self.environment.coredata.get_option(OptionKey('debug')) try: self.sanitize = self.environment.coredata.get_option(OptionKey('b_sanitize')) except MesonException: self.sanitize = 'none' sln_filename = os.path.join(self.environment.get_build_dir(), self.build.project_name + '.sln') projlist = self.generate_projects() self.gen_testproj('RUN_TESTS', os.path.join(self.environment.get_build_dir(), 'RUN_TESTS.vcxproj')) self.gen_installproj('RUN_INSTALL', os.path.join(self.environment.get_build_dir(), 'RUN_INSTALL.vcxproj')) self.gen_regenproj('REGEN', os.path.join(self.environment.get_build_dir(), 'REGEN.vcxproj')) self.generate_solution(sln_filename, projlist) self.generate_regen_info() Vs2010Backend.touch_regen_timestamp(self.environment.get_build_dir())
[ "def", "generate", "(", "self", ")", ":", "target_machine", "=", "self", ".", "interpreter", ".", "builtin", "[", "'target_machine'", "]", ".", "cpu_family_method", "(", "None", ",", "None", ")", "if", "target_machine", "==", "'64'", "or", "target_machine", ...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/backend/vs2010backend.py#L177-L228
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_adm_policy_user.py
python
OpenShiftCLI._run
(self, cmds, input_data)
return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
Actually executes the command. This makes mocking easier.
Actually executes the command. This makes mocking easier.
[ "Actually", "executes", "the", "command", ".", "This", "makes", "mocking", "easier", "." ]
def _run(self, cmds, input_data): ''' Actually executes the command. This makes mocking easier. ''' curr_env = os.environ.copy() curr_env.update({'KUBECONFIG': self.kubeconfig}) proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env) stdout, stderr = proc.communicate(input_data) return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
[ "def", "_run", "(", "self", ",", "cmds", ",", "input_data", ")", ":", "curr_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "curr_env", ".", "update", "(", "{", "'KUBECONFIG'", ":", "self", ".", "kubeconfig", "}", ")", "proc", "=", "subproces...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_adm_policy_user.py#L1117-L1129
BlackLight/platypush
a6b552504e2ac327c94f3a28b607061b6b60cf36
platypush/backend/http/app/routes/hook.py
python
_hook
(hook_name)
Endpoint for custom webhooks
Endpoint for custom webhooks
[ "Endpoint", "for", "custom", "webhooks" ]
def _hook(hook_name): """ Endpoint for custom webhooks """ event_args = { 'hook': hook_name, 'method': request.method, 'args': dict(request.args or {}), 'data': request.data.decode(), 'headers': dict(request.headers or {}), } if event_args['data']: # noinspection PyBroadException try: event_args['data'] = json.loads(event_args['data']) except Exception as e: logger().warning('Not a valid JSON string: {}: {}'.format(event_args['data'], str(e))) event = WebhookEvent(**event_args) try: send_message(event) return Response(json.dumps({'status': 'ok', **event_args}), mimetype='application/json') except Exception as e: logger().exception(e) logger().error('Error while dispatching webhook event {}: {}'.format(event, str(e))) abort(500, str(e))
[ "def", "_hook", "(", "hook_name", ")", ":", "event_args", "=", "{", "'hook'", ":", "hook_name", ",", "'method'", ":", "request", ".", "method", ",", "'args'", ":", "dict", "(", "request", ".", "args", "or", "{", "}", ")", ",", "'data'", ":", "request...
https://github.com/BlackLight/platypush/blob/a6b552504e2ac327c94f3a28b607061b6b60cf36/platypush/backend/http/app/routes/hook.py#L19-L45
translate/translate
72816df696b5263abfe80ab59129b299b85ae749
translate/storage/properties.py
python
xwikiunit.represents_missing
(cls, line)
return line.startswith(cls.get_missing_part())
Return true if the line represents a missing translation
Return true if the line represents a missing translation
[ "Return", "true", "if", "the", "line", "represents", "a", "missing", "translation" ]
def represents_missing(cls, line): """Return true if the line represents a missing translation""" return line.startswith(cls.get_missing_part())
[ "def", "represents_missing", "(", "cls", ",", "line", ")", ":", "return", "line", ".", "startswith", "(", "cls", ".", "get_missing_part", "(", ")", ")" ]
https://github.com/translate/translate/blob/72816df696b5263abfe80ab59129b299b85ae749/translate/storage/properties.py#L969-L971
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/studio/v1/flow/execution/execution_step/__init__.py
python
ExecutionStepList.page
(self, page_token=values.unset, page_number=values.unset, page_size=values.unset)
return ExecutionStepPage(self._version, response, self._solution)
Retrieve a single page of ExecutionStepInstance records from the API. Request is executed immediately :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of ExecutionStepInstance :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage
Retrieve a single page of ExecutionStepInstance records from the API. Request is executed immediately
[ "Retrieve", "a", "single", "page", "of", "ExecutionStepInstance", "records", "from", "the", "API", ".", "Request", "is", "executed", "immediately" ]
def page(self, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of ExecutionStepInstance records from the API. Request is executed immediately :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of ExecutionStepInstance :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage """ data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) response = self._version.page(method='GET', uri=self._uri, params=data, ) return ExecutionStepPage(self._version, response, self._solution)
[ "def", "page", "(", "self", ",", "page_token", "=", "values", ".", "unset", ",", "page_number", "=", "values", ".", "unset", ",", "page_size", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'PageToken'", ":", "pag...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py#L78-L95
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/gui/preferences/traypanel.py
python
TrayPanel.__createTrayGui
(self)
Создать элементы интерфейса, связанные с треем
Создать элементы интерфейса, связанные с треем
[ "Создать", "элементы", "интерфейса", "связанные", "с", "треем" ]
def __createTrayGui(self): """ Создать элементы интерфейса, связанные с треем """ self.minimizeCheckBox = wx.CheckBox( self, -1, _("Minimize to tray")) self.startIconizedCheckBox = wx.CheckBox( self, -1, _("Start iconized")) self.alwaysInTrayCheckBox = wx.CheckBox( self, -1, _("Always show tray icon")) self.minimizeOnCloseCheckBox = wx.CheckBox( self, -1, _("Minimize on close window"))
[ "def", "__createTrayGui", "(", "self", ")", ":", "self", ".", "minimizeCheckBox", "=", "wx", ".", "CheckBox", "(", "self", ",", "-", "1", ",", "_", "(", "\"Minimize to tray\"", ")", ")", "self", ".", "startIconizedCheckBox", "=", "wx", ".", "CheckBox", "...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/preferences/traypanel.py#L36-L58
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/coding/code_constructions.py
python
DuadicCodeEvenPair
(F,S1,S2)
return C1,C2
r""" Constructs the "even pair" of duadic codes associated to the "splitting" (see the docstring for ``_is_a_splitting`` for the definition) S1, S2 of n. .. warning:: Maybe the splitting should be associated to a sum of q-cyclotomic cosets mod n, where q is a *prime*. EXAMPLES:: sage: from sage.coding.code_constructions import _is_a_splitting sage: n = 11; q = 3 sage: C = Zmod(n).cyclotomic_cosets(q); C [[0], [1, 3, 4, 5, 9], [2, 6, 7, 8, 10]] sage: S1 = C[1] sage: S2 = C[2] sage: _is_a_splitting(S1,S2,11) True sage: codes.DuadicCodeEvenPair(GF(q),S1,S2) ([11, 5] Cyclic Code over GF(3), [11, 5] Cyclic Code over GF(3))
r""" Constructs the "even pair" of duadic codes associated to the "splitting" (see the docstring for ``_is_a_splitting`` for the definition) S1, S2 of n.
[ "r", "Constructs", "the", "even", "pair", "of", "duadic", "codes", "associated", "to", "the", "splitting", "(", "see", "the", "docstring", "for", "_is_a_splitting", "for", "the", "definition", ")", "S1", "S2", "of", "n", "." ]
def DuadicCodeEvenPair(F,S1,S2): r""" Constructs the "even pair" of duadic codes associated to the "splitting" (see the docstring for ``_is_a_splitting`` for the definition) S1, S2 of n. .. warning:: Maybe the splitting should be associated to a sum of q-cyclotomic cosets mod n, where q is a *prime*. EXAMPLES:: sage: from sage.coding.code_constructions import _is_a_splitting sage: n = 11; q = 3 sage: C = Zmod(n).cyclotomic_cosets(q); C [[0], [1, 3, 4, 5, 9], [2, 6, 7, 8, 10]] sage: S1 = C[1] sage: S2 = C[2] sage: _is_a_splitting(S1,S2,11) True sage: codes.DuadicCodeEvenPair(GF(q),S1,S2) ([11, 5] Cyclic Code over GF(3), [11, 5] Cyclic Code over GF(3)) """ from sage.misc.stopgap import stopgap stopgap("The function DuadicCodeEvenPair has several issues which may cause wrong results", 25896) from .cyclic_code import CyclicCode n = len(S1) + len(S2) + 1 if not _is_a_splitting(S1,S2,n): raise TypeError("%s, %s must be a splitting of %s."%(S1,S2,n)) q = F.order() k = Mod(q,n).multiplicative_order() FF = GF(q**k,"z") z = FF.gen() zeta = z**((q**k-1)/n) P1 = PolynomialRing(FF,"x") x = P1.gen() g1 = prod([x-zeta**i for i in S1+[0]]) g2 = prod([x-zeta**i for i in S2+[0]]) P2 = PolynomialRing(F,"x") x = P2.gen() gg1 = P2([_lift2smallest_field(c)[0] for c in g1.coefficients(sparse=False)]) gg2 = P2([_lift2smallest_field(c)[0] for c in g2.coefficients(sparse=False)]) C1 = CyclicCode(length = n, generator_pol = gg1) C2 = CyclicCode(length = n, generator_pol = gg2) return C1,C2
[ "def", "DuadicCodeEvenPair", "(", "F", ",", "S1", ",", "S2", ")", ":", "from", "sage", ".", "misc", ".", "stopgap", "import", "stopgap", "stopgap", "(", "\"The function DuadicCodeEvenPair has several issues which may cause wrong results\"", ",", "25896", ")", "from", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/coding/code_constructions.py#L328-L375
ArangoDB-Community/pyArango
57eba567b32c5c8d57b4322599e4a32cbd68d025
pyArango/action.py
python
ConnectionAction.patch
(self, url, data=None, **kwargs)
return self.session.patch(action_url, data, **kwargs)
HTTP PATCH Method.
HTTP PATCH Method.
[ "HTTP", "PATCH", "Method", "." ]
def patch(self, url, data=None, **kwargs): """HTTP PATCH Method.""" action_url = '%s%s' % (self.end_point_url, url) return self.session.patch(action_url, data, **kwargs)
[ "def", "patch", "(", "self", ",", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "action_url", "=", "'%s%s'", "%", "(", "self", ".", "end_point_url", ",", "url", ")", "return", "self", ".", "session", ".", "patch", "(", "action...
https://github.com/ArangoDB-Community/pyArango/blob/57eba567b32c5c8d57b4322599e4a32cbd68d025/pyArango/action.py#L47-L50
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/projects/assemblenet/modeling/assemblenet_plus.py
python
_ApplyEdgeWeight.__init__
(self, weights_shape, index: Optional[int] = None, use_5d_mode: bool = False, model_edge_weights: Optional[List[Any]] = None, num_object_classes: Optional[int] = None, **kwargs)
Constructor. Args: weights_shape: A list of intergers. Each element means number of edges. index: `int` index of the block within the AssembleNet architecture. Used for summation weight initial loading. use_5d_mode: `bool` indicating whether the inputs are in 5D tensor or 4D. model_edge_weights: AssembleNet++ model structure connection weights in the string format. num_object_classes: Assemblenet++ structure used object inputs so we should use what dataset classes you might be use (e.g. ADE-20k 151 classes) **kwargs: pass through arguments. Returns: The output `Tensor` after concatenation.
Constructor.
[ "Constructor", "." ]
def __init__(self, weights_shape, index: Optional[int] = None, use_5d_mode: bool = False, model_edge_weights: Optional[List[Any]] = None, num_object_classes: Optional[int] = None, **kwargs): """Constructor. Args: weights_shape: A list of intergers. Each element means number of edges. index: `int` index of the block within the AssembleNet architecture. Used for summation weight initial loading. use_5d_mode: `bool` indicating whether the inputs are in 5D tensor or 4D. model_edge_weights: AssembleNet++ model structure connection weights in the string format. num_object_classes: Assemblenet++ structure used object inputs so we should use what dataset classes you might be use (e.g. ADE-20k 151 classes) **kwargs: pass through arguments. Returns: The output `Tensor` after concatenation. """ super(_ApplyEdgeWeight, self).__init__(**kwargs) self._weights_shape = weights_shape self._index = index self._use_5d_mode = use_5d_mode self._model_edge_weights = model_edge_weights self._num_object_classes = num_object_classes data_format = tf.keras.backend.image_data_format() assert data_format == 'channels_last'
[ "def", "__init__", "(", "self", ",", "weights_shape", ",", "index", ":", "Optional", "[", "int", "]", "=", "None", ",", "use_5d_mode", ":", "bool", "=", "False", ",", "model_edge_weights", ":", "Optional", "[", "List", "[", "Any", "]", "]", "=", "None"...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/projects/assemblenet/modeling/assemblenet_plus.py#L151-L184
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/bs4/builder/_lxml.py
python
LXMLTreeBuilderForXML._register_namespaces
(self, mapping)
Let the BeautifulSoup object know about namespaces encountered while parsing the document. This might be useful later on when creating CSS selectors.
Let the BeautifulSoup object know about namespaces encountered while parsing the document.
[ "Let", "the", "BeautifulSoup", "object", "know", "about", "namespaces", "encountered", "while", "parsing", "the", "document", "." ]
def _register_namespaces(self, mapping): """Let the BeautifulSoup object know about namespaces encountered while parsing the document. This might be useful later on when creating CSS selectors. """ for key, value in mapping.items(): if key and key not in self.soup._namespaces: # Let the BeautifulSoup object know about a new namespace. # If there are multiple namespaces defined with the same # prefix, the first one in the document takes precedence. self.soup._namespaces[key] = value
[ "def", "_register_namespaces", "(", "self", ",", "mapping", ")", ":", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", ":", "if", "key", "and", "key", "not", "in", "self", ".", "soup", ".", "_namespaces", ":", "# Let the BeautifulSoup...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/bs4/builder/_lxml.py#L67-L78
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_darwin/systrace/catapult/third_party/pyserial/serial/tools/miniterm.py
python
Miniterm._start_reader
(self)
Start reader thread
Start reader thread
[ "Start", "reader", "thread" ]
def _start_reader(self): """Start reader thread""" self._reader_alive = True # start serial->console thread self.receiver_thread = threading.Thread(target=self.reader) self.receiver_thread.setDaemon(True) self.receiver_thread.start()
[ "def", "_start_reader", "(", "self", ")", ":", "self", ".", "_reader_alive", "=", "True", "# start serial->console thread", "self", ".", "receiver_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "reader", ")", "self", ".", "receiver_...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_darwin/systrace/catapult/third_party/pyserial/serial/tools/miniterm.py#L184-L190
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/contrib/plural_rules/fr.py
python
construct_plural_form
(word, plural_id)
return word + 's'
u""" >>> [construct_plural_form(x, 1) for x in \ [ 'bleu', 'nez', 'sex', 'bas', 'gruau', 'jeu', 'journal',\ 'chose' ]] ['bleus', 'nez', 'sex', 'bas', 'gruaux', 'jeux', 'journaux', 'choses']
u""" >>> [construct_plural_form(x, 1) for x in \ [ 'bleu', 'nez', 'sex', 'bas', 'gruau', 'jeu', 'journal',\ 'chose' ]] ['bleus', 'nez', 'sex', 'bas', 'gruaux', 'jeux', 'journaux', 'choses']
[ "u", ">>>", "[", "construct_plural_form", "(", "x", "1", ")", "for", "x", "in", "\\", "[", "bleu", "nez", "sex", "bas", "gruau", "jeu", "journal", "\\", "chose", "]]", "[", "bleus", "nez", "sex", "bas", "gruaux", "jeux", "journaux", "choses", "]" ]
def construct_plural_form(word, plural_id): u""" >>> [construct_plural_form(x, 1) for x in \ [ 'bleu', 'nez', 'sex', 'bas', 'gruau', 'jeu', 'journal',\ 'chose' ]] ['bleus', 'nez', 'sex', 'bas', 'gruaux', 'jeux', 'journaux', 'choses'] """ if word in irregular: return irregular[word] if word[-1:] in ('s', 'x', 'z'): return word if word[-2:] in ('au', 'eu'): return word + 'x' if word[-2:] == 'al': return word[0:-2] + 'aux' return word + 's'
[ "def", "construct_plural_form", "(", "word", ",", "plural_id", ")", ":", "if", "word", "in", "irregular", ":", "return", "irregular", "[", "word", "]", "if", "word", "[", "-", "1", ":", "]", "in", "(", "'s'", ",", "'x'", ",", "'z'", ")", ":", "retu...
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/contrib/plural_rules/fr.py#L50-L65
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/sdb/connection.py
python
SDBConnection.create_domain
(self, domain_name)
return d
Create a SimpleDB domain. :type domain_name: string :param domain_name: The name of the new domain :rtype: :class:`boto.sdb.domain.Domain` object :return: The newly created domain
Create a SimpleDB domain.
[ "Create", "a", "SimpleDB", "domain", "." ]
def create_domain(self, domain_name): """ Create a SimpleDB domain. :type domain_name: string :param domain_name: The name of the new domain :rtype: :class:`boto.sdb.domain.Domain` object :return: The newly created domain """ params = {'DomainName': domain_name} d = self.get_object('CreateDomain', params, Domain) d.name = domain_name return d
[ "def", "create_domain", "(", "self", ",", "domain_name", ")", ":", "params", "=", "{", "'DomainName'", ":", "domain_name", "}", "d", "=", "self", ".", "get_object", "(", "'CreateDomain'", ",", "params", ",", "Domain", ")", "d", ".", "name", "=", "domain_...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/sdb/connection.py#L310-L323
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/python-3.7.2-embed-win32/Crypto/Util/_raw_api.py
python
load_pycryptodome_raw_lib
(name, cdecl)
Load a shared library and return a handle to it. @name, the name of the library expressed as a PyCryptodome module, for instance Crypto.Cipher._raw_cbc. @cdecl, the C function declarations.
Load a shared library and return a handle to it.
[ "Load", "a", "shared", "library", "and", "return", "a", "handle", "to", "it", "." ]
def load_pycryptodome_raw_lib(name, cdecl): """Load a shared library and return a handle to it. @name, the name of the library expressed as a PyCryptodome module, for instance Crypto.Cipher._raw_cbc. @cdecl, the C function declarations. """ split = name.split(".") dir_comps, basename = split[:-1], split[-1] attempts = [] for ext in extension_suffixes: try: filename = basename + ext return load_lib(pycryptodome_filename(dir_comps, filename), cdecl) except OSError as exp: attempts.append("Trying '%s': %s" % (filename, str(exp))) raise OSError("Cannot load native module '%s': %s" % (name, ", ".join(attempts)))
[ "def", "load_pycryptodome_raw_lib", "(", "name", ",", "cdecl", ")", ":", "split", "=", "name", ".", "split", "(", "\".\"", ")", "dir_comps", ",", "basename", "=", "split", "[", ":", "-", "1", "]", ",", "split", "[", "-", "1", "]", "attempts", "=", ...
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/python-3.7.2-embed-win32/Crypto/Util/_raw_api.py#L239-L258
KenT2/pipresents-gapless
31a347bb8b45898a3fe08b1daf765e31d47b7a87
remi/gui.py
python
FileUploader.set_on_data_listener
(self, callback, *userdata)
Register the listener for the ondata event. Note: the listener prototype have to be in the form on_fileupload_data(self, widget, filedata, filename), where filedata is the bytearray chunk.
Register the listener for the ondata event.
[ "Register", "the", "listener", "for", "the", "ondata", "event", "." ]
def set_on_data_listener(self, callback, *userdata): """Register the listener for the ondata event. Note: the listener prototype have to be in the form on_fileupload_data(self, widget, filedata, filename), where filedata is the bytearray chunk. """ self.eventManager.register_listener(self.EVENT_ON_DATA, callback, *userdata)
[ "def", "set_on_data_listener", "(", "self", ",", "callback", ",", "*", "userdata", ")", ":", "self", ".", "eventManager", ".", "register_listener", "(", "self", ".", "EVENT_ON_DATA", ",", "callback", ",", "*", "userdata", ")" ]
https://github.com/KenT2/pipresents-gapless/blob/31a347bb8b45898a3fe08b1daf765e31d47b7a87/remi/gui.py#L2480-L2486
JDASoftwareGroup/kartothek
1821ea5df60d4079d3911b3c2f17be11d8780e22
kartothek/api/consistency.py
python
_check_dimension_columns
(datasets: Dict[str, DatasetMetadata], cube: Cube)
Check if required dimension are present in given datasets. For the seed dataset all dimension columns must be present. For all other datasets at least 1 dimension column must be present. Parameters ---------- datasets Datasets. cube Cube specification. Raises ------ ValueError: In case dimension columns are broken.
Check if required dimension are present in given datasets.
[ "Check", "if", "required", "dimension", "are", "present", "in", "given", "datasets", "." ]
def _check_dimension_columns(datasets: Dict[str, DatasetMetadata], cube: Cube) -> None: """ Check if required dimension are present in given datasets. For the seed dataset all dimension columns must be present. For all other datasets at least 1 dimension column must be present. Parameters ---------- datasets Datasets. cube Cube specification. Raises ------ ValueError: In case dimension columns are broken. """ for ktk_cube_dataset_id in sorted(datasets.keys()): ds = datasets[ktk_cube_dataset_id] columns = get_dataset_columns(ds) if ktk_cube_dataset_id == cube.seed_dataset: missing = set(cube.dimension_columns) - columns if missing: raise ValueError( 'Seed dataset "{ktk_cube_dataset_id}" has missing dimension columns: {missing}'.format( ktk_cube_dataset_id=ktk_cube_dataset_id, missing=", ".join(sorted(missing)), ) ) else: present = set(cube.dimension_columns) & columns if len(present) == 0: raise ValueError( ( 'Dataset "{ktk_cube_dataset_id}" must have at least 1 of the following dimension columns: ' "{dims}" ).format( ktk_cube_dataset_id=ktk_cube_dataset_id, dims=", ".join(cube.dimension_columns), ) )
[ "def", "_check_dimension_columns", "(", "datasets", ":", "Dict", "[", "str", ",", "DatasetMetadata", "]", ",", "cube", ":", "Cube", ")", "->", "None", ":", "for", "ktk_cube_dataset_id", "in", "sorted", "(", "datasets", ".", "keys", "(", ")", ")", ":", "d...
https://github.com/JDASoftwareGroup/kartothek/blob/1821ea5df60d4079d3911b3c2f17be11d8780e22/kartothek/api/consistency.py#L110-L151
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/_pydecimal.py
python
Context.Etop
(self)
return int(self.Emax - self.prec + 1)
Returns maximum exponent (= Emax - prec + 1)
Returns maximum exponent (= Emax - prec + 1)
[ "Returns", "maximum", "exponent", "(", "=", "Emax", "-", "prec", "+", "1", ")" ]
def Etop(self): """Returns maximum exponent (= Emax - prec + 1)""" return int(self.Emax - self.prec + 1)
[ "def", "Etop", "(", "self", ")", ":", "return", "int", "(", "self", ".", "Emax", "-", "self", ".", "prec", "+", "1", ")" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/_pydecimal.py#L4067-L4069
astropy/astroquery
11c9c83fa8e5f948822f8f73c854ec4b72043016
astroquery/utils/tap/model/taptable.py
python
TapTableMeta.__str__
(self)
return f"TAP Table name: {self.get_qualified_name()}" \ f"\nDescription: {self.description}" \ f"\nNum. columns: {len(self.columns)}"
[]
def __str__(self): return f"TAP Table name: {self.get_qualified_name()}" \ f"\nDescription: {self.description}" \ f"\nNum. columns: {len(self.columns)}"
[ "def", "__str__", "(", "self", ")", ":", "return", "f\"TAP Table name: {self.get_qualified_name()}\"", "f\"\\nDescription: {self.description}\"", "f\"\\nNum. columns: {len(self.columns)}\"" ]
https://github.com/astropy/astroquery/blob/11c9c83fa8e5f948822f8f73c854ec4b72043016/astroquery/utils/tap/model/taptable.py#L50-L53
qiime2/qiime2
3906f67c70a1321e99e7fc59e79550c2432a8cee
qiime2/metadata/metadata.py
python
Metadata.column_count
(self)
return len(self._columns)
Number of metadata columns. This property is read-only. Returns ------- int Number of metadata columns. Notes ----- Zero metadata columns are allowed. See Also -------- id_count
Number of metadata columns.
[ "Number", "of", "metadata", "columns", "." ]
def column_count(self): """Number of metadata columns. This property is read-only. Returns ------- int Number of metadata columns. Notes ----- Zero metadata columns are allowed. See Also -------- id_count """ return len(self._columns)
[ "def", "column_count", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_columns", ")" ]
https://github.com/qiime2/qiime2/blob/3906f67c70a1321e99e7fc59e79550c2432a8cee/qiime2/metadata/metadata.py#L378-L397
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/ceilometer/ceilometer/storage/models.py
python
ResourceMeter.__init__
(self, counter_name, counter_type, counter_unit)
Create a new resource meter. :param counter_name: the name of the counter updating the resource :param counter_type: one of gauge, delta, cumulative :param counter_unit: official units name for the sample data
Create a new resource meter.
[ "Create", "a", "new", "resource", "meter", "." ]
def __init__(self, counter_name, counter_type, counter_unit): """Create a new resource meter. :param counter_name: the name of the counter updating the resource :param counter_type: one of gauge, delta, cumulative :param counter_unit: official units name for the sample data """ Model.__init__(self, counter_name=counter_name, counter_type=counter_type, counter_unit=counter_unit, )
[ "def", "__init__", "(", "self", ",", "counter_name", ",", "counter_type", ",", "counter_unit", ")", ":", "Model", ".", "__init__", "(", "self", ",", "counter_name", "=", "counter_name", ",", "counter_type", "=", "counter_type", ",", "counter_unit", "=", "count...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/ceilometer/ceilometer/storage/models.py#L119-L130
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/_posixserialport.py
python
SerialPort.connectionLost
(self, reason)
Called when the serial port disconnects. Will call C{connectionLost} on the protocol that is handling the serial data.
Called when the serial port disconnects.
[ "Called", "when", "the", "serial", "port", "disconnects", "." ]
def connectionLost(self, reason): """ Called when the serial port disconnects. Will call C{connectionLost} on the protocol that is handling the serial data. """ abstract.FileDescriptor.connectionLost(self, reason) self._serial.close() self.protocol.connectionLost(reason)
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "abstract", ".", "FileDescriptor", ".", "connectionLost", "(", "self", ",", "reason", ")", "self", ".", "_serial", ".", "close", "(", ")", "self", ".", "protocol", ".", "connectionLost", "(", ...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/_posixserialport.py#L64-L73
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
addon_common/common/blender.py
python
ModifierWrapper_Mirror.write
(self)
[]
def write(self): if self._reading: return self.mod.use_x = self.x self.mod.use_y = self.y self.mod.use_z = self.z self.mod.merge_threshold = self._symmetry_threshold self.mod.show_viewport = self.show_viewport
[ "def", "write", "(", "self", ")", ":", "if", "self", ".", "_reading", ":", "return", "self", ".", "mod", ".", "use_x", "=", "self", ".", "x", "self", ".", "mod", ".", "use_y", "=", "self", ".", "y", "self", ".", "mod", ".", "use_z", "=", "self"...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/addon_common/common/blender.py#L166-L172
cool-RR/python_toolbox
cb9ef64b48f1d03275484d707dc5079b6701ad0c
python_toolbox/combi/chain_space.py
python
ChainSpace.index
(self, item)
Get the index number of `item` in this space.
Get the index number of `item` in this space.
[ "Get", "the", "index", "number", "of", "item", "in", "this", "space", "." ]
def index(self, item): '''Get the index number of `item` in this space.''' for sequence, accumulated_length in zip(self.sequences, self.accumulated_lengths): try: index_in_sequence = sequence.index(item) except ValueError: pass except TypeError: assert isinstance(sequence, (str, bytes)) and \ (not isinstance(item, (str, bytes))) else: return index_in_sequence + accumulated_length else: raise ValueError
[ "def", "index", "(", "self", ",", "item", ")", ":", "for", "sequence", ",", "accumulated_length", "in", "zip", "(", "self", ".", "sequences", ",", "self", ".", "accumulated_lengths", ")", ":", "try", ":", "index_in_sequence", "=", "sequence", ".", "index",...
https://github.com/cool-RR/python_toolbox/blob/cb9ef64b48f1d03275484d707dc5079b6701ad0c/python_toolbox/combi/chain_space.py#L103-L117
LinuxCNC/simple-gcode-generators
d06c2750fe03c41becd6bd5863ace54b52920155
face/face.py
python
Application.SelectAllText
(self)
[]
def SelectAllText(self): self.g_code.tag_add(SEL, '1.0', END)
[ "def", "SelectAllText", "(", "self", ")", ":", "self", ".", "g_code", ".", "tag_add", "(", "SEL", ",", "'1.0'", ",", "END", ")" ]
https://github.com/LinuxCNC/simple-gcode-generators/blob/d06c2750fe03c41becd6bd5863ace54b52920155/face/face.py#L427-L428
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/setuptools/command/bdist_egg.py
python
bdist_egg.call_command
(self, cmdname, **kw)
return cmd
Invoke reinitialized command `cmdname` with keyword args
Invoke reinitialized command `cmdname` with keyword args
[ "Invoke", "reinitialized", "command", "cmdname", "with", "keyword", "args" ]
def call_command(self, cmdname, **kw): """Invoke reinitialized command `cmdname` with keyword args""" for dirname in INSTALL_DIRECTORY_ATTRS: kw.setdefault(dirname, self.bdist_dir) kw.setdefault('skip_build', self.skip_build) kw.setdefault('dry_run', self.dry_run) cmd = self.reinitialize_command(cmdname, **kw) self.run_command(cmdname) return cmd
[ "def", "call_command", "(", "self", ",", "cmdname", ",", "*", "*", "kw", ")", ":", "for", "dirname", "in", "INSTALL_DIRECTORY_ATTRS", ":", "kw", ".", "setdefault", "(", "dirname", ",", "self", ".", "bdist_dir", ")", "kw", ".", "setdefault", "(", "'skip_b...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/setuptools/command/bdist_egg.py#L139-L147
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/intctrl.py
python
IntCtrl.IsInBounds
(self, value=None)
Returns True if no value is specified and the current value of the control falls within the current bounds. This function can also be called with a value to see if that value would fall within the current bounds of the given control. :param int `value`: value to check or None
Returns True if no value is specified and the current value of the control falls within the current bounds. This function can also be called with a value to see if that value would fall within the current bounds of the given control.
[ "Returns", "True", "if", "no", "value", "is", "specified", "and", "the", "current", "value", "of", "the", "control", "falls", "within", "the", "current", "bounds", ".", "This", "function", "can", "also", "be", "called", "with", "a", "value", "to", "see", ...
def IsInBounds(self, value=None): """ Returns True if no value is specified and the current value of the control falls within the current bounds. This function can also be called with a value to see if that value would fall within the current bounds of the given control. :param int `value`: value to check or None """ if value is None: value = self.GetValue() if( not (value is None and self.IsNoneAllowed()) and type(value) not in six.integer_types ): raise ValueError ( 'IntCtrl requires integer values, passed %s'% repr(value) ) min = self.GetMin() max = self.GetMax() if min is None: min = value if max is None: max = value # if bounds set, and value is None, return False if value is None and (min is not None or max is not None): return 0 else: return min <= value <= max
[ "def", "IsInBounds", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "self", ".", "GetValue", "(", ")", "if", "(", "not", "(", "value", "is", "None", "and", "self", ".", "IsNoneAllowed", "(", ")", ...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/intctrl.py#L697-L724
wummel/linkchecker
c2ce810c3fb00b895a841a7be6b2e78c64e7b042
third_party/dnspython/dns/rdtypes/ANY/RRSIG.py
python
RRSIG.choose_relativity
(self, origin = None, relativize = True)
[]
def choose_relativity(self, origin = None, relativize = True): self.signer = self.signer.choose_relativity(origin, relativize)
[ "def", "choose_relativity", "(", "self", ",", "origin", "=", "None", ",", "relativize", "=", "True", ")", ":", "self", ".", "signer", "=", "self", ".", "signer", ".", "choose_relativity", "(", "origin", ",", "relativize", ")" ]
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/rdtypes/ANY/RRSIG.py#L151-L152
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
plugin.video.online.anidub.com/BeautifulSoup.py
python
Tag.__ne__
(self, other)
return not self == other
Returns true iff this tag is not identical to the other tag, as defined in __eq__.
Returns true iff this tag is not identical to the other tag, as defined in __eq__.
[ "Returns", "true", "iff", "this", "tag", "is", "not", "identical", "to", "the", "other", "tag", "as", "defined", "in", "__eq__", "." ]
def __ne__(self, other): """Returns true iff this tag is not identical to the other tag, as defined in __eq__.""" return not self == other
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "self", "==", "other" ]
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/plugin.video.online.anidub.com/BeautifulSoup.py#L672-L675
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/analytics/client.py
python
GoalQuery.path
(self)
return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties' '/%s/profiles/%s/goals' % (self.acct_id, self.web_prop_id, self.profile_id))
Wrapper for path attribute.
Wrapper for path attribute.
[ "Wrapper", "for", "path", "attribute", "." ]
def path(self): """Wrapper for path attribute.""" return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties' '/%s/profiles/%s/goals' % (self.acct_id, self.web_prop_id, self.profile_id))
[ "def", "path", "(", "self", ")", ":", "return", "(", "'/analytics/feeds/datasources/ga/accounts/%s/webproperties'", "'/%s/profiles/%s/goals'", "%", "(", "self", ".", "acct_id", ",", "self", ".", "web_prop_id", ",", "self", ".", "profile_id", ")", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/analytics/client.py#L288-L292
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/modsym/ambient.py
python
ModularSymbolsAmbient_wtk_g0._hecke_images
(self, i, v)
return heilbronn.hecke_images_gamma0_weight_k(c.u,c.v, c.i, N, self.weight(), v, self.manin_gens_to_basis())
Return matrix whose rows are the images of the `i`-th standard basis vector under the Hecke operators `T_p` for all integers in `v`. INPUT: - ``i`` - nonnegative integer - ``v`` - a list of positive integer OUTPUT: - ``matrix`` - whose rows are the Hecke images EXAMPLES:: sage: M = ModularSymbols(11,4,1) sage: mat = M._hecke_images(0,[1,2,3,4]) sage: M.T(1)(M.0).element() == mat[0] True sage: M.T(2)(M.0).element() == mat[1] True sage: M.T(3)(M.0).element() == mat[2] True sage: M.T(4)(M.0).element() == mat[3] True sage: M = ModularSymbols(12,4) sage: mat = M._hecke_images(0,[1,2,3,4]) sage: M.T(1)(M.0).element() == mat[0] True sage: M.T(2)(M.0).element() == mat[1] True sage: M.T(3)(M.0).element() == mat[2] True sage: M.T(4)(M.0).element() == mat[3] True
Return matrix whose rows are the images of the `i`-th standard basis vector under the Hecke operators `T_p` for all integers in `v`.
[ "Return", "matrix", "whose", "rows", "are", "the", "images", "of", "the", "i", "-", "th", "standard", "basis", "vector", "under", "the", "Hecke", "operators", "T_p", "for", "all", "integers", "in", "v", "." ]
def _hecke_images(self, i, v): """ Return matrix whose rows are the images of the `i`-th standard basis vector under the Hecke operators `T_p` for all integers in `v`. INPUT: - ``i`` - nonnegative integer - ``v`` - a list of positive integer OUTPUT: - ``matrix`` - whose rows are the Hecke images EXAMPLES:: sage: M = ModularSymbols(11,4,1) sage: mat = M._hecke_images(0,[1,2,3,4]) sage: M.T(1)(M.0).element() == mat[0] True sage: M.T(2)(M.0).element() == mat[1] True sage: M.T(3)(M.0).element() == mat[2] True sage: M.T(4)(M.0).element() == mat[3] True sage: M = ModularSymbols(12,4) sage: mat = M._hecke_images(0,[1,2,3,4]) sage: M.T(1)(M.0).element() == mat[0] True sage: M.T(2)(M.0).element() == mat[1] True sage: M.T(3)(M.0).element() == mat[2] True sage: M.T(4)(M.0).element() == mat[3] True """ # Find basis vector for ambient space such that it is not in # the kernel of the dual space corresponding to self. c = self.manin_generators()[self.manin_basis()[i]] N = self.level() return heilbronn.hecke_images_gamma0_weight_k(c.u,c.v, c.i, N, self.weight(), v, self.manin_gens_to_basis())
[ "def", "_hecke_images", "(", "self", ",", "i", ",", "v", ")", ":", "# Find basis vector for ambient space such that it is not in", "# the kernel of the dual space corresponding to self.", "c", "=", "self", ".", "manin_generators", "(", ")", "[", "self", ".", "manin_basis"...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modsym/ambient.py#L2797-L2844
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/sim_type.py
python
SimTypeFunction._with_arch
(self, arch)
return out
[]
def _with_arch(self, arch): out = SimTypeFunction([a.with_arch(arch) for a in self.args], self.returnty.with_arch(arch) if self.returnty is not None else None, label=self.label, arg_names=self.arg_names, variadic=self.variadic ) out._arch = arch return out
[ "def", "_with_arch", "(", "self", ",", "arch", ")", ":", "out", "=", "SimTypeFunction", "(", "[", "a", ".", "with_arch", "(", "arch", ")", "for", "a", "in", "self", ".", "args", "]", ",", "self", ".", "returnty", ".", "with_arch", "(", "arch", ")",...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/sim_type.py#L889-L897
mherrmann/fbs
8ed25c1c8120597691f142f93571ffdcfda24f22
fbs/builtin_commands/__init__.py
python
test
()
Execute your automated tests
Execute your automated tests
[ "Execute", "your", "automated", "tests" ]
def test(): """ Execute your automated tests """ require_existing_project() sys.path.append(path('src/main/python')) suite = TestSuite() test_dirs = SETTINGS['test_dirs'] for test_dir in map(path, test_dirs): sys.path.append(test_dir) try: dir_names = listdir(test_dir) except FileNotFoundError: continue for dir_name in dir_names: dir_path = join(test_dir, dir_name) if isfile(join(dir_path, '__init__.py')): suite.addTest(defaultTestLoader.discover( dir_name, top_level_dir=test_dir )) has_tests = bool(list(suite)) if has_tests: TextTestRunner().run(suite) else: _LOG.warning( 'No tests found. You can add them to:\n * '+ '\n * '.join(test_dirs) )
[ "def", "test", "(", ")", ":", "require_existing_project", "(", ")", "sys", ".", "path", ".", "append", "(", "path", "(", "'src/main/python'", ")", ")", "suite", "=", "TestSuite", "(", ")", "test_dirs", "=", "SETTINGS", "[", "'test_dirs'", "]", "for", "te...
https://github.com/mherrmann/fbs/blob/8ed25c1c8120597691f142f93571ffdcfda24f22/fbs/builtin_commands/__init__.py#L463-L490
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/query/nested.py
python
NestedParent.requires
(self)
return self.child.requires()
[]
def requires(self): return self.child.requires()
[ "def", "requires", "(", "self", ")", ":", "return", "self", ".", "child", ".", "requires", "(", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/query/nested.py#L105-L106
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/pythagorastreeviewer.py
python
InteractiveSquareGraphicsItem.__init__
(self, tree_node, parent=None, **kwargs)
[]
def __init__(self, tree_node, parent=None, **kwargs): super().__init__(tree_node, parent, **kwargs) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.initial_zvalue = self.zValue() # The max z value changes if any item is selected self.any_selected = False self.timer.setSingleShot(True)
[ "def", "__init__", "(", "self", ",", "tree_node", ",", "parent", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "tree_node", ",", "parent", ",", "*", "*", "kwargs", ")", "self", ".", "setFlag", "(", "QGraph...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/pythagorastreeviewer.py#L390-L398
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/tornado/web.py
python
RequestHandler.render_linked_js
(self, js_files)
return ''.join('<script src="' + escape.xhtml_escape(p) + '" type="text/javascript"></script>' for p in paths)
Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output.
Default method used to render the final js links for the rendered webpage.
[ "Default", "method", "used", "to", "render", "the", "final", "js", "links", "for", "the", "rendered", "webpage", "." ]
def render_linked_js(self, js_files): """Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() for path in js_files: if not is_absolute(path): path = self.static_url(path) if path not in unique_paths: paths.append(path) unique_paths.add(path) return ''.join('<script src="' + escape.xhtml_escape(p) + '" type="text/javascript"></script>' for p in paths)
[ "def", "render_linked_js", "(", "self", ",", "js_files", ")", ":", "paths", "=", "[", "]", "unique_paths", "=", "set", "(", ")", "for", "path", "in", "js_files", ":", "if", "not", "is_absolute", "(", "path", ")", ":", "path", "=", "self", ".", "stati...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/tornado/web.py#L826-L844
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/rebulk/match.py
python
_BaseMatches.conflicting
(self, match, predicate=None, index=None)
return filter_index(ret, predicate, index)
Retrieves a list of ``Match`` objects that conflicts with given match. :param match: :type match: :param predicate: :type predicate: :param index: :type index: :return: :rtype:
Retrieves a list of ``Match`` objects that conflicts with given match. :param match: :type match: :param predicate: :type predicate: :param index: :type index: :return: :rtype:
[ "Retrieves", "a", "list", "of", "Match", "objects", "that", "conflicts", "with", "given", "match", ".", ":", "param", "match", ":", ":", "type", "match", ":", ":", "param", "predicate", ":", ":", "type", "predicate", ":", ":", "param", "index", ":", ":...
def conflicting(self, match, predicate=None, index=None): """ Retrieves a list of ``Match`` objects that conflicts with given match. :param match: :type match: :param predicate: :type predicate: :param index: :type index: :return: :rtype: """ ret = _BaseMatches._base() for i in range(*match.span): for at_match in self.at_index(i): if at_match not in ret: ret.append(at_match) ret.remove(match) return filter_index(ret, predicate, index)
[ "def", "conflicting", "(", "self", ",", "match", ",", "predicate", "=", "None", ",", "index", "=", "None", ")", ":", "ret", "=", "_BaseMatches", ".", "_base", "(", ")", "for", "i", "in", "range", "(", "*", "match", ".", "span", ")", ":", "for", "...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/rebulk/match.py#L435-L456
kpreid/shinysdr
25022d36903ff67e036e82a22b6555a12a4d8e8a
shinysdr/i/depgraph.py
python
_RepeatingAsyncTask.__async_finish
(self)
Clean up after the async task.
Clean up after the async task.
[ "Clean", "up", "after", "the", "async", "task", "." ]
def __async_finish(self): """Clean up after the async task.""" # print 'async_finish' self.__running_deferred = None self.__maybe_run()
[ "def", "__async_finish", "(", "self", ")", ":", "# print 'async_finish'", "self", ".", "__running_deferred", "=", "None", "self", ".", "__maybe_run", "(", ")" ]
https://github.com/kpreid/shinysdr/blob/25022d36903ff67e036e82a22b6555a12a4d8e8a/shinysdr/i/depgraph.py#L339-L343
DIYer22/boxx
d271bc375a33e01e616a0f74ce028e6d77d1820e
boxx/ylsys.py
python
SystemInfo.ip_by_target_ip
(target_ip="8.8.8.8")
return [ (s.connect((target_ip, 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]
[]
def ip_by_target_ip(target_ip="8.8.8.8"): import socket return [ (s.connect((target_ip, 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]
[ "def", "ip_by_target_ip", "(", "target_ip", "=", "\"8.8.8.8\"", ")", ":", "import", "socket", "return", "[", "(", "s", ".", "connect", "(", "(", "target_ip", ",", "80", ")", ")", ",", "s", ".", "getsockname", "(", ")", "[", "0", "]", ",", "s", ".",...
https://github.com/DIYer22/boxx/blob/d271bc375a33e01e616a0f74ce028e6d77d1820e/boxx/ylsys.py#L141-L147
crossbario/crossbar
ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64
crossbar/master/cluster/webcluster.py
python
WebClusterManager.get_webcluster_service
(self, webcluster_oid: str, webservice_oid: str, details: Optional[CallDetails] = None)
return webservice.marshal()
Get definition of a web service by ID. See also the corresponding procedure :meth:`crossbar.master.cluster.webcluster.WebClusterManager.get_webcluster_service_by_path` which returns the same information, given HTTP path rather than object ID. :param webcluster_oid: The web cluster running the web service to return. :param webservice_oid: The web service to return. :return: The web service definition, for example: .. code-block:: json { "description": null, "label": null, "oid": "6cc51192-4259-4640-84cb-ee03b6f92fbf", "path": "info", "tags": null, "type": "nodeinfo", "webcluster_oid": "92f5f4c7-4175-4c72-a0a6-81467c343565" }
Get definition of a web service by ID.
[ "Get", "definition", "of", "a", "web", "service", "by", "ID", "." ]
def get_webcluster_service(self, webcluster_oid: str, webservice_oid: str, details: Optional[CallDetails] = None) -> dict: """ Get definition of a web service by ID. See also the corresponding procedure :meth:`crossbar.master.cluster.webcluster.WebClusterManager.get_webcluster_service_by_path` which returns the same information, given HTTP path rather than object ID. :param webcluster_oid: The web cluster running the web service to return. :param webservice_oid: The web service to return. :return: The web service definition, for example: .. code-block:: json { "description": null, "label": null, "oid": "6cc51192-4259-4640-84cb-ee03b6f92fbf", "path": "info", "tags": null, "type": "nodeinfo", "webcluster_oid": "92f5f4c7-4175-4c72-a0a6-81467c343565" } """ assert type(webcluster_oid) == str assert type(webservice_oid) == str assert details is None or isinstance(details, CallDetails) self.log.info('{func}(webcluster_oid={webcluster_oid}, webservice_oid={webservice_oid}, details={details})', webcluster_oid=hlid(webcluster_oid), webservice_oid=hlid(webservice_oid), func=hltype(self.get_webcluster_service), details=details) try: webcluster_oid_ = uuid.UUID(webcluster_oid) except Exception as e: raise ApplicationError('wamp.error.invalid_argument', 'invalid oid "{}"'.format(str(e))) try: webservice_oid_ = uuid.UUID(webservice_oid) except Exception as e: raise ApplicationError('wamp.error.invalid_argument', 'invalid oid "{}"'.format(str(e))) with self.db.begin() as txn: webcluster = self.schema.webclusters[txn, webcluster_oid_] if not webcluster: raise ApplicationError('crossbar.error.no_such_object', 'no object with oid {} found'.format(webcluster_oid_)) webservice = self.schema.webservices[txn, webservice_oid_] if not webservice: raise ApplicationError('crossbar.error.no_such_object', 'no object with oid {} found'.format(webservice_oid_)) return webservice.marshal()
[ "def", "get_webcluster_service", "(", "self", ",", "webcluster_oid", ":", "str", ",", "webservice_oid", ":", "str", ",", "details", ":", "Optional", "[", "CallDetails", "]", "=", "None", ")", "->", "dict", ":", "assert", "type", "(", "webcluster_oid", ")", ...
https://github.com/crossbario/crossbar/blob/ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64/crossbar/master/cluster/webcluster.py#L1627-L1685
nengo/nengo
f5a88ba6b42b39a722299db6e889a5d034fcfeda
nengo/transforms.py
python
Transform.sample
(self, rng=np.random)
Returns concrete weights to implement the specified transform. Parameters ---------- rng : `numpy.random.RandomState`, optional Random number generator state. Returns ------- array_like Transform weights
Returns concrete weights to implement the specified transform.
[ "Returns", "concrete", "weights", "to", "implement", "the", "specified", "transform", "." ]
def sample(self, rng=np.random): """Returns concrete weights to implement the specified transform. Parameters ---------- rng : `numpy.random.RandomState`, optional Random number generator state. Returns ------- array_like Transform weights """ raise NotImplementedError()
[ "def", "sample", "(", "self", ",", "rng", "=", "np", ".", "random", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/nengo/nengo/blob/f5a88ba6b42b39a722299db6e889a5d034fcfeda/nengo/transforms.py#L26-L39
osroom/osroom
fcb9b7c5e5cfd8e919f8d87521800e70b09b5b44
apps/core/plug_in/config_process.py
python
get_plugin_config
(plugin_name, key)
获取网站动态配置中对应的project中key的值 :return:
获取网站动态配置中对应的project中key的值 :return:
[ "获取网站动态配置中对应的project中key的值", ":", "return", ":" ]
def get_plugin_config(plugin_name, key): """ 获取网站动态配置中对应的project中key的值 :return: """ with app.app_context(): return get_all_config()[plugin_name][key]
[ "def", "get_plugin_config", "(", "plugin_name", ",", "key", ")", ":", "with", "app", ".", "app_context", "(", ")", ":", "return", "get_all_config", "(", ")", "[", "plugin_name", "]", "[", "key", "]" ]
https://github.com/osroom/osroom/blob/fcb9b7c5e5cfd8e919f8d87521800e70b09b5b44/apps/core/plug_in/config_process.py#L81-L87
menpo/menpo
a61500656c4fc2eea82497684f13cc31a605550b
menpo/landmark/labels/human/face.py
python
face_ibug_68_to_face_ibug_65
(pcloud)
return new_pcloud, mapping
r""" Apply the IBUG 68 point semantic labels, but ignore the 3 points that are coincident for a closed mouth (bottom of the inner mouth). The semantic labels applied are as follows: - jaw - left_eyebrow - right_eyebrow - nose - left_eye - right_eye - mouth References ---------- .. [1] http://www.multipie.org/ .. [2] http://ibug.doc.ic.ac.uk/resources/300-W/
r""" Apply the IBUG 68 point semantic labels, but ignore the 3 points that are coincident for a closed mouth (bottom of the inner mouth).
[ "r", "Apply", "the", "IBUG", "68", "point", "semantic", "labels", "but", "ignore", "the", "3", "points", "that", "are", "coincident", "for", "a", "closed", "mouth", "(", "bottom", "of", "the", "inner", "mouth", ")", "." ]
def face_ibug_68_to_face_ibug_65(pcloud): r""" Apply the IBUG 68 point semantic labels, but ignore the 3 points that are coincident for a closed mouth (bottom of the inner mouth). The semantic labels applied are as follows: - jaw - left_eyebrow - right_eyebrow - nose - left_eye - right_eye - mouth References ---------- .. [1] http://www.multipie.org/ .. [2] http://ibug.doc.ic.ac.uk/resources/300-W/ """ from menpo.shape import LabelledPointUndirectedGraph # Apply face_ibug_68_to_face_ibug_68 new_pcloud, mapping = face_ibug_68_to_face_ibug_68(pcloud, return_mapping=True) # The coincident points are considered the final 3 landmarks (bottom of # the inner mouth points). We remove all the edges for the inner mouth # which are the last 8. edges = new_pcloud.edges[:-8] # Re-add the inner mouth without the bottom 3 points edges = np.vstack([edges, connectivity_from_range((60, 65), close_loop=True)]) # Luckily, OrderedDict maintains the original ordering despite updates outer_mouth_indices = np.arange(48, 60) inner_mouth_indices = np.arange(60, 65) mapping["mouth"] = np.hstack([outer_mouth_indices, inner_mouth_indices]) new_pcloud = LabelledPointUndirectedGraph.init_from_indices_mapping( new_pcloud.points[:-3], edges, mapping ) return new_pcloud, mapping
[ "def", "face_ibug_68_to_face_ibug_65", "(", "pcloud", ")", ":", "from", "menpo", ".", "shape", "import", "LabelledPointUndirectedGraph", "# Apply face_ibug_68_to_face_ibug_68", "new_pcloud", ",", "mapping", "=", "face_ibug_68_to_face_ibug_68", "(", "pcloud", ",", "return_ma...
https://github.com/menpo/menpo/blob/a61500656c4fc2eea82497684f13cc31a605550b/menpo/landmark/labels/human/face.py#L976-L1017
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/OpenSSL/SSL.py
python
Connection.set_session
(self, session)
Set the session to be used when the TLS/SSL connection is established. :param session: A Session instance representing the session to use. :returns: None
Set the session to be used when the TLS/SSL connection is established.
[ "Set", "the", "session", "to", "be", "used", "when", "the", "TLS", "/", "SSL", "connection", "is", "established", "." ]
def set_session(self, session): """ Set the session to be used when the TLS/SSL connection is established. :param session: A Session instance representing the session to use. :returns: None """ if not isinstance(session, Session): raise TypeError("session must be a Session instance") result = _lib.SSL_set_session(self._ssl, session._session) if not result: _raise_current_error()
[ "def", "set_session", "(", "self", ",", "session", ")", ":", "if", "not", "isinstance", "(", "session", ",", "Session", ")", ":", "raise", "TypeError", "(", "\"session must be a Session instance\"", ")", "result", "=", "_lib", ".", "SSL_set_session", "(", "sel...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/OpenSSL/SSL.py#L1770-L1782
cheshirekow/cmake_format
eff5df1f41c665ea7cac799396042e4f406ef09a
cmakelang/contrib/validate_pullrequest.py
python
TestContribution.test_commit_is_signed
(self)
Ensure that the feature commit is signed
Ensure that the feature commit is signed
[ "Ensure", "that", "the", "feature", "commit", "is", "signed" ]
def test_commit_is_signed(self): """ Ensure that the feature commit is signed """ repodir = get_repo_dir() feature_sha1 = os.environ.get("TRAVIS_PULL_REQUEST_SHA") signer_encoded = subprocess.check_output( ["git", "show", "-s", r'--pretty="%GK"', feature_sha1], cwd=repodir).decode("utf-8").strip().strip('"') # TODO(josh): deduplicate with validate_database # First, get a list of keys already in the local keyring known_fingerprints = set() proc = subprocess.Popen( ["gpg", "--fingerprint", "--with-colons"], stdout=subprocess.PIPE) for line in proc.stdout: parts = line.decode("utf-8").split(":") if parts[0] == "fpr": fingerprint = parts[-2] known_fingerprints.add(fingerprint[-16:]) proc.wait() if signer_encoded not in known_fingerprints: # TODO(josh): use SKS pool instead of specific server result = subprocess.check_call( ["gpg", "--keyserver", "keyserver.ubuntu.com", "--recv-keys", signer_encoded]) self.assertEqual( result, 0, msg="Failed to fetch signer key from keyserver") with tempfile.NamedTemporaryFile(delete=False) as stderr: result = subprocess.call( ["git", "verify-commit", feature_sha1], cwd=repodir, stderr=stderr) stderrpath = stderr.name with open(stderrpath, "r") as infile: stderrtext = infile.read() os.unlink(stderrpath) self.assertEqual( 0, result, "git was unable to verify commit {}\n{}" .format(feature_sha1, stderrtext))
[ "def", "test_commit_is_signed", "(", "self", ")", ":", "repodir", "=", "get_repo_dir", "(", ")", "feature_sha1", "=", "os", ".", "environ", ".", "get", "(", "\"TRAVIS_PULL_REQUEST_SHA\"", ")", "signer_encoded", "=", "subprocess", ".", "check_output", "(", "[", ...
https://github.com/cheshirekow/cmake_format/blob/eff5df1f41c665ea7cac799396042e4f406ef09a/cmakelang/contrib/validate_pullrequest.py#L92-L134
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
libs/scss/__init__.py
python
Scss._do_import
(self, rule, p_selectors, p_parents, p_children, scope, media, c_property, c_codestr, code, name)
Implements @import Load and import mixins and functions and rules
Implements
[ "Implements" ]
def _do_import(self, rule, p_selectors, p_parents, p_children, scope, media, c_property, c_codestr, code, name): """ Implements @import Load and import mixins and functions and rules """ i_codestr = None if '..' not in name and '://' not in name and 'url(' not in name: # Protect against going to prohibited places... names = name.split(',') for name in names: name = dequote(name.strip()) if '@import ' + name not in rule[OPTIONS]: # If already imported in this scope, skip... try: raise KeyError i_codestr = self._scss_files[name] except KeyError: filename = os.path.basename(name) dirname = os.path.dirname(name) load_paths = [] i_codestr = None for path in [ './' ] + LOAD_PATHS.split(','): for basepath in [ './', os.path.dirname(rule[PATH]) ]: i_codestr = None full_path = os.path.realpath(os.path.join(path, basepath, dirname)) if full_path not in load_paths: try: full_filename = os.path.join(full_path, '_'+filename+'.scss') i_codestr = open(full_filename).read() except: try: full_filename = os.path.join(full_path, filename+'.scss') i_codestr = open(full_filename).read() except: try: full_filename = os.path.join(full_path, '_'+filename) i_codestr = open(full_filename).read() except: try: full_filename = os.path.join(full_path, filename) i_codestr = open(full_filename).read() except: pass if i_codestr is not None: break else: load_paths.append(full_path) if i_codestr is not None: break if i_codestr is None: i_codestr = self._do_magic_import(rule, p_selectors, p_parents, p_children, scope, media, c_property, c_codestr, code, name) i_codestr = self._scss_files[name] = i_codestr and self.load_string(i_codestr) if i_codestr is None: log.warn("File to import not found or unreadable: '%s'\nLoad paths:\n\t%s", filename, "\n\t".join(load_paths)) else: _rule = spawn_rule(rule, codestr=i_codestr, path=full_filename, file=name) self.manage_children(_rule, p_selectors, p_parents, p_children, scope, media) rule[OPTIONS]['@import ' + name] = True else: rule[PROPERTIES].append((c_property, None))
[ "def", "_do_import", "(", "self", ",", "rule", ",", "p_selectors", ",", "p_parents", ",", "p_children", ",", "scope", ",", "media", ",", "c_property", ",", "c_codestr", ",", "code", ",", "name", ")", ":", "i_codestr", "=", "None", "if", "'..'", "not", ...
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/libs/scss/__init__.py#L1005-L1062
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/makers/map.py
python
MapDatasetMaker.make_edisp
(self, geom, observation)
return make_edisp_map( edisp=observation.edisp, pointing=observation.pointing_radec, geom=geom, exposure_map=exposure, use_region_center=use_region_center, )
Make energy dispersion map. Parameters ---------- geom : `~gammapy.maps.Geom` Reference geom. observation : `~gammapy.data.Observation` Observation container. Returns ------- edisp : `~gammapy.irf.EDispMap` Edisp map.
Make energy dispersion map.
[ "Make", "energy", "dispersion", "map", "." ]
def make_edisp(self, geom, observation): """Make energy dispersion map. Parameters ---------- geom : `~gammapy.maps.Geom` Reference geom. observation : `~gammapy.data.Observation` Observation container. Returns ------- edisp : `~gammapy.irf.EDispMap` Edisp map. """ exposure = self.make_exposure_irf(geom.squash(axis_name="migra"), observation) use_region_center = getattr(self, "use_region_center", True) return make_edisp_map( edisp=observation.edisp, pointing=observation.pointing_radec, geom=geom, exposure_map=exposure, use_region_center=use_region_center, )
[ "def", "make_edisp", "(", "self", ",", "geom", ",", "observation", ")", ":", "exposure", "=", "self", ".", "make_exposure_irf", "(", "geom", ".", "squash", "(", "axis_name", "=", "\"migra\"", ")", ",", "observation", ")", "use_region_center", "=", "getattr",...
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/makers/map.py#L176-L201
wandb/client
3963364d8112b7dedb928fa423b6878ea1b467d9
wandb/apis/public.py
python
Artifact.delete
(self, delete_aliases=False)
return True
Delete an artifact and its files. Examples: Delete all the "model" artifacts a run has logged: ``` runs = api.runs(path="my_entity/my_project") for run in runs: for artifact in run.logged_artifacts(): if artifact.type == "model": artifact.delete(delete_aliases=True) ``` Arguments: delete_aliases: (bool) If true, deletes all aliases associated with the artifact. Otherwise, this raises an exception if the artifact has existing alaises.
Delete an artifact and its files.
[ "Delete", "an", "artifact", "and", "its", "files", "." ]
def delete(self, delete_aliases=False): """ Delete an artifact and its files. Examples: Delete all the "model" artifacts a run has logged: ``` runs = api.runs(path="my_entity/my_project") for run in runs: for artifact in run.logged_artifacts(): if artifact.type == "model": artifact.delete(delete_aliases=True) ``` Arguments: delete_aliases: (bool) If true, deletes all aliases associated with the artifact. Otherwise, this raises an exception if the artifact has existing alaises. """ mutation = gql( """ mutation DeleteArtifact($artifactID: ID!, $deleteAliases: Boolean) { deleteArtifact(input: { artifactID: $artifactID deleteAliases: $deleteAliases }) { artifact { id } } } """ ) self.client.execute( mutation, variable_values={"artifactID": self.id, "deleteAliases": delete_aliases,}, ) return True
[ "def", "delete", "(", "self", ",", "delete_aliases", "=", "False", ")", ":", "mutation", "=", "gql", "(", "\"\"\"\n mutation DeleteArtifact($artifactID: ID!, $deleteAliases: Boolean) {\n deleteArtifact(input: {\n artifactID: $artifactID\n d...
https://github.com/wandb/client/blob/3963364d8112b7dedb928fa423b6878ea1b467d9/wandb/apis/public.py#L3610-L3646
SUSE/DeepSea
9c7fad93915ba1250c40d50c855011e9fe41ed21
srv/modules/runners/populate.py
python
HardwareProfile._label
(self, vendor, capacity)
return vendor + re.sub(' ', '', capacity)
Use a single word for vendor. Strip spaces from capacity.
Use a single word for vendor. Strip spaces from capacity.
[ "Use", "a", "single", "word", "for", "vendor", ".", "Strip", "spaces", "from", "capacity", "." ]
def _label(self, vendor, capacity): """ Use a single word for vendor. Strip spaces from capacity. """ if ' ' in vendor: vendor = self._brand(vendor) return vendor + re.sub(' ', '', capacity)
[ "def", "_label", "(", "self", ",", "vendor", ",", "capacity", ")", ":", "if", "' '", "in", "vendor", ":", "vendor", "=", "self", ".", "_brand", "(", "vendor", ")", "return", "vendor", "+", "re", ".", "sub", "(", "' '", ",", "''", ",", "capacity", ...
https://github.com/SUSE/DeepSea/blob/9c7fad93915ba1250c40d50c855011e9fe41ed21/srv/modules/runners/populate.py#L212-L218
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_internal/operations/prepare.py
python
DistAbstraction.prep_for_dist
(self, finder)
Ensure that we can get a Dist for this requirement.
Ensure that we can get a Dist for this requirement.
[ "Ensure", "that", "we", "can", "get", "a", "Dist", "for", "this", "requirement", "." ]
def prep_for_dist(self, finder): """Ensure that we can get a Dist for this requirement.""" raise NotImplementedError(self.dist)
[ "def", "prep_for_dist", "(", "self", ",", "finder", ")", ":", "raise", "NotImplementedError", "(", "self", ".", "dist", ")" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_internal/operations/prepare.py#L68-L70
peeringdb/peeringdb
47c6a699267b35663898f8d261159bdae9720f04
mainsite/settings/__init__.py
python
_set_default
(name, value, context)
Sets the default value for the option if it's not already set.
Sets the default value for the option if it's not already set.
[ "Sets", "the", "default", "value", "for", "the", "option", "if", "it", "s", "not", "already", "set", "." ]
def _set_default(name, value, context): """Sets the default value for the option if it's not already set.""" if name not in context: context[name] = value
[ "def", "_set_default", "(", "name", ",", "value", ",", "context", ")", ":", "if", "name", "not", "in", "context", ":", "context", "[", "name", "]", "=", "value" ]
https://github.com/peeringdb/peeringdb/blob/47c6a699267b35663898f8d261159bdae9720f04/mainsite/settings/__init__.py#L177-L180
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/tarfile.py
python
TarInfo._proc_builtin
(self, tarfile)
return self
Process a builtin type or an unknown type which will be treated as a regular file.
Process a builtin type or an unknown type which will be treated as a regular file.
[ "Process", "a", "builtin", "type", "or", "an", "unknown", "type", "which", "will", "be", "treated", "as", "a", "regular", "file", "." ]
def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the following data blocks. offset += self._block(self.size) tarfile.offset = offset # Patch the TarInfo object with saved global # header information. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) return self
[ "def", "_proc_builtin", "(", "self", ",", "tarfile", ")", ":", "self", ".", "offset_data", "=", "tarfile", ".", "fileobj", ".", "tell", "(", ")", "offset", "=", "self", ".", "offset_data", "if", "self", ".", "isreg", "(", ")", "or", "self", ".", "typ...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/tarfile.py#L1114-L1129
tosher/Mediawiker
81bf97cace59bedcb1668e7830b85c36e014428e
lib/Crypto.win.x64/Crypto/Util/asn1.py
python
DerBitString.__init__
(self, value=b(''), implicit=None, explicit=None)
Initialize the DER object as a BIT STRING. :Parameters: value : byte string or DER object The initial, packed bit string. If not specified, the bit string is empty. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OCTET STRING (3). explicit : integer The EXPLICIT tag to use for the encoded object.
Initialize the DER object as a BIT STRING.
[ "Initialize", "the", "DER", "object", "as", "a", "BIT", "STRING", "." ]
def __init__(self, value=b(''), implicit=None, explicit=None): """Initialize the DER object as a BIT STRING. :Parameters: value : byte string or DER object The initial, packed bit string. If not specified, the bit string is empty. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OCTET STRING (3). explicit : integer The EXPLICIT tag to use for the encoded object. """ DerObject.__init__(self, 0x03, b(''), implicit, False, explicit) # The bitstring value (packed) if isinstance(value, DerObject): self.value = value.encode() else: self.value = value
[ "def", "__init__", "(", "self", ",", "value", "=", "b", "(", "''", ")", ",", "implicit", "=", "None", ",", "explicit", "=", "None", ")", ":", "DerObject", ".", "__init__", "(", "self", ",", "0x03", ",", "b", "(", "''", ")", ",", "implicit", ",", ...
https://github.com/tosher/Mediawiker/blob/81bf97cace59bedcb1668e7830b85c36e014428e/lib/Crypto.win.x64/Crypto/Util/asn1.py#L724-L743
optuna/optuna
2c44c1a405ba059efd53f4b9c8e849d20fb95c0a
optuna/storages/_cached_storage.py
python
_CachedStorage.set_trial_values
(self, trial_id: int, values: Sequence[float])
[]
def set_trial_values(self, trial_id: int, values: Sequence[float]) -> None: with self._lock: cached_trial = self._get_cached_trial(trial_id) if cached_trial is not None: self._check_trial_is_updatable(cached_trial) cached_trial.values = values self._backend.set_trial_values(trial_id, values=values)
[ "def", "set_trial_values", "(", "self", ",", "trial_id", ":", "int", ",", "values", ":", "Sequence", "[", "float", "]", ")", "->", "None", ":", "with", "self", ".", "_lock", ":", "cached_trial", "=", "self", ".", "_get_cached_trial", "(", "trial_id", ")"...
https://github.com/optuna/optuna/blob/2c44c1a405ba059efd53f4b9c8e849d20fb95c0a/optuna/storages/_cached_storage.py#L273-L280
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/framework/hetero/sync/batch_info_sync.py
python
Host.sync_batch_index
(self, suffix=tuple())
return batch_index
[]
def sync_batch_index(self, suffix=tuple()): batch_index = self.batch_data_index_transfer.get(idx=0, suffix=suffix) return batch_index
[ "def", "sync_batch_index", "(", "self", ",", "suffix", "=", "tuple", "(", ")", ")", ":", "batch_index", "=", "self", ".", "batch_data_index_transfer", ".", "get", "(", "idx", "=", "0", ",", "suffix", "=", "suffix", ")", "return", "batch_index" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/framework/hetero/sync/batch_info_sync.py#L63-L66
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Tools/GeniaSentenceSplitter.py
python
moveElements
(document)
[]
def moveElements(document): entMap = {} entSentence = {} entSentenceIndex = {} sentences = document.findall("sentence") sentenceCount = 0 for sentence in sentences: sentenceOffset = Range.charOffsetToSingleTuple(sentence.get("charOffset")) # Move entities entCount = 0 for entity in document.findall("entity"): entityOffsets = Range.charOffsetToTuples(entity.get("charOffset")) overlaps = False for entityOffset in entityOffsets: if Range.overlap(sentenceOffset, entityOffset): overlaps = True break if overlaps: document.remove(entity) sentence.append(entity) entityId = entity.get("id") entityIdLastPart = entityId.rsplit(".", 1)[-1] if entityIdLastPart.startswith("e"): entity.set("id", sentence.get("id") + "." + entityIdLastPart) entMap[entityId] = sentence.get("id") + "." + entityIdLastPart else: entity.set("docId", entityId) entity.set("id", sentence.get("id") + ".e" + str(entCount)) entMap[entityId] = sentence.get("id") + ".e" + str(entCount) entSentence[entityId] = sentence entSentenceIndex[entityId] = sentenceCount #newEntityOffset = (entityOffset[0] - sentenceOffset[0], entityOffset[1] - sentenceOffset[0]) newEntityOffsets = [] for entityOffset in entityOffsets: newOffset = (entityOffset[0] - sentenceOffset[0], entityOffset[1] - sentenceOffset[0]) newOffset = (max(0, newOffset[0]), max(0, newOffset[1])) if newOffset != (0, 0): assert newOffset[1] > newOffset[0], (entity.attrib, entityOffsets, sentenceOffset) newEntityOffsets.append( (entityOffset[0] - sentenceOffset[0], entityOffset[1] - sentenceOffset[0]) ) assert len(newEntityOffsets) > 0, (entity.attrib, entityOffsets, sentenceOffset) entity.set("origOffset", entity.get("charOffset")) #entity.set("charOffset", str(newEntityOffset[0]) + "-" + str(newEntityOffset[1])) entity.set("charOffset", Range.tuplesToCharOffset(newEntityOffsets)) entCount += 1 sentenceCount += 1 if len([x for x in document.findall("entity")]) != 0: raise Exception("Sentence splitting does not cover the entire document") # Move interactions intCount = 0 interactions = [] interactionOldToNewId = {} for interaction in document.findall("interaction"): interactions.append(interaction) #if entSentenceIndex[interaction.get("e1")] < entSentenceIndex[interaction.get("e2")]: # targetSentence = entSentence[interaction.get("e1")] #else: # targetSentence = entSentence[interaction.get("e2")] # Interactions go to a sentence always by e1, as this is the event they are an argument of. # If an intersentence interaction is a relation, this shouldn't matter. targetSentence = entSentence[interaction.get("e1")] document.remove(interaction) targetSentence.append(interaction) newId = targetSentence.get("id") + ".i" + str(intCount) interactionOldToNewId[interaction.get("id")] = newId interaction.set("id", newId) interaction.set("e1", entMap[interaction.get("e1")]) interaction.set("e2", entMap[interaction.get("e2")]) intCount += 1 for interaction in interactions: if interaction.get("siteOf") != None: interaction.set("siteOf", interactionOldToNewId[interaction.get("siteOf")])
[ "def", "moveElements", "(", "document", ")", ":", "entMap", "=", "{", "}", "entSentence", "=", "{", "}", "entSentenceIndex", "=", "{", "}", "sentences", "=", "document", ".", "findall", "(", "\"sentence\"", ")", "sentenceCount", "=", "0", "for", "sentence"...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Tools/GeniaSentenceSplitter.py#L39-L110
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/compilers/mixins/intel.py
python
IntelGnuLikeCompiler.get_has_func_attribute_extra_args
(self, name: str)
return ['-diag-error', '1292']
[]
def get_has_func_attribute_extra_args(self, name: str) -> T.List[str]: return ['-diag-error', '1292']
[ "def", "get_has_func_attribute_extra_args", "(", "self", ",", "name", ":", "str", ")", "->", "T", ".", "List", "[", "str", "]", ":", "return", "[", "'-diag-error'", ",", "'1292'", "]" ]
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/mixins/intel.py#L122-L123
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_project.py
python
Project.__init__
(self, content)
Project constructor
Project constructor
[ "Project", "constructor" ]
def __init__(self, content): '''Project constructor''' super(Project, self).__init__(content=content)
[ "def", "__init__", "(", "self", ",", "content", ")", ":", "super", "(", "Project", ",", "self", ")", ".", "__init__", "(", "content", "=", "content", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_project.py#L1488-L1490
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/metagoofil/hachoir_parser/archive/sevenzip.py
python
NextHeader.createFields2
(self)
[]
def createFields2(self): yield Enum(UInt8(self, "header_type"), ID_INFO) yield RawBytes(self, "header_data", self._size-1)
[ "def", "createFields2", "(", "self", ")", ":", "yield", "Enum", "(", "UInt8", "(", "self", ",", "\"header_type\"", ")", ",", "ID_INFO", ")", "yield", "RawBytes", "(", "self", ",", "\"header_data\"", ",", "self", ".", "_size", "-", "1", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_parser/archive/sevenzip.py#L317-L319
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/events/v1/subscription/__init__.py
python
SubscriptionInstance._proxy
(self)
return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SubscriptionContext for this SubscriptionInstance :rtype: twilio.rest.events.v1.subscription.SubscriptionContext
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SubscriptionContext for this SubscriptionInstance :rtype: twilio.rest.events.v1.subscription.SubscriptionContext """ if self._context is None: self._context = SubscriptionContext(self._version, sid=self._solution['sid'], ) return self._context
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "SubscriptionContext", "(", "self", ".", "_version", ",", "sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "retu...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/events/v1/subscription/__init__.py#L328-L338
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/setuptools/dist.py
python
assert_string_list
(dist, attr, value)
Verify that value is a string list or None
Verify that value is a string list or None
[ "Verify", "that", "value", "is", "a", "string", "list", "or", "None" ]
def assert_string_list(dist, attr, value): """Verify that value is a string list or None""" try: assert ''.join(value)!=value except (TypeError,ValueError,AttributeError,AssertionError): raise DistutilsSetupError( "%r must be a list of strings (got %r)" % (attr,value) )
[ "def", "assert_string_list", "(", "dist", ",", "attr", ",", "value", ")", ":", "try", ":", "assert", "''", ".", "join", "(", "value", ")", "!=", "value", "except", "(", "TypeError", ",", "ValueError", ",", "AttributeError", ",", "AssertionError", ")", ":...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/setuptools/dist.py#L74-L81
sabri-zaki/EasY_HaCk
2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9
.modules/.sqlmap/lib/core/common.py
python
ntToPosixSlashes
(filepath)
return filepath.replace('\\', '/') if filepath else filepath
Replaces all occurrences of NT slashes (\) in provided filepath with Posix ones (/) >>> ntToPosixSlashes('C:\\Windows') 'C:/Windows'
Replaces all occurrences of NT slashes (\) in provided filepath with Posix ones (/)
[ "Replaces", "all", "occurrences", "of", "NT", "slashes", "(", "\\", ")", "in", "provided", "filepath", "with", "Posix", "ones", "(", "/", ")" ]
def ntToPosixSlashes(filepath): """ Replaces all occurrences of NT slashes (\) in provided filepath with Posix ones (/) >>> ntToPosixSlashes('C:\\Windows') 'C:/Windows' """ return filepath.replace('\\', '/') if filepath else filepath
[ "def", "ntToPosixSlashes", "(", "filepath", ")", ":", "return", "filepath", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "filepath", "else", "filepath" ]
https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.sqlmap/lib/core/common.py#L1962-L1971
lululxvi/deepxde
730c97282636e86c845ce2ba3253482f2178469e
deepxde/backend/pytorch/tensor.py
python
silu
(x)
return torch.nn.functional.silu(x)
[]
def silu(x): return torch.nn.functional.silu(x)
[ "def", "silu", "(", "x", ")", ":", "return", "torch", ".", "nn", ".", "functional", ".", "silu", "(", "x", ")" ]
https://github.com/lululxvi/deepxde/blob/730c97282636e86c845ce2ba3253482f2178469e/deepxde/backend/pytorch/tensor.py#L86-L87
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/matrices/expressions/matexpr.py
python
MatrixExpr.T
(self)
return self.transpose()
Matrix transposition
Matrix transposition
[ "Matrix", "transposition" ]
def T(self): '''Matrix transposition''' return self.transpose()
[ "def", "T", "(", "self", ")", ":", "return", "self", ".", "transpose", "(", ")" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/matrices/expressions/matexpr.py#L252-L254
gentoo/portage
e5be73709b1a42b40380fd336f9381452b01a723
lib/_emerge/DepPriority.py
python
DepPriority.__int__
(self)
return -5
Note: These priorities are only used for measuring hardness in the circular dependency display via digraph.debug_print(), and nothing more. For actual merge order calculations, the measures defined by the DepPriorityNormalRange and DepPrioritySatisfiedRange classes are used. Attributes Hardness buildtime_slot_op 0 buildtime -1 runtime -2 runtime_post -3 optional -4 (none of the above) -5
Note: These priorities are only used for measuring hardness in the circular dependency display via digraph.debug_print(), and nothing more. For actual merge order calculations, the measures defined by the DepPriorityNormalRange and DepPrioritySatisfiedRange classes are used.
[ "Note", ":", "These", "priorities", "are", "only", "used", "for", "measuring", "hardness", "in", "the", "circular", "dependency", "display", "via", "digraph", ".", "debug_print", "()", "and", "nothing", "more", ".", "For", "actual", "merge", "order", "calculat...
def __int__(self): """ Note: These priorities are only used for measuring hardness in the circular dependency display via digraph.debug_print(), and nothing more. For actual merge order calculations, the measures defined by the DepPriorityNormalRange and DepPrioritySatisfiedRange classes are used. Attributes Hardness buildtime_slot_op 0 buildtime -1 runtime -2 runtime_post -3 optional -4 (none of the above) -5 """ if self.optional: return -4 if self.buildtime_slot_op: return 0 if self.buildtime: return -1 if self.runtime: return -2 if self.runtime_post: return -3 return -5
[ "def", "__int__", "(", "self", ")", ":", "if", "self", ".", "optional", ":", "return", "-", "4", "if", "self", ".", "buildtime_slot_op", ":", "return", "0", "if", "self", ".", "buildtime", ":", "return", "-", "1", "if", "self", ".", "runtime", ":", ...
https://github.com/gentoo/portage/blob/e5be73709b1a42b40380fd336f9381452b01a723/lib/_emerge/DepPriority.py#L11-L40
guillermooo/Vintageous
f958207009902052aed5fcac09745f1742648604
ex_commands.py
python
ExOunmap.run
(self, command_line='')
[]
def run(self, command_line=''): assert command_line, 'expected non-empty command line' ounmap_command = parse_command_line(command_line) mappings = Mappings(self.state) try: mappings.remove(modes.OPERATOR_PENDING, ounmap_command.command.keys) except KeyError: sublime.status_message('Vintageous: Mapping not found.')
[ "def", "run", "(", "self", ",", "command_line", "=", "''", ")", ":", "assert", "command_line", ",", "'expected non-empty command line'", "ounmap_command", "=", "parse_command_line", "(", "command_line", ")", "mappings", "=", "Mappings", "(", "self", ".", "state", ...
https://github.com/guillermooo/Vintageous/blob/f958207009902052aed5fcac09745f1742648604/ex_commands.py#L423-L430
MitjaNemec/Kicad_action_plugins
0994a10808687fbcffcb0eba507fa9bd8422ae19
save_restore_layout/save_restore_layout.py
python
rotate_around_center
(coordinates, angle)
return new_x, new_y
rotate coordinates for a defined angle in degrees around coordinate center
rotate coordinates for a defined angle in degrees around coordinate center
[ "rotate", "coordinates", "for", "a", "defined", "angle", "in", "degrees", "around", "coordinate", "center" ]
def rotate_around_center(coordinates, angle): """ rotate coordinates for a defined angle in degrees around coordinate center""" new_x = coordinates[0] * math.cos(2 * math.pi * angle/360)\ - coordinates[1] * math.sin(2 * math.pi * angle/360) new_y = coordinates[0] * math.sin(2 * math.pi * angle/360)\ + coordinates[1] * math.cos(2 * math.pi * angle/360) return new_x, new_y
[ "def", "rotate_around_center", "(", "coordinates", ",", "angle", ")", ":", "new_x", "=", "coordinates", "[", "0", "]", "*", "math", ".", "cos", "(", "2", "*", "math", ".", "pi", "*", "angle", "/", "360", ")", "-", "coordinates", "[", "1", "]", "*",...
https://github.com/MitjaNemec/Kicad_action_plugins/blob/0994a10808687fbcffcb0eba507fa9bd8422ae19/save_restore_layout/save_restore_layout.py#L71-L77
s3tools/s3cmd
4c4bddf32667efbbccb5514b61cee2d918546b58
S3/Utils.py
python
mkdir_with_parents
(dir_name)
return True
mkdir_with_parents(dst_dir) Create directory 'dir_name' with all parent directories Returns True on success, False otherwise.
mkdir_with_parents(dst_dir)
[ "mkdir_with_parents", "(", "dst_dir", ")" ]
def mkdir_with_parents(dir_name): """ mkdir_with_parents(dst_dir) Create directory 'dir_name' with all parent directories Returns True on success, False otherwise. """ pathmembers = dir_name.split(os.sep) tmp_stack = [] while pathmembers and not os.path.isdir(deunicodise(os.sep.join(pathmembers))): tmp_stack.append(pathmembers.pop()) while tmp_stack: pathmembers.append(tmp_stack.pop()) cur_dir = os.sep.join(pathmembers) try: debug("mkdir(%s)" % cur_dir) os.mkdir(deunicodise(cur_dir)) except (OSError, IOError) as e: debug("Can not make directory '%s' (Reason: %s)" % (cur_dir, e.strerror)) return False except Exception as e: debug("Can not make directory '%s' (Reason: %s)" % (cur_dir, e)) return False return True
[ "def", "mkdir_with_parents", "(", "dir_name", ")", ":", "pathmembers", "=", "dir_name", ".", "split", "(", "os", ".", "sep", ")", "tmp_stack", "=", "[", "]", "while", "pathmembers", "and", "not", "os", ".", "path", ".", "isdir", "(", "deunicodise", "(", ...
https://github.com/s3tools/s3cmd/blob/4c4bddf32667efbbccb5514b61cee2d918546b58/S3/Utils.py#L117-L141
mahmoud/boltons
270e974975984f662f998c8f6eb0ebebd964de82
boltons/setutils.py
python
IndexedSet._add_dead
(self, start, stop=None)
return
[]
def _add_dead(self, start, stop=None): # TODO: does not handle when the new interval subsumes # multiple existing intervals dints = self.dead_indices if stop is None: stop = start + 1 cand_int = [start, stop] if not dints: dints.append(cand_int) return int_idx = bisect_left(dints, cand_int) dint = dints[int_idx - 1] d_start, d_stop = dint if start <= d_start <= stop: dint[0] = start elif start <= d_stop <= stop: dint[1] = stop else: dints.insert(int_idx, cand_int) return
[ "def", "_add_dead", "(", "self", ",", "start", ",", "stop", "=", "None", ")", ":", "# TODO: does not handle when the new interval subsumes", "# multiple existing intervals", "dints", "=", "self", ".", "dead_indices", "if", "stop", "is", "None", ":", "stop", "=", "...
https://github.com/mahmoud/boltons/blob/270e974975984f662f998c8f6eb0ebebd964de82/boltons/setutils.py#L189-L208
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_storage_class.py
python
V1StorageClass.provisioner
(self)
return self._provisioner
Gets the provisioner of this V1StorageClass. # noqa: E501 Provisioner indicates the type of the provisioner. # noqa: E501 :return: The provisioner of this V1StorageClass. # noqa: E501 :rtype: str
Gets the provisioner of this V1StorageClass. # noqa: E501
[ "Gets", "the", "provisioner", "of", "this", "V1StorageClass", ".", "#", "noqa", ":", "E501" ]
def provisioner(self): """Gets the provisioner of this V1StorageClass. # noqa: E501 Provisioner indicates the type of the provisioner. # noqa: E501 :return: The provisioner of this V1StorageClass. # noqa: E501 :rtype: str """ return self._provisioner
[ "def", "provisioner", "(", "self", ")", ":", "return", "self", ".", "_provisioner" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_storage_class.py#L259-L267
eBay/accelerator
218d9a5e4451ac72b9e65df6c5b32e37d25136c8
accelerator/dependency.py
python
initialise_jobs
(setup, target_WorkSpace, DataBase, Methods, verbose=False)
return new_jobid_list, {'jobs': res}
[]
def initialise_jobs(setup, target_WorkSpace, DataBase, Methods, verbose=False): # create a DepTree object used to track options and make status DepTree = deptree.DepTree(Methods, setup) if not setup.get('force_build'): # compare database to deptree reqlist = DepTree.get_reqlist() for uid, job in DataBase.match_exact(reqlist): DepTree.set_link(uid, job) DepTree.propagate_make() why_build = setup.get('why_build') if why_build: orig_tree = deepcopy(DepTree.tree) DepTree.fill_in_default_options() # get list of jobs in execution order joblist = DepTree.get_sorted_joblist() newjoblist = [x for x in joblist if x['make']] num_new_jobs = len(newjoblist) if why_build == True or (why_build and num_new_jobs): res = OrderedDict() DepTree.tree = orig_tree joblist = DepTree.get_sorted_joblist() for job in joblist: if job['make']: res[job['method']] = find_possible_jobs(DataBase, Methods, job) else: res[job['method']] = {job['link']: {}} return [], {'why_build': res} if num_new_jobs: new_jobid_list = target_WorkSpace.allocate_jobs(num_new_jobs) # insert new jobids for (x,jid) in zip(newjoblist, new_jobid_list): x['link'] = jid for data in newjoblist: method = Methods.db[data['method']] params = data['params'][data['method']] new_setup = setupfile.generate( caption=setup.caption, method=data['method'], options=params['options'], datasets=params['datasets'], jobs=params['jobs'], package=method['package'], description=Methods.descriptions[data['method']], ) new_setup.hash = Methods.hash[data['method']][0] new_setup.seed = randint(0, 2**63 - 1) new_setup.jobid = data['link'] new_setup.slices = target_WorkSpace.slices typing = Methods.typing[data['method']] if typing: new_setup['_typing'] = typing setupfile.save_setup(data['link'], new_setup) else: new_jobid_list = [] res = {j['method']: {k: v for k, v in j.items() if k in ('link', 'make', 'total_time')} for j in joblist} return new_jobid_list, {'jobs': res}
[ "def", "initialise_jobs", "(", "setup", ",", "target_WorkSpace", ",", "DataBase", ",", "Methods", ",", "verbose", "=", "False", ")", ":", "# create a DepTree object used to track options and make status", "DepTree", "=", "deptree", ".", "DepTree", "(", "Methods", ",",...
https://github.com/eBay/accelerator/blob/218d9a5e4451ac72b9e65df6c5b32e37d25136c8/accelerator/dependency.py#L67-L128
EnterpriseDB/barman
487bad92edec72712531ead4746fad72bb310270
barman/postgres.py
python
PostgreSQL.server_version
(self)
return conn.server_version
Version of PostgreSQL (returned by psycopg2)
Version of PostgreSQL (returned by psycopg2)
[ "Version", "of", "PostgreSQL", "(", "returned", "by", "psycopg2", ")" ]
def server_version(self): """ Version of PostgreSQL (returned by psycopg2) """ conn = self.connect() return conn.server_version
[ "def", "server_version", "(", "self", ")", ":", "conn", "=", "self", ".", "connect", "(", ")", "return", "conn", ".", "server_version" ]
https://github.com/EnterpriseDB/barman/blob/487bad92edec72712531ead4746fad72bb310270/barman/postgres.py#L229-L234
caktux/pytrader
b45b216dab3db78d6028d85e9a6f80419c22cea0
pytrader.py
python
WinStatus.slot_changed
(self, dummy_sender, dummy_data)
the callback funtion called by the Api() instance
the callback funtion called by the Api() instance
[ "the", "callback", "funtion", "called", "by", "the", "Api", "()", "instance" ]
def slot_changed(self, dummy_sender, dummy_data): """the callback funtion called by the Api() instance""" self.do_paint()
[ "def", "slot_changed", "(", "self", ",", "dummy_sender", ",", "dummy_data", ")", ":", "self", ".", "do_paint", "(", ")" ]
https://github.com/caktux/pytrader/blob/b45b216dab3db78d6028d85e9a6f80419c22cea0/pytrader.py#L1041-L1043
tensorflow/privacy
867f3d4c5566b21433a6a1bed998094d1479b4d5
tensorflow_privacy/privacy/dp_query/dp_query.py
python
DPQuery.accumulate_preprocessed_record
(self, sample_state, preprocessed_record)
Accumulates a single preprocessed record into the sample state. This method is intended to only do simple aggregation, typically just a sum. In the future, we might remove this method and replace it with a way to declaratively specify the type of aggregation required. Args: sample_state: The current sample state. In standard DP-SGD training, the accumulated sum of previous clipped microbatch gradients. preprocessed_record: The preprocessed record to accumulate. Returns: The updated sample state.
Accumulates a single preprocessed record into the sample state.
[ "Accumulates", "a", "single", "preprocessed", "record", "into", "the", "sample", "state", "." ]
def accumulate_preprocessed_record(self, sample_state, preprocessed_record): """Accumulates a single preprocessed record into the sample state. This method is intended to only do simple aggregation, typically just a sum. In the future, we might remove this method and replace it with a way to declaratively specify the type of aggregation required. Args: sample_state: The current sample state. In standard DP-SGD training, the accumulated sum of previous clipped microbatch gradients. preprocessed_record: The preprocessed record to accumulate. Returns: The updated sample state. """ pass
[ "def", "accumulate_preprocessed_record", "(", "self", ",", "sample_state", ",", "preprocessed_record", ")", ":", "pass" ]
https://github.com/tensorflow/privacy/blob/867f3d4c5566b21433a6a1bed998094d1479b4d5/tensorflow_privacy/privacy/dp_query/dp_query.py#L174-L189
Tencent/bk-bcs-saas
2b437bf2f5fd5ce2078f7787c3a12df609f7679d
bcs-app/backend/uniapps/application/base_views.py
python
BaseAPI.get_k8s_rs_info
(self, request, project_id, cluster_id, ns_name, resource_name)
return rs_name_list
获取k8s deployment副本信息
获取k8s deployment副本信息
[ "获取k8s", "deployment副本信息" ]
def get_k8s_rs_info(self, request, project_id, cluster_id, ns_name, resource_name): """获取k8s deployment副本信息""" ret_data = {} client = K8SClient(request.user.token.access_token, project_id, cluster_id, None) extra = {"data.metadata.ownerReferences.name": resource_name} extra_encode = base64_encode_params(extra) resp = client.get_rs({"extra": extra_encode, "namespace": ns_name, "field": "resourceName,data.status"}) if resp.get("code") != 0: raise error_codes.APIError.f(resp.get("message") or _("查询出现异常"), replace=True) data = resp.get("data") or [] if not data: return ret_data # NOTE: 因为线上存在revision history,需要忽略掉replica为0的rs rs_name_list = [ info["resourceName"] for info in data if info.get("resourceName") and getitems(info, ["data", "status", "replicas"], 0) > 0 ] return rs_name_list
[ "def", "get_k8s_rs_info", "(", "self", ",", "request", ",", "project_id", ",", "cluster_id", ",", "ns_name", ",", "resource_name", ")", ":", "ret_data", "=", "{", "}", "client", "=", "K8SClient", "(", "request", ".", "user", ".", "token", ".", "access_toke...
https://github.com/Tencent/bk-bcs-saas/blob/2b437bf2f5fd5ce2078f7787c3a12df609f7679d/bcs-app/backend/uniapps/application/base_views.py#L169-L188
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/parser/nltk_lite/semantics/logic.py
python
Parser.token
(self, destructive=1)
return None
Get the next waiting token. The destructive flag indicates whether the token will be removed from the buffer; setting it to 0 gives lookahead capability.
Get the next waiting token. The destructive flag indicates whether the token will be removed from the buffer; setting it to 0 gives lookahead capability.
[ "Get", "the", "next", "waiting", "token", ".", "The", "destructive", "flag", "indicates", "whether", "the", "token", "will", "be", "removed", "from", "the", "buffer", ";", "setting", "it", "to", "0", "gives", "lookahead", "capability", "." ]
def token(self, destructive=1): """Get the next waiting token. The destructive flag indicates whether the token will be removed from the buffer; setting it to 0 gives lookahead capability.""" if self.buffer == '': raise Error, "end of stream" tok = None buffer = self.buffer while not tok: seq = buffer.split(' ', 1) if len(seq) == 1: tok, buffer = seq[0], '' else: assert len(seq) == 2 tok, buffer = seq if tok: if destructive: self.buffer = buffer return tok assert 0 # control never gets here return None
[ "def", "token", "(", "self", ",", "destructive", "=", "1", ")", ":", "if", "self", ".", "buffer", "==", "''", ":", "raise", "Error", ",", "\"end of stream\"", "tok", "=", "None", "buffer", "=", "self", ".", "buffer", "while", "not", "tok", ":", "seq"...
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/parser/nltk_lite/semantics/logic.py#L583-L603
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/gdata/docs/data.py
python
CategoryFinder.is_hidden
(self)
return self.has_label(HIDDEN_LABEL)
Whether this Resource is hidden. Returns: Boolean value indicating that the resource is hidden.
Whether this Resource is hidden.
[ "Whether", "this", "Resource", "is", "hidden", "." ]
def is_hidden(self): """Whether this Resource is hidden. Returns: Boolean value indicating that the resource is hidden. """ return self.has_label(HIDDEN_LABEL)
[ "def", "is_hidden", "(", "self", ")", ":", "return", "self", ".", "has_label", "(", "HIDDEN_LABEL", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/docs/data.py#L292-L298
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/utilities/math_utils.py
python
get_lookat_matrix
(eye, center, up)
return result
Given the position of a camera, the point it is looking at, and an up-direction. Computes the lookat matrix that moves all vectors such that the camera is at the origin of the coordinate system, looking down the z-axis. Parameters ---------- eye : array_like The position of the camera. Must be 3D. center : array_like The location that the camera is looking at. Must be 3D. up : array_like The direction that is considered up for the camera. Must be 3D. Returns ------- lookat_matrix : ndarray A new 4x4 2D array in homogeneous coordinates. This matrix moves all vectors in the same way required to move the camera to the origin of the coordinate system, with it pointing down the negative z-axis.
Given the position of a camera, the point it is looking at, and an up-direction. Computes the lookat matrix that moves all vectors such that the camera is at the origin of the coordinate system, looking down the z-axis.
[ "Given", "the", "position", "of", "a", "camera", "the", "point", "it", "is", "looking", "at", "and", "an", "up", "-", "direction", ".", "Computes", "the", "lookat", "matrix", "that", "moves", "all", "vectors", "such", "that", "the", "camera", "is", "at",...
def get_lookat_matrix(eye, center, up): """ Given the position of a camera, the point it is looking at, and an up-direction. Computes the lookat matrix that moves all vectors such that the camera is at the origin of the coordinate system, looking down the z-axis. Parameters ---------- eye : array_like The position of the camera. Must be 3D. center : array_like The location that the camera is looking at. Must be 3D. up : array_like The direction that is considered up for the camera. Must be 3D. Returns ------- lookat_matrix : ndarray A new 4x4 2D array in homogeneous coordinates. This matrix moves all vectors in the same way required to move the camera to the origin of the coordinate system, with it pointing down the negative z-axis. """ eye = np.array(eye) center = np.array(center) up = np.array(up) f = (center - eye) / np.linalg.norm(center - eye) s = np.cross(f, up) / np.linalg.norm(np.cross(f, up)) u = np.cross(s, f) result = np.zeros((4, 4), dtype="float32", order="C") result[0][0] = s[0] result[0][1] = s[1] result[0][2] = s[2] result[1][0] = u[0] result[1][1] = u[1] result[1][2] = u[2] result[2][0] = -f[0] result[2][1] = -f[1] result[2][2] = -f[2] result[0][3] = -np.dot(s, eye) result[1][3] = -np.dot(u, eye) result[2][3] = np.dot(f, eye) result[3][3] = 1.0 return result
[ "def", "get_lookat_matrix", "(", "eye", ",", "center", ",", "up", ")", ":", "eye", "=", "np", ".", "array", "(", "eye", ")", "center", "=", "np", ".", "array", "(", "center", ")", "up", "=", "np", ".", "array", "(", "up", ")", "f", "=", "(", ...
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/utilities/math_utils.py#L1017-L1069
JenningsL/PointRCNN
36b5e3226a230dcc89e7bb6cdd8d31cb7cdf8136
models/projection.py
python
tf_rect_to_image
(pts3d, calib)
return tf.stack([ tf.gather(pts2d_hom, 0, axis=-1)/depth, tf.gather(pts2d_hom, 1, axis=-1)/depth, ], axis=-1)
Projects 3D points into image space Args: pts3d: a tensor of rect points in the shape [B, N, 3]. calib: tensor [3, 4] stereo camera calibration p2 matrix Returns: pts2d: a float32 tensor points in image space - B x N x [x, y]
Projects 3D points into image space
[ "Projects", "3D", "points", "into", "image", "space" ]
def tf_rect_to_image(pts3d, calib): """ Projects 3D points into image space Args: pts3d: a tensor of rect points in the shape [B, N, 3]. calib: tensor [3, 4] stereo camera calibration p2 matrix Returns: pts2d: a float32 tensor points in image space - B x N x [x, y] """ B = pts3d.shape[0] N = pts3d.shape[1] calib_expand = tf.tile(tf.expand_dims(calib, 1), [1,N,1,1]) # (B,N,3, 4) # pts3d_list = tf.reshape(B*N, 3) pts3d_hom = tf.concat([pts3d, tf.ones((B,N,1))], axis=-1) # (B,N,4) pts3d_hom = tf.expand_dims(pts3d_hom, axis=-1) # (B,N,4,1) pts2d_hom = tf.matmul(calib_expand, pts3d_hom) # (B,N,3,1) pts2d_hom = tf.squeeze(pts2d_hom, axis=-1) # (B,N,3) depth = tf.gather(pts2d_hom, 2, axis=-1) return tf.stack([ tf.gather(pts2d_hom, 0, axis=-1)/depth, tf.gather(pts2d_hom, 1, axis=-1)/depth, ], axis=-1)
[ "def", "tf_rect_to_image", "(", "pts3d", ",", "calib", ")", ":", "B", "=", "pts3d", ".", "shape", "[", "0", "]", "N", "=", "pts3d", ".", "shape", "[", "1", "]", "calib_expand", "=", "tf", ".", "tile", "(", "tf", ".", "expand_dims", "(", "calib", ...
https://github.com/JenningsL/PointRCNN/blob/36b5e3226a230dcc89e7bb6cdd8d31cb7cdf8136/models/projection.py#L5-L28
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/idlelib/EditorWindow.py
python
EditorWindow.config_dialog
(self, event=None)
[]
def config_dialog(self, event=None): configDialog.ConfigDialog(self.top,'Settings')
[ "def", "config_dialog", "(", "self", ",", "event", "=", "None", ")", ":", "configDialog", ".", "ConfigDialog", "(", "self", ".", "top", ",", "'Settings'", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/EditorWindow.py#L573-L574
OpenKMIP/PyKMIP
c0c980395660ea1b1a8009e97f17ab32d1100233
kmip/pie/objects.py
python
PrivateKey.validate
(self)
Verify that the contents of the PrivateKey object are valid. Raises: TypeError: if the types of any PrivateKey attributes are invalid.
Verify that the contents of the PrivateKey object are valid.
[ "Verify", "that", "the", "contents", "of", "the", "PrivateKey", "object", "are", "valid", "." ]
def validate(self): """ Verify that the contents of the PrivateKey object are valid. Raises: TypeError: if the types of any PrivateKey attributes are invalid. """ if not isinstance(self.value, bytes): raise TypeError("key value must be bytes") elif not isinstance(self.cryptographic_algorithm, enums.CryptographicAlgorithm): raise TypeError("key algorithm must be a CryptographicAlgorithm " "enumeration") elif not isinstance(self.cryptographic_length, six.integer_types): raise TypeError("key length must be an integer") elif not isinstance(self.key_format_type, enums.KeyFormatType): raise TypeError("key format type must be a KeyFormatType " "enumeration") elif self.key_format_type not in self._valid_formats: raise ValueError("key format type must be one of {0}".format( self._valid_formats)) # TODO (peter-hamilton) Verify that the key bytes match the key format mask_count = len(self.cryptographic_usage_masks) for i in range(mask_count): mask = self.cryptographic_usage_masks[i] if not isinstance(mask, enums.CryptographicUsageMask): position = "({0} in list)".format(i) raise TypeError( "key mask {0} must be a CryptographicUsageMask " "enumeration".format(position)) name_count = len(self.names) for i in range(name_count): name = self.names[i] if not isinstance(name, six.string_types): position = "({0} in list)".format(i) raise TypeError("key name {0} must be a string".format( position))
[ "def", "validate", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "value", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"key value must be bytes\"", ")", "elif", "not", "isinstance", "(", "self", ".", "cryptographic_algorithm", "...
https://github.com/OpenKMIP/PyKMIP/blob/c0c980395660ea1b1a8009e97f17ab32d1100233/kmip/pie/objects.py#L1035-L1074
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/oscrypto/_win/symmetric.py
python
rc2_cbc_pkcs5_decrypt
(key, data, iv)
return _decrypt('rc2', key, data, iv, True)
Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext
Decrypts RC2 ciphertext using a 64 bit key
[ "Decrypts", "RC2", "ciphertext", "using", "a", "64", "bit", "key" ]
def rc2_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt('rc2', key, data, iv, True)
[ "def", "rc2_cbc_pkcs5_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "<", "5", "or", "len", "(", "key", ")", ">", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 5 to 16 byt...
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/oscrypto/_win/symmetric.py#L335-L373
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/distutils/command/register.py
python
register.post_to_server
(self, data, auth=None)
return result
Post a query to the server, and return a string response.
Post a query to the server, and return a string response.
[ "Post", "a", "query", "to", "the", "server", "and", "return", "a", "string", "response", "." ]
def post_to_server(self, data, auth=None): ''' Post a query to the server, and return a string response. ''' if 'name' in data: self.announce('Registering %s to %s' % (data['name'], self.repository), log.INFO) # Build up the MIME payload for the urllib2 POST data boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = '\n--' + boundary end_boundary = sep_boundary + '--' chunks = [] for key, value in data.items(): # handle multiple entries for the same name if type(value) not in (type([]), type( () )): value = [value] for value in value: chunks.append(sep_boundary) chunks.append('\nContent-Disposition: form-data; name="%s"'%key) chunks.append("\n\n") chunks.append(value) if value and value[-1] == '\r': chunks.append('\n') # write an extra newline (lurve Macs) chunks.append(end_boundary) chunks.append("\n") # chunks may be bytes (str) or unicode objects that we need to encode body = [] for chunk in chunks: if isinstance(chunk, unicode): body.append(chunk.encode('utf-8')) else: body.append(chunk) body = ''.join(body) # build the Request headers = { 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'%boundary, 'Content-length': str(len(body)) } req = urllib2.Request(self.repository, body, headers) # handle HTTP and include the Basic Auth handler opener = urllib2.build_opener( urllib2.HTTPBasicAuthHandler(password_mgr=auth) ) data = '' try: result = opener.open(req) except urllib2.HTTPError, e: if self.show_response: data = e.fp.read() result = e.code, e.msg except urllib2.URLError, e: result = 500, str(e) else: if self.show_response: data = result.read() result = 200, 'OK' if self.show_response: dashes = '-' * 75 self.announce('%s%s%s' % (dashes, data, dashes)) return result
[ "def", "post_to_server", "(", "self", ",", "data", ",", "auth", "=", "None", ")", ":", "if", "'name'", "in", "data", ":", "self", ".", "announce", "(", "'Registering %s to %s'", "%", "(", "data", "[", "'name'", "]", ",", "self", ".", "repository", ")",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/distutils/command/register.py#L251-L315
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/future/backports/urllib/parse.py
python
DefragResultBytes.geturl
(self)
[]
def geturl(self): if self.fragment: return self.url + b'#' + self.fragment else: return self.url
[ "def", "geturl", "(", "self", ")", ":", "if", "self", ".", "fragment", ":", "return", "self", ".", "url", "+", "b'#'", "+", "self", ".", "fragment", "else", ":", "return", "self", ".", "url" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/backports/urllib/parse.py#L262-L266
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/core/io/interactive_commands/branching_prompt.py
python
BranchingPrompt.do_shell
(self, line)
Run a shell command. Ex: (orion) ! pwd
Run a shell command. Ex: (orion) ! pwd
[ "Run", "a", "shell", "command", ".", "Ex", ":", "(", "orion", ")", "!", "pwd" ]
def do_shell(self, line): """Run a shell command. Ex: (orion) ! pwd""" print("running shell command:", line) print(os.popen(line).read())
[ "def", "do_shell", "(", "self", ",", "line", ")", ":", "print", "(", "\"running shell command:\"", ",", "line", ")", "print", "(", "os", ".", "popen", "(", "line", ")", ".", "read", "(", ")", ")" ]
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/core/io/interactive_commands/branching_prompt.py#L253-L256
pyansys/pymapdl
c07291fc062b359abf0e92b95a92d753a95ef3d7
ansys/mapdl/core/_commands/solution/fe_forces.py
python
FeForces.fssect
(self, rho="", nev="", nlod="", kbr="", **kwargs)
return self.run(command, **kwargs)
Calculates and stores total linearized stress components. APDL Command: FSSECT Parameters ---------- rho In-plane (X-Y) average radius of curvature of the inside and outside surfaces of an axisymmetric section. If zero (or blank), a plane or 3-D structure is assumed. If nonzero, an axisymmetric structure is assumed. Use a suitably large number (see the Mechanical APDL Theory Reference) or use -1 for an axisymmetric straight section. nev Event number to be associated with these stresses (defaults to 1). nlod Loading number to be associated with these stresses (defaults to 1). kbr For an axisymmetric analysis (RHO ≠ 0): 0 - Include the thickness-direction bending stresses 1 - Ignore the thickness-direction bending stresses 2 - Include the thickness-direction bending stress using the same formula as the Y (axial direction ) bending stress. Also use the same formula for the shear stress. Notes ----- Calculates and stores the total linearized stress components at the ends of a section path [PATH] (as defined by the first two nodes with the PPATH command). The path must be entirely within the selected elements (that is, there must not be any element gaps along the path). Stresses are stored according to the fatigue event number and loading number specified. Locations (one for each node) are associated with those previously defined for these nodes [FL] or else they are automatically defined. Stresses are separated into six total components (SX through SXZ) and six membrane-plus-bending (SX through SXZ) components. The temperature at each end point and the current time are also stored along with the total stress components. Calculations are made from the stresses currently in the database (last SET or LCASE command). Stresses are stored as section coordinate components if axisymmetric or as global Cartesian coordinate components otherwise, regardless of the active results coordinate system [RSYS]. The FSLIST command may be used to list stresses. The FS command can be used to modify stored stresses. See also the PRSECT and PLSECT commands for similar calculations.
Calculates and stores total linearized stress components.
[ "Calculates", "and", "stores", "total", "linearized", "stress", "components", "." ]
def fssect(self, rho="", nev="", nlod="", kbr="", **kwargs): """Calculates and stores total linearized stress components. APDL Command: FSSECT Parameters ---------- rho In-plane (X-Y) average radius of curvature of the inside and outside surfaces of an axisymmetric section. If zero (or blank), a plane or 3-D structure is assumed. If nonzero, an axisymmetric structure is assumed. Use a suitably large number (see the Mechanical APDL Theory Reference) or use -1 for an axisymmetric straight section. nev Event number to be associated with these stresses (defaults to 1). nlod Loading number to be associated with these stresses (defaults to 1). kbr For an axisymmetric analysis (RHO ≠ 0): 0 - Include the thickness-direction bending stresses 1 - Ignore the thickness-direction bending stresses 2 - Include the thickness-direction bending stress using the same formula as the Y (axial direction ) bending stress. Also use the same formula for the shear stress. Notes ----- Calculates and stores the total linearized stress components at the ends of a section path [PATH] (as defined by the first two nodes with the PPATH command). The path must be entirely within the selected elements (that is, there must not be any element gaps along the path). Stresses are stored according to the fatigue event number and loading number specified. Locations (one for each node) are associated with those previously defined for these nodes [FL] or else they are automatically defined. Stresses are separated into six total components (SX through SXZ) and six membrane-plus-bending (SX through SXZ) components. The temperature at each end point and the current time are also stored along with the total stress components. Calculations are made from the stresses currently in the database (last SET or LCASE command). Stresses are stored as section coordinate components if axisymmetric or as global Cartesian coordinate components otherwise, regardless of the active results coordinate system [RSYS]. The FSLIST command may be used to list stresses. The FS command can be used to modify stored stresses. See also the PRSECT and PLSECT commands for similar calculations. """ command = f"FSSECT,{rho},{nev},{nlod},{kbr}" return self.run(command, **kwargs)
[ "def", "fssect", "(", "self", ",", "rho", "=", "\"\"", ",", "nev", "=", "\"\"", ",", "nlod", "=", "\"\"", ",", "kbr", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "command", "=", "f\"FSSECT,{rho},{nev},{nlod},{kbr}\"", "return", "self", ".", "run", ...
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/_commands/solution/fe_forces.py#L301-L356
skarra/ASynK
e908a1ad670a2d79f791a6a7539392e078a64add
lib/demjson.py
python
_nonnumber_float_constants
()
return nan, inf, neginf
Try to return the Nan, Infinity, and -Infinity float values. This is unnecessarily complex because there is no standard platform- independent way to do this in Python as the language (opposed to some implementation of it) doesn't discuss non-numbers. We try various strategies from the best to the worst. If this Python interpreter uses the IEEE 754 floating point standard then the returned values will probably be real instances of the 'float' type. Otherwise a custom class object is returned which will attempt to simulate the correct behavior as much as possible.
Try to return the Nan, Infinity, and -Infinity float values. This is unnecessarily complex because there is no standard platform- independent way to do this in Python as the language (opposed to some implementation of it) doesn't discuss non-numbers. We try various strategies from the best to the worst. If this Python interpreter uses the IEEE 754 floating point standard then the returned values will probably be real instances of the 'float' type. Otherwise a custom class object is returned which will attempt to simulate the correct behavior as much as possible.
[ "Try", "to", "return", "the", "Nan", "Infinity", "and", "-", "Infinity", "float", "values", ".", "This", "is", "unnecessarily", "complex", "because", "there", "is", "no", "standard", "platform", "-", "independent", "way", "to", "do", "this", "in", "Python", ...
def _nonnumber_float_constants(): """Try to return the Nan, Infinity, and -Infinity float values. This is unnecessarily complex because there is no standard platform- independent way to do this in Python as the language (opposed to some implementation of it) doesn't discuss non-numbers. We try various strategies from the best to the worst. If this Python interpreter uses the IEEE 754 floating point standard then the returned values will probably be real instances of the 'float' type. Otherwise a custom class object is returned which will attempt to simulate the correct behavior as much as possible. """ try: # First, try (mostly portable) float constructor. Works under # Linux x86 (gcc) and some Unices. nan = float('nan') inf = float('inf') neginf = float('-inf') except ValueError: try: # Try the AIX (PowerPC) float constructors nan = float('NaNQ') inf = float('INF') neginf = float('-INF') except ValueError: try: # Next, try binary unpacking. Should work under # platforms using IEEE 754 floating point. import struct, sys xnan = '7ff8000000000000'.decode('hex') # Quiet NaN xinf = '7ff0000000000000'.decode('hex') xcheck = 'bdc145651592979d'.decode('hex') # -3.14159e-11 # Could use float.__getformat__, but it is a new python feature, # so we use sys.byteorder. if sys.byteorder == 'big': nan = struct.unpack('d', xnan)[0] inf = struct.unpack('d', xinf)[0] check = struct.unpack('d', xcheck)[0] else: nan = struct.unpack('d', xnan[::-1])[0] inf = struct.unpack('d', xinf[::-1])[0] check = struct.unpack('d', xcheck[::-1])[0] neginf = - inf if check != -3.14159e-11: raise ValueError('Unpacking raw IEEE 754 floats does not work') except (ValueError, TypeError): # Punt, make some fake classes to simulate. These are # not perfect though. For instance nan * 1.0 == nan, # as expected, but 1.0 * nan == 0.0, which is wrong. class nan(float): """An approximation of the NaN (not a number) floating point number.""" def __repr__(self): return 'nan' def __str__(self): return 'nan' def __add__(self,x): return self def __radd__(self,x): return self def __sub__(self,x): return self def __rsub__(self,x): return self def __mul__(self,x): return self def __rmul__(self,x): return self def __div__(self,x): return self def __rdiv__(self,x): return self def __divmod__(self,x): return (self,self) def __rdivmod__(self,x): return (self,self) def __mod__(self,x): return self def __rmod__(self,x): return self def __pow__(self,exp): return self def __rpow__(self,exp): return self def __neg__(self): return self def __pos__(self): return self def __abs__(self): return self def __lt__(self,x): return False def __le__(self,x): return False def __eq__(self,x): return False def __neq__(self,x): return True def __ge__(self,x): return False def __gt__(self,x): return False def __complex__(self,*a): raise NotImplementedError('NaN can not be converted to a complex') if decimal: nan = decimal.Decimal('NaN') else: nan = nan() class inf(float): """An approximation of the +Infinity floating point number.""" def __repr__(self): return 'inf' def __str__(self): return 'inf' def __add__(self,x): return self def __radd__(self,x): return self def __sub__(self,x): return self def __rsub__(self,x): return self def __mul__(self,x): if x is neginf or x < 0: return neginf elif x == 0: return nan else: return self def __rmul__(self,x): return self.__mul__(x) def __div__(self,x): if x == 0: raise ZeroDivisionError('float division') elif x < 0: return neginf else: return self def __rdiv__(self,x): if x is inf or x is neginf or x is nan: return nan return 0.0 def __divmod__(self,x): if x == 0: raise ZeroDivisionError('float divmod()') elif x < 0: return (nan,nan) else: return (self,self) def __rdivmod__(self,x): if x is inf or x is neginf or x is nan: return (nan, nan) return (0.0, x) def __mod__(self,x): if x == 0: raise ZeroDivisionError('float modulo') else: return nan def __rmod__(self,x): if x is inf or x is neginf or x is nan: return nan return x def __pow__(self, exp): if exp == 0: return 1.0 else: return self def __rpow__(self, x): if -1 < x < 1: return 0.0 elif x == 1.0: return 1.0 elif x is nan or x is neginf or x < 0: return nan else: return self def __neg__(self): return neginf def __pos__(self): return self def __abs__(self): return self def __lt__(self,x): return False def __le__(self,x): if x is self: return True else: return False def __eq__(self,x): if x is self: return True else: return False def __neq__(self,x): if x is self: return False else: return True def __ge__(self,x): return True def __gt__(self,x): return True def __complex__(self,*a): raise NotImplementedError('Infinity can not be converted to a complex') if decimal: inf = decimal.Decimal('Infinity') else: inf = inf() class neginf(float): """An approximation of the -Infinity floating point number.""" def __repr__(self): return '-inf' def __str__(self): return '-inf' def __add__(self,x): return self def __radd__(self,x): return self def __sub__(self,x): return self def __rsub__(self,x): return self def __mul__(self,x): if x is self or x < 0: return inf elif x == 0: return nan else: return self def __rmul__(self,x): return self.__mul__(self) def __div__(self,x): if x == 0: raise ZeroDivisionError('float division') elif x < 0: return inf else: return self def __rdiv__(self,x): if x is inf or x is neginf or x is nan: return nan return -0.0 def __divmod__(self,x): if x == 0: raise ZeroDivisionError('float divmod()') elif x < 0: return (nan,nan) else: return (self,self) def __rdivmod__(self,x): if x is inf or x is neginf or x is nan: return (nan, nan) return (-0.0, x) def __mod__(self,x): if x == 0: raise ZeroDivisionError('float modulo') else: return nan def __rmod__(self,x): if x is inf or x is neginf or x is nan: return nan return x def __pow__(self,exp): if exp == 0: return 1.0 else: return self def __rpow__(self, x): if x is nan or x is inf or x is inf: return nan return 0.0 def __neg__(self): return inf def __pos__(self): return self def __abs__(self): return inf def __lt__(self,x): return True def __le__(self,x): return True def __eq__(self,x): if x is self: return True else: return False def __neq__(self,x): if x is self: return False else: return True def __ge__(self,x): if x is self: return True else: return False def __gt__(self,x): return False def __complex__(self,*a): raise NotImplementedError('-Infinity can not be converted to a complex') if decimal: neginf = decimal.Decimal('-Infinity') else: neginf = neginf(0) return nan, inf, neginf
[ "def", "_nonnumber_float_constants", "(", ")", ":", "try", ":", "# First, try (mostly portable) float constructor. Works under", "# Linux x86 (gcc) and some Unices.", "nan", "=", "float", "(", "'nan'", ")", "inf", "=", "float", "(", "'inf'", ")", "neginf", "=", "float"...
https://github.com/skarra/ASynK/blob/e908a1ad670a2d79f791a6a7539392e078a64add/lib/demjson.py#L231-L483