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
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
controllers/med.py
python
hospital
()
return s3_rest_controller(rheader = med_hospital_rheader)
Main REST controller for Hospitals
Main REST controller for Hospitals
[ "Main", "REST", "controller", "for", "Hospitals" ]
def hospital(): """ Main REST controller for Hospitals """ # Custom Method to Assign HRs from s3db.hrm import hrm_AssignMethod s3db.set_method("med", "hospital", method = "assign", action = hrm_AssignMethod(component = "human_resource_site"), ) # Pre-processor def prep(r): # Function to call for all Site Instance Types from s3db.org import org_site_prep org_site_prep(r) if r.interactive: if r.component: cname = r.component_name if cname == "status": table = db.med_hospital_status table.facility_status.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Facility Status"), T("Status of the facility."), ), ) table.facility_operations.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Facility Operations"), T("Overall status of the facility operations."), ), ) table.clinical_status.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Clinical Status"), T("Status of the clinical departments."), ), ) table.clinical_operations.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Clinical Operations"), T("Overall status of the clinical operations."), ), ) table.ems_status.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Emergency Medical Services"), T("Status of operations/availability of emergency medical services at this facility."), ), ) table.ems_reason.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("EMS Status Reasons"), T("Report the contributing factors for the current EMS status."), ), ) table.or_status.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("OR Status"), T("Status of the operating rooms of this facility."), ), ) table.or_reason.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("OR Status Reason"), T("Report the contributing factors for the current OR status."), ), ) table.morgue_status.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Morgue Status"), T("Status of morgue capacity."), ), ) table.morgue_units.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Morgue Units Available"), T("Number of vacant/available units to which victims can be transported immediately."), ), ) table.security_status.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Security Status"), T("Status of security procedures/access restrictions for the facility."), ), ) table.staffing.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Staffing Level"), T("Current staffing level at the facility."), ), ) table.access_status.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Road Conditions"), T("Describe the condition of the roads from/to the facility."), ), ) elif cname == "bed_capacity": table = db.med_bed_capacity table.bed_type.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Bed Type"), T("Specify the bed type of this unit."), ), ) table.beds_baseline.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Baseline Number of Beds"), T("Baseline number of beds of that type in this unit."), ), ) table.beds_available.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Available Beds"), T("Number of available/vacant beds of that type in this unit at the time of reporting."), ), ) table.beds_add24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Additional Beds / 24hrs"), T("Number of additional beds of that type expected to become available in this unit within the next 24 hours."), ), ) elif cname == "activity": table = db.med_hospital_activity table.date.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Date & Time"), T("Date and time this report relates to."), ), ) table.patients.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Patients"), T("Number of in-patients at the time of reporting."), ), ) table.admissions24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Admissions/24hrs"), T("Number of newly admitted patients during the past 24 hours."), ), ) table.discharges24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Discharges/24hrs"), T("Number of discharged patients during the past 24 hours."), ), ) table.deaths24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Deaths/24hrs"), T("Number of deaths during the past 24 hours."), ), ) elif cname == "image": table = s3db.doc_image table.location_id.readable = table.location_id.writable = False table.organisation_id.readable = table.organisation_id.writable = False table.person_id.readable = table.person_id.writable = False elif cname == "ctc": table = db.med_ctc table.ctc.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Cholera Treatment Center"), T("Does this facility provide a cholera treatment center?"), ), ) table.number_of_patients.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Current number of patients"), T("How many patients with the disease are currently hospitalized at this facility?"), ), ) table.cases_24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("New cases in the past 24h"), T("How many new cases have been admitted to this facility in the past 24h?"), ), ) table.deaths_24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Deaths in the past 24h"), T("How many of the patients with the disease died in the past 24h at this facility?"), ), ) table.icaths_available.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Infusion catheters available"), T("Specify the number of available sets"), ), ) table.icaths_needed_24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Infusion catheters need per 24h"), T("Specify the number of sets needed per 24h"), ), ) table.infusions_available.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Infusions available"), T("Specify the number of available units (litres) of Ringer-Lactate or equivalent solutions"), ), ) table.infusions_needed_24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Infusions needed per 24h"), T("Specify the number of units (litres) of Ringer-Lactate or equivalent solutions needed per 24h"), ), ) table.antibiotics_available.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Antibiotics available"), T("Specify the number of available units (adult doses)"), ), ) table.antibiotics_needed_24.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Antibiotics needed per 24h"), T("Specify the number of units (adult doses) needed per 24h"), ), ) table.problem_types.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Current problems, categories"), T("Select all that apply"), ), ) table.problem_details.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Current problems, details"), T("Please specify any problems and obstacles with the proper handling of the disease, in detail (in numbers, where appropriate). You may also add suggestions the situation could be improved."), ), ) else: # No Component table = r.table if settings.get_med_have(): # HAVE compliance table.town.label = T("Town") components_get = s3db.resource("med_hospital").components.get # UID assigned by Local Government gov_uuid = components_get("gov_uuid") f = gov_uuid.table.value f.requires = IS_EMPTY_OR([IS_LENGTH(128), IS_NOT_ONE_OF(db, "org_site_tag.value"), ]) f.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Government UID"), T("The Unique Identifier (UUID) as assigned to this facility by the government."), ), ) from s3 import S3LocationFilter, S3OptionsFilter, S3RangeFilter, S3TextFilter stable = s3db.med_hospital_status filter_widgets = [ S3TextFilter(["name", "code", "comments", "organisation_id$name", "organisation_id$acronym", "location_id$name", "location_id$L1", "location_id$L2", ], label = T("Name"), _class = "filter-search", ), S3OptionsFilter("facility_type", label = T("Type"), #hidden = True, ), S3LocationFilter("location_id", label = T("Location"), levels = ("L0", "L1", "L2"), #hidden = True, ), S3OptionsFilter("status.facility_status", label = T("Status"), options = stable.facility_status.represent.options, #represent = "%(name)s", #hidden = True, ), S3OptionsFilter("status.power_supply_type", label = T("Power"), options = stable.power_supply_type.represent.options, #represent = "%(name)s", #hidden = True, ), S3OptionsFilter("bed_capacity.bed_type", label = T("Bed Type"), options = s3db.med_bed_capacity.bed_type.represent.options, #represent = "%(name)s", #hidden = True, ), S3RangeFilter("total_beds", label = T("Total Beds"), #represent = "%(name)s", #hidden = True, ), ] s3db.configure("med_hospital", filter_widgets = filter_widgets, ) s3.formats["have"] = r.url() # .have added by JS # Add comments table.total_beds.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Total Beds"), T("Total number of beds in this facility. Automatically updated from daily reports."), ), ) table.available_beds.comment = DIV(_class = "tooltip", _title = "%s|%s" % (T("Available Beds"), T("Number of vacant/available beds in this facility. Automatically updated from daily reports."), ), ) elif r.representation == "plain": # Duplicates info in the other fields r.table.location_id.readable = False return True s3.prep = prep from s3db.med import med_hospital_rheader return s3_rest_controller(rheader = med_hospital_rheader)
[ "def", "hospital", "(", ")", ":", "# Custom Method to Assign HRs", "from", "s3db", ".", "hrm", "import", "hrm_AssignMethod", "s3db", ".", "set_method", "(", "\"med\"", ",", "\"hospital\"", ",", "method", "=", "\"assign\"", ",", "action", "=", "hrm_AssignMethod", ...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/controllers/med.py#L38-L344
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbShangPin.taobao_item_img_upload
( self, num_iid, id='', position='', image='', is_major='false', is_rectangle='false' )
return self._top_request( "taobao.item.img.upload", { "num_iid": num_iid, "id": id, "position": position, "image": image, "is_major": is_major, "is_rectangle": is_rectangle }, result_processor=lambda x: x["item_img"] )
添加商品图片 添加一张商品图片到num_iid指定的商品中 传入的num_iid所对应的商品必须属于当前会话的用户 如果更新图片需要设置itemimg_id,且该itemimg_id的图片记录需要属于传入的num_iid对应的商品。如果新增图片则不用设置 。 使用taobao.item.seller.get中返回的item_imgs字段获取图片id。 商品图片有数量和大小上的限制,根据卖家享有的服务(如:卖家订购了多图服务等),商品图片数量限制不同。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=23 :param num_iid: 商品数字ID,该参数必须 :param id: 商品图片id(如果是更新图片,则需要传该参数) :param position: 图片序号 :param image: 商品图片内容类型:JPG,GIF;最大:3M 。支持的文件类型:gif,jpg,jpeg,png :param is_major: 是否将该图片设为主图,可选值:true,false;默认值:false(非主图) :param is_rectangle: 是否3:4长方形图片,绑定3:4主图视频时用于上传3:4商品主图
添加商品图片 添加一张商品图片到num_iid指定的商品中 传入的num_iid所对应的商品必须属于当前会话的用户 如果更新图片需要设置itemimg_id,且该itemimg_id的图片记录需要属于传入的num_iid对应的商品。如果新增图片则不用设置 。 使用taobao.item.seller.get中返回的item_imgs字段获取图片id。 商品图片有数量和大小上的限制,根据卖家享有的服务(如:卖家订购了多图服务等),商品图片数量限制不同。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=23
[ "添加商品图片", "添加一张商品图片到num_iid指定的商品中", "传入的num_iid所对应的商品必须属于当前会话的用户", "如果更新图片需要设置itemimg_id,且该itemimg_id的图片记录需要属于传入的num_iid对应的商品。如果新增图片则不用设置", "。", "使用taobao", ".", "item", ".", "seller", ".", "get中返回的item_imgs字段获取图片id。", "商品图片有数量和大小上的限制,根据卖家享有的服务(如:卖家订购了多图服务等),商品图片数量限制不同。", "文档地址:https", "...
def taobao_item_img_upload( self, num_iid, id='', position='', image='', is_major='false', is_rectangle='false' ): """ 添加商品图片 添加一张商品图片到num_iid指定的商品中 传入的num_iid所对应的商品必须属于当前会话的用户 如果更新图片需要设置itemimg_id,且该itemimg_id的图片记录需要属于传入的num_iid对应的商品。如果新增图片则不用设置 。 使用taobao.item.seller.get中返回的item_imgs字段获取图片id。 商品图片有数量和大小上的限制,根据卖家享有的服务(如:卖家订购了多图服务等),商品图片数量限制不同。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=23 :param num_iid: 商品数字ID,该参数必须 :param id: 商品图片id(如果是更新图片,则需要传该参数) :param position: 图片序号 :param image: 商品图片内容类型:JPG,GIF;最大:3M 。支持的文件类型:gif,jpg,jpeg,png :param is_major: 是否将该图片设为主图,可选值:true,false;默认值:false(非主图) :param is_rectangle: 是否3:4长方形图片,绑定3:4主图视频时用于上传3:4商品主图 """ return self._top_request( "taobao.item.img.upload", { "num_iid": num_iid, "id": id, "position": position, "image": image, "is_major": is_major, "is_rectangle": is_rectangle }, result_processor=lambda x: x["item_img"] )
[ "def", "taobao_item_img_upload", "(", "self", ",", "num_iid", ",", "id", "=", "''", ",", "position", "=", "''", ",", "image", "=", "''", ",", "is_major", "=", "'false'", ",", "is_rectangle", "=", "'false'", ")", ":", "return", "self", ".", "_top_request"...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L11222-L11258
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/PDB/internal_coords.py
python
Edron.gen_key
(lst: Union[List[str], List["AtomKey"]])
Generate string of ':'-joined AtomKey strings from input. :param lst: list of AtomKey objects or id strings
Generate string of ':'-joined AtomKey strings from input.
[ "Generate", "string", "of", ":", "-", "joined", "AtomKey", "strings", "from", "input", "." ]
def gen_key(lst: Union[List[str], List["AtomKey"]]) -> str: """Generate string of ':'-joined AtomKey strings from input. :param lst: list of AtomKey objects or id strings """ if isinstance(lst[0], str): lst = cast(List[str], lst) return ":".join(lst) else: lst = cast(List[AtomKey], lst) return ":".join(ak.id for ak in lst)
[ "def", "gen_key", "(", "lst", ":", "Union", "[", "List", "[", "str", "]", ",", "List", "[", "\"AtomKey\"", "]", "]", ")", "->", "str", ":", "if", "isinstance", "(", "lst", "[", "0", "]", ",", "str", ")", ":", "lst", "=", "cast", "(", "List", ...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/PDB/internal_coords.py#L2621-L2631
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/decimal.py
python
Context.copy_sign
(self, a, b)
return a.copy_sign(b)
Copies the second operand's sign to the first one. In detail, it returns a copy of the first operand with the sign equal to the sign of the second operand. >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) Decimal('1.50') >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) Decimal('1.50') >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) Decimal('-1.50') >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) Decimal('-1.50') >>> ExtendedContext.copy_sign(1, -2) Decimal('-1') >>> ExtendedContext.copy_sign(Decimal(1), -2) Decimal('-1') >>> ExtendedContext.copy_sign(1, Decimal(-2)) Decimal('-1')
Copies the second operand's sign to the first one.
[ "Copies", "the", "second", "operand", "s", "sign", "to", "the", "first", "one", "." ]
def copy_sign(self, a, b): """Copies the second operand's sign to the first one. In detail, it returns a copy of the first operand with the sign equal to the sign of the second operand. >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) Decimal('1.50') >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) Decimal('1.50') >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) Decimal('-1.50') >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) Decimal('-1.50') >>> ExtendedContext.copy_sign(1, -2) Decimal('-1') >>> ExtendedContext.copy_sign(Decimal(1), -2) Decimal('-1') >>> ExtendedContext.copy_sign(1, Decimal(-2)) Decimal('-1') """ a = _convert_other(a, raiseit=True) return a.copy_sign(b)
[ "def", "copy_sign", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "copy_sign", "(", "b", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/decimal.py#L4167-L4189
shellphish/ictf-framework
c0384f12060cf47442a52f516c6e78bd722f208a
gamebot/dbapi.py
python
DBApi.get_full_game_state
(self)
return DBApi._get_json_response(target_url, target_logger=self.log)
Get the game state API: /game/state :return: A huge dict that contains almost everything
Get the game state API: /game/state :return: A huge dict that contains almost everything
[ "Get", "the", "game", "state", "API", ":", "/", "game", "/", "state", ":", "return", ":", "A", "huge", "dict", "that", "contains", "almost", "everything" ]
def get_full_game_state(self): """ Get the game state API: /game/state :return: A huge dict that contains almost everything """ target_url = self.__build_url(DBApi.GET_FULL_GAME_STATE) return DBApi._get_json_response(target_url, target_logger=self.log)
[ "def", "get_full_game_state", "(", "self", ")", ":", "target_url", "=", "self", ".", "__build_url", "(", "DBApi", ".", "GET_FULL_GAME_STATE", ")", "return", "DBApi", ".", "_get_json_response", "(", "target_url", ",", "target_logger", "=", "self", ".", "log", "...
https://github.com/shellphish/ictf-framework/blob/c0384f12060cf47442a52f516c6e78bd722f208a/gamebot/dbapi.py#L202-L209
libertysoft3/saidit
271c7d03adb369f82921d811360b00812e42da24
r2/r2/lib/utils/utils.py
python
epoch_timestamp
(dt)
return (dt - EPOCH).total_seconds()
Returns the number of seconds from the epoch to date. :param datetime dt: datetime (with time zone) :rtype: float
Returns the number of seconds from the epoch to date.
[ "Returns", "the", "number", "of", "seconds", "from", "the", "epoch", "to", "date", "." ]
def epoch_timestamp(dt): """Returns the number of seconds from the epoch to date. :param datetime dt: datetime (with time zone) :rtype: float """ return (dt - EPOCH).total_seconds()
[ "def", "epoch_timestamp", "(", "dt", ")", ":", "return", "(", "dt", "-", "EPOCH", ")", ".", "total_seconds", "(", ")" ]
https://github.com/libertysoft3/saidit/blob/271c7d03adb369f82921d811360b00812e42da24/r2/r2/lib/utils/utils.py#L2017-L2023
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/dav.py
python
dav.get_root_probability
(self)
return 0.8
:return: This method returns the probability of getting a root shell using this attack plugin. This is used by the "exploit *" function to order the plugins and first try to exploit the more critical ones. This method should return 0 for an exploit that will never return a root shell, and 1 for an exploit that WILL ALWAYS return a root shell.
:return: This method returns the probability of getting a root shell using this attack plugin. This is used by the "exploit *" function to order the plugins and first try to exploit the more critical ones. This method should return 0 for an exploit that will never return a root shell, and 1 for an exploit that WILL ALWAYS return a root shell.
[ ":", "return", ":", "This", "method", "returns", "the", "probability", "of", "getting", "a", "root", "shell", "using", "this", "attack", "plugin", ".", "This", "is", "used", "by", "the", "exploit", "*", "function", "to", "order", "the", "plugins", "and", ...
def get_root_probability(self): """ :return: This method returns the probability of getting a root shell using this attack plugin. This is used by the "exploit *" function to order the plugins and first try to exploit the more critical ones. This method should return 0 for an exploit that will never return a root shell, and 1 for an exploit that WILL ALWAYS return a root shell. """ return 0.8
[ "def", "get_root_probability", "(", "self", ")", ":", "return", "0.8" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/dav.py#L125-L134
amosbastian/fpl
141e10d315df3f886b103ce4351e8e56a96489f8
fpl/models/fixture.py
python
Fixture.get_assisters
(self)
Returns all players who made an assist in the fixture. :rtype: dict
Returns all players who made an assist in the fixture.
[ "Returns", "all", "players", "who", "made", "an", "assist", "in", "the", "fixture", "." ]
def get_assisters(self): """Returns all players who made an assist in the fixture. :rtype: dict """ try: return self.stats["assists"] except KeyError: return {"a": [], "h": []}
[ "def", "get_assisters", "(", "self", ")", ":", "try", ":", "return", "self", ".", "stats", "[", "\"assists\"", "]", "except", "KeyError", ":", "return", "{", "\"a\"", ":", "[", "]", ",", "\"h\"", ":", "[", "]", "}" ]
https://github.com/amosbastian/fpl/blob/141e10d315df3f886b103ce4351e8e56a96489f8/fpl/models/fixture.py#L31-L39
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/asyncio/selector_events.py
python
_test_selector_event
(selector, fd, event)
[]
def _test_selector_event(selector, fd, event): # Test if the selector is monitoring 'event' events # for the file descriptor 'fd'. try: key = selector.get_key(fd) except KeyError: return False else: return bool(key.events & event)
[ "def", "_test_selector_event", "(", "selector", ",", "fd", ",", "event", ")", ":", "# Test if the selector is monitoring 'event' events", "# for the file descriptor 'fd'.", "try", ":", "key", "=", "selector", ".", "get_key", "(", "fd", ")", "except", "KeyError", ":", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/asyncio/selector_events.py#L31-L39
Yelp/paasta
6c08c04a577359509575c794b973ea84d72accf9
paasta_tools/paastaapi/model/kubernetes_replica_set.py
python
KubernetesReplicaSet.openapi_types
()
return { 'create_timestamp': (float,), # noqa: E501 'name': (str,), # noqa: E501 'ready_replicas': (int,), # noqa: E501 'replicas': (int,), # noqa: E501 'git_sha': (str, none_type,), # noqa: E501 'config_sha': (str, none_type,), # noqa: E501 }
This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type.
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { 'create_timestamp': (float,), # noqa: E501 'name': (str,), # noqa: E501 'ready_replicas': (int,), # noqa: E501 'replicas': (int,), # noqa: E501 'git_sha': (str, none_type,), # noqa: E501 'config_sha': (str, none_type,), # noqa: E501 }
[ "def", "openapi_types", "(", ")", ":", "return", "{", "'create_timestamp'", ":", "(", "float", ",", ")", ",", "# noqa: E501", "'name'", ":", "(", "str", ",", ")", ",", "# noqa: E501", "'ready_replicas'", ":", "(", "int", ",", ")", ",", "# noqa: E501", "'...
https://github.com/Yelp/paasta/blob/6c08c04a577359509575c794b973ea84d72accf9/paasta_tools/paastaapi/model/kubernetes_replica_set.py#L69-L85
huntfx/MouseTracks
4dfab6386f9461be77cb19b54c9c498d74fb4ef6
mousetracks/image/animation.py
python
TrackHistory._step_range
(self, steps)
[]
def _step_range(self, steps): try: return self._CACHE['Steps'][steps] except KeyError: self._CACHE['Steps'][steps] = list(range(steps)) return self._CACHE['Steps'][steps]
[ "def", "_step_range", "(", "self", ",", "steps", ")", ":", "try", ":", "return", "self", ".", "_CACHE", "[", "'Steps'", "]", "[", "steps", "]", "except", "KeyError", ":", "self", ".", "_CACHE", "[", "'Steps'", "]", "[", "steps", "]", "=", "list", "...
https://github.com/huntfx/MouseTracks/blob/4dfab6386f9461be77cb19b54c9c498d74fb4ef6/mousetracks/image/animation.py#L32-L37
SirVer/ultisnips
2c83e40ce66814bf813457bb58ea96184ab9bb81
pythonx/UltiSnips/snippet_manager.py
python
SnippetManager.snippets_in_current_scope
(self, search_all)
Returns the snippets that could be expanded to Vim as a global variable.
Returns the snippets that could be expanded to Vim as a global variable.
[ "Returns", "the", "snippets", "that", "could", "be", "expanded", "to", "Vim", "as", "a", "global", "variable", "." ]
def snippets_in_current_scope(self, search_all): """Returns the snippets that could be expanded to Vim as a global variable.""" before = "" if search_all else vim_helper.buf.line_till_cursor snippets = self._snips(before, True) # Sort snippets alphabetically snippets.sort(key=lambda x: x.trigger) for snip in snippets: description = snip.description[ snip.description.find(snip.trigger) + len(snip.trigger) + 2 : ] location = snip.location if snip.location else "" key = snip.trigger # remove surrounding "" or '' in snippet description if it exists if len(description) > 2: if description[0] == description[-1] and description[0] in "'\"": description = description[1:-1] vim_helper.command( "let g:current_ulti_dict['{key}'] = '{val}'".format( key=key.replace("'", "''"), val=description.replace("'", "''") ) ) if search_all: vim_helper.command( ( "let g:current_ulti_dict_info['{key}'] = {{" "'description': '{description}'," "'location': '{location}'," "}}" ).format( key=key.replace("'", "''"), location=location.replace("'", "''"), description=description.replace("'", "''"), ) )
[ "def", "snippets_in_current_scope", "(", "self", ",", "search_all", ")", ":", "before", "=", "\"\"", "if", "search_all", "else", "vim_helper", ".", "buf", ".", "line_till_cursor", "snippets", "=", "self", ".", "_snips", "(", "before", ",", "True", ")", "# So...
https://github.com/SirVer/ultisnips/blob/2c83e40ce66814bf813457bb58ea96184ab9bb81/pythonx/UltiSnips/snippet_manager.py#L196-L236
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventType.get_guest_admin_signed_in_via_trusted_teams
(self)
return self._value
(logins) Started trusted team admin session Only call this if :meth:`is_guest_admin_signed_in_via_trusted_teams` is true. :rtype: GuestAdminSignedInViaTrustedTeamsType
(logins) Started trusted team admin session
[ "(", "logins", ")", "Started", "trusted", "team", "admin", "session" ]
def get_guest_admin_signed_in_via_trusted_teams(self): """ (logins) Started trusted team admin session Only call this if :meth:`is_guest_admin_signed_in_via_trusted_teams` is true. :rtype: GuestAdminSignedInViaTrustedTeamsType """ if not self.is_guest_admin_signed_in_via_trusted_teams(): raise AttributeError("tag 'guest_admin_signed_in_via_trusted_teams' not set") return self._value
[ "def", "get_guest_admin_signed_in_via_trusted_teams", "(", "self", ")", ":", "if", "not", "self", ".", "is_guest_admin_signed_in_via_trusted_teams", "(", ")", ":", "raise", "AttributeError", "(", "\"tag 'guest_admin_signed_in_via_trusted_teams' not set\"", ")", "return", "sel...
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L33663-L33673
maqp/tfc
4bb13da1f19671e1e723db7e8a21be58847209af
src/common/path.py
python
Completer.path_complete
(self, args: Optional[List[str]] = None)
return self.complete_path(args[-1])
Return the list of directories from the current directory.
Return the list of directories from the current directory.
[ "Return", "the", "list", "of", "directories", "from", "the", "current", "directory", "." ]
def path_complete(self, args: Optional[List[str]] = None) -> Any: """Return the list of directories from the current directory.""" if not args: return self.complete_path('.') # Treat the last arg as a path and complete it return self.complete_path(args[-1])
[ "def", "path_complete", "(", "self", ",", "args", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ")", "->", "Any", ":", "if", "not", "args", ":", "return", "self", ".", "complete_path", "(", "'.'", ")", "# Treat the last arg as a path a...
https://github.com/maqp/tfc/blob/4bb13da1f19671e1e723db7e8a21be58847209af/src/common/path.py#L107-L113
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/api/resources/__init__.py
python
CouchResourceMixin.detail_uri_kwargs
(self, bundle_or_obj)
return { 'pk': get_obj(bundle_or_obj)._id }
[]
def detail_uri_kwargs(self, bundle_or_obj): return { 'pk': get_obj(bundle_or_obj)._id }
[ "def", "detail_uri_kwargs", "(", "self", ",", "bundle_or_obj", ")", ":", "return", "{", "'pk'", ":", "get_obj", "(", "bundle_or_obj", ")", ".", "_id", "}" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/api/resources/__init__.py#L215-L218
pyatom/pyatom
a170717408d46f5d872585a877ffd8ee09a1a052
atomac/AXClasses.py
python
BaseAXUIElement._findFirst
(self, **kwargs)
Return the first object that matches the criteria.
Return the first object that matches the criteria.
[ "Return", "the", "first", "object", "that", "matches", "the", "criteria", "." ]
def _findFirst(self, **kwargs): """Return the first object that matches the criteria.""" for item in self._generateFind(**kwargs): return item
[ "def", "_findFirst", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "item", "in", "self", ".", "_generateFind", "(", "*", "*", "kwargs", ")", ":", "return", "item" ]
https://github.com/pyatom/pyatom/blob/a170717408d46f5d872585a877ffd8ee09a1a052/atomac/AXClasses.py#L739-L742
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/itsdangerous.py
python
Signer.verify_signature
(self, value, sig)
return self.algorithm.verify_signature(key, value, sig)
Verifies the signature for the given value.
Verifies the signature for the given value.
[ "Verifies", "the", "signature", "for", "the", "given", "value", "." ]
def verify_signature(self, value, sig): """Verifies the signature for the given value.""" key = self.derive_key() try: sig = base64_decode(sig) except Exception: return False return self.algorithm.verify_signature(key, value, sig)
[ "def", "verify_signature", "(", "self", ",", "value", ",", "sig", ")", ":", "key", "=", "self", ".", "derive_key", "(", ")", "try", ":", "sig", "=", "base64_decode", "(", "sig", ")", "except", "Exception", ":", "return", "False", "return", "self", ".",...
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/itsdangerous.py#L355-L362
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/api_client.py
python
ApiClient.select_header_content_type
(self, content_types)
Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json).
Returns `Content-Type` based on an array of content_types provided.
[ "Returns", "Content", "-", "Type", "based", "on", "an", "array", "of", "content_types", "provided", "." ]
def select_header_content_type(self, content_types): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). """ if not content_types: return 'application/json' content_types = [x.lower() for x in content_types] if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: return content_types[0]
[ "def", "select_header_content_type", "(", "self", ",", "content_types", ")", ":", "if", "not", "content_types", ":", "return", "'application/json'", "content_types", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "content_types", "]", "if", "'applica...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api_client.py#L497-L511
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/db/backends/oracle/base.py
python
DatabaseOperations._get_sequence_name
(self, table)
return '%s_SQ' % util.truncate_name(table, name_length).upper()
[]
def _get_sequence_name(self, table): name_length = self.max_name_length() - 3 return '%s_SQ' % util.truncate_name(table, name_length).upper()
[ "def", "_get_sequence_name", "(", "self", ",", "table", ")", ":", "name_length", "=", "self", ".", "max_name_length", "(", ")", "-", "3", "return", "'%s_SQ'", "%", "util", ".", "truncate_name", "(", "table", ",", "name_length", ")", ".", "upper", "(", ")...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/db/backends/oracle/base.py#L403-L405
quic/aimet
dae9bae9a77ca719aa7553fefde4768270fc3518
TrainingExtensions/common/src/python/aimet_common/winnow/mask.py
python
Mask.propagate_internal_connectivity_out_channels_to_in_channels
(self)
Based on the internal connectivity, propagates the output channel masks to input channel masks
Based on the internal connectivity, propagates the output channel masks to input channel masks
[ "Based", "on", "the", "internal", "connectivity", "propagates", "the", "output", "channel", "masks", "to", "input", "channel", "masks" ]
def propagate_internal_connectivity_out_channels_to_in_channels(self): """ Based on the internal connectivity, propagates the output channel masks to input channel masks""" # The last module doesn't have output channel mask if self._output_channel_masks: if self._internal_connectivity is not None: self._internal_connectivity.backward_propagate_the_masks(self._output_channel_masks, self._input_channel_masks)
[ "def", "propagate_internal_connectivity_out_channels_to_in_channels", "(", "self", ")", ":", "# The last module doesn't have output channel mask", "if", "self", ".", "_output_channel_masks", ":", "if", "self", ".", "_internal_connectivity", "is", "not", "None", ":", "self", ...
https://github.com/quic/aimet/blob/dae9bae9a77ca719aa7553fefde4768270fc3518/TrainingExtensions/common/src/python/aimet_common/winnow/mask.py#L816-L823
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/logic/algorithms/dpll2.py
python
SATSolver._find_model
(self)
Main DPLL loop. Returns a generator of models. Variables are chosen successively, and assigned to be either True or False. If a solution is not found with this setting, the opposite is chosen and the search continues. The solver halts when every variable has a setting. Examples ======== >>> from sympy.logic.algorithms.dpll2 import SATSolver >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, ... {3, -2}], {1, 2, 3}, set()) >>> list(l._find_model()) [{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}] >>> from sympy.abc import A, B, C >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, ... {3, -2}], {1, 2, 3}, set(), [A, B, C]) >>> list(l._find_model()) [{A: True, B: False, C: False}, {A: True, B: True, C: True}]
Main DPLL loop. Returns a generator of models.
[ "Main", "DPLL", "loop", ".", "Returns", "a", "generator", "of", "models", "." ]
def _find_model(self): """ Main DPLL loop. Returns a generator of models. Variables are chosen successively, and assigned to be either True or False. If a solution is not found with this setting, the opposite is chosen and the search continues. The solver halts when every variable has a setting. Examples ======== >>> from sympy.logic.algorithms.dpll2 import SATSolver >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, ... {3, -2}], {1, 2, 3}, set()) >>> list(l._find_model()) [{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}] >>> from sympy.abc import A, B, C >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2}, ... {3, -2}], {1, 2, 3}, set(), [A, B, C]) >>> list(l._find_model()) [{A: True, B: False, C: False}, {A: True, B: True, C: True}] """ # We use this variable to keep track of if we should flip a # variable setting in successive rounds flip_var = False # Check if unit prop says the theory is unsat right off the bat self._simplify() if self.is_unsatisfied: return # While the theory still has clauses remaining while True: # Perform cleanup / fixup at regular intervals if self.num_decisions % self.INTERVAL == 0: for func in self.update_functions: func() if flip_var: # We have just backtracked and we are trying to opposite literal flip_var = False lit = self._current_level.decision else: # Pick a literal to set lit = self.heur_calculate() self.num_decisions += 1 # Stopping condition for a satisfying theory if 0 == lit: yield dict((self.symbols[abs(lit) - 1], lit > 0) for lit in self.var_settings) while self._current_level.flipped: self._undo() if len(self.levels) == 1: return flip_lit = -self._current_level.decision self._undo() self.levels.append(Level(flip_lit, flipped=True)) flip_var = True continue # Start the new decision level self.levels.append(Level(lit)) # Assign the literal, updating the clauses it satisfies self._assign_literal(lit) # _simplify the theory self._simplify() # Check if we've made the theory unsat if self.is_unsatisfied: self.is_unsatisfied = False # We unroll all of the decisions until we can flip a literal while self._current_level.flipped: self._undo() # If we've unrolled all the way, the theory is unsat if 1 == len(self.levels): return # Detect and add a learned clause self.add_learned_clause(self.compute_conflict()) # Try the opposite setting of the most recent decision flip_lit = -self._current_level.decision self._undo() self.levels.append(Level(flip_lit, flipped=True)) flip_var = True
[ "def", "_find_model", "(", "self", ")", ":", "# We use this variable to keep track of if we should flip a", "# variable setting in successive rounds", "flip_var", "=", "False", "# Check if unit prop says the theory is unsat right off the bat", "self", ".", "_simplify", "(", ")", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/logic/algorithms/dpll2.py#L165-L260
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/os.py
python
execlp
(file, *args)
execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process.
execlp(file, *args)
[ "execlp", "(", "file", "*", "args", ")" ]
def execlp(file, *args): """execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. """ execvp(file, args)
[ "def", "execlp", "(", "file", ",", "*", "args", ")", ":", "execvp", "(", "file", ",", "args", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/os.py#L546-L551
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/simulation/movie.py
python
Movie._close
(self)
return
Close movie file and adjust atom positions.
Close movie file and adjust atom positions.
[ "Close", "movie", "file", "and", "adjust", "atom", "positions", "." ]
def _close(self): """ Close movie file and adjust atom positions. """ #bruce 050427 comment: what this did in old code: # - if already closed, noop. # - pause (sets internal play-state variables, updates dashboard ###k) # - close file. # - unfreeze atoms. # - if frame moved while movie open this time, self.assy.changed() # - wanted to delete saved frame 0 but doesn't (due to crash during devel) if _DEBUG1: print_compact_stack( "movie._close() called. self.isOpen = %r" % self.isOpen) if not self.isOpen: return self._pause(0) ## self.fileobj.close() # Close the movie file. self.alist_and_moviefile.snuggle_singlets() #bruce 050427 self.alist_and_moviefile.close_file() #bruce 050427 self.isOpen = False #bruce 050425 guess: see if this fixes some bugs if _DEBUG1: print "self.isOpen = False #bruce 050425 guess: see if this fixes some bugs" ###@@@ ## self.movend() # Unfreeze atoms. if self.startFrame != self.currentFrame: self.assy.changed() #bruce 050427 comment: this [i.e. having this condition rather than 'if 1' [060107]] # only helps if nothing else in playing a movie does this... # I'm not sure if that's still true (or if it was in the older code, either). return
[ "def", "_close", "(", "self", ")", ":", "#bruce 050427 comment: what this did in old code:", "# - if already closed, noop.", "# - pause (sets internal play-state variables, updates dashboard ###k)", "# - close file.", "# - unfreeze atoms.", "# - if frame moved while movie open this time, self....
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/simulation/movie.py#L564-L592
OpenKMIP/PyKMIP
c0c980395660ea1b1a8009e97f17ab32d1100233
kmip/pie/client.py
python
ProxyKmipClient._build_common_attributes
(self, operation_policy_name=None)
return common_attributes
Build a list of common attributes that are shared across symmetric as well as asymmetric objects
Build a list of common attributes that are shared across symmetric as well as asymmetric objects
[ "Build", "a", "list", "of", "common", "attributes", "that", "are", "shared", "across", "symmetric", "as", "well", "as", "asymmetric", "objects" ]
def _build_common_attributes(self, operation_policy_name=None): ''' Build a list of common attributes that are shared across symmetric as well as asymmetric objects ''' common_attributes = [] if operation_policy_name: common_attributes.append( self.attribute_factory.create_attribute( enums.AttributeType.OPERATION_POLICY_NAME, operation_policy_name ) ) return common_attributes
[ "def", "_build_common_attributes", "(", "self", ",", "operation_policy_name", "=", "None", ")", ":", "common_attributes", "=", "[", "]", "if", "operation_policy_name", ":", "common_attributes", ".", "append", "(", "self", ".", "attribute_factory", ".", "create_attri...
https://github.com/OpenKMIP/PyKMIP/blob/c0c980395660ea1b1a8009e97f17ab32d1100233/kmip/pie/client.py#L1732-L1747
metabrainz/listenbrainz-server
391a0b91ac3a48398027467651ce3160765c7f37
listenbrainz_spark/utils/__init__.py
python
copy
(hdfs_src_path: str, hdfs_dst_path: str, overwrite: bool = False)
Copy a file or folder in HDFS Args: hdfs_src_path – Source path. hdfs_dst_path – Destination path. If the path already exists and is a directory, the source will be copied into it. overwrite - Wether to overwrite the path if it already exists.
Copy a file or folder in HDFS
[ "Copy", "a", "file", "or", "folder", "in", "HDFS" ]
def copy(hdfs_src_path: str, hdfs_dst_path: str, overwrite: bool = False): """ Copy a file or folder in HDFS Args: hdfs_src_path – Source path. hdfs_dst_path – Destination path. If the path already exists and is a directory, the source will be copied into it. overwrite - Wether to overwrite the path if it already exists. """ walk = hdfs_walk(hdfs_src_path) for (root, dirs, files) in walk: for _file in files: src_file_path = os.path.join(root, _file) dst_file_path = os.path.join(hdfs_dst_path, os.path.relpath(src_file_path, hdfs_src_path)) with hdfs_connection.client.read(src_file_path) as reader: with hdfs_connection.client.write(dst_file_path, overwrite=overwrite) as writer: writer.write(reader.read())
[ "def", "copy", "(", "hdfs_src_path", ":", "str", ",", "hdfs_dst_path", ":", "str", ",", "overwrite", ":", "bool", "=", "False", ")", ":", "walk", "=", "hdfs_walk", "(", "hdfs_src_path", ")", "for", "(", "root", ",", "dirs", ",", "files", ")", "in", "...
https://github.com/metabrainz/listenbrainz-server/blob/391a0b91ac3a48398027467651ce3160765c7f37/listenbrainz_spark/utils/__init__.py#L333-L349
ewels/MultiQC
9b953261d3d684c24eef1827a5ce6718c847a5af
multiqc/modules/picard/BaseDistributionByCycleMetrics.py
python
parse_reports
(self)
return len(self.picard_baseDistributionByCycle_data)
Find Picard BaseDistributionByCycleMetrics reports and parse their data
Find Picard BaseDistributionByCycleMetrics reports and parse their data
[ "Find", "Picard", "BaseDistributionByCycleMetrics", "reports", "and", "parse", "their", "data" ]
def parse_reports(self): """Find Picard BaseDistributionByCycleMetrics reports and parse their data""" # Set up vars self.picard_baseDistributionByCycle_data = dict() self.picard_baseDistributionByCycle_samplestats = dict() # Go through logs and find Metrics base_dist_files = self.find_log_files("picard/basedistributionbycycle", filehandles=True) for f in base_dist_files: try: lines = iter(f["f"]) # read through the header of the file to obtain the # sample name clean_fn = lambda n: self.clean_s_name(n, f) s_name = read_sample_name(lines, clean_fn, "BaseDistributionByCycle") assert s_name is not None # pull out the data data = read_base_distrib_data(lines) assert data is not None # data should be a hierarchical dict # data[read_end][cycle] assert not (set(data) - set([1, 2])) # set up the set of s_names if 2 in set(data): s_names = {1: "%s_R1" % s_name, 2: "%s_R2" % s_name} else: s_names = {1: s_name} previously_used = set(s_names.values()) & set(self.picard_baseDistributionByCycle_data) if previously_used: for duped_name in previously_used: log.debug("Duplicate sample name found in {}! " "Overwriting: {}".format(f["fn"], duped_name)) for name in s_names.values(): self.add_data_source(f, name, section="BaseDistributionByCycle") for read_end in s_names: data_by_cycle = data[read_end] s_name = s_names[read_end] self.picard_baseDistributionByCycle_data[s_name] = data_by_cycle samplestats = { "sum_pct_a": 0, "sum_pct_c": 0, "sum_pct_g": 0, "sum_pct_t": 0, "sum_pct_n": 0, "cycle_count": 0, } self.picard_baseDistributionByCycle_samplestats[s_name] = samplestats for c, row in data_by_cycle.items(): pct_a, pct_c, pct_g, pct_t, pct_n = row samplestats["sum_pct_a"] += pct_a samplestats["sum_pct_c"] += pct_c samplestats["sum_pct_g"] += pct_g samplestats["sum_pct_t"] += pct_t samplestats["sum_pct_n"] += pct_n samplestats["cycle_count"] += len(data_by_cycle.keys()) except AssertionError: pass # Calculate summed mean values for all read orientations for s_name, v in self.picard_baseDistributionByCycle_samplestats.items(): v["mean_pct_a"] = v["sum_pct_a"] / v["cycle_count"] v["mean_pct_c"] = v["sum_pct_c"] / v["cycle_count"] v["mean_pct_g"] = v["sum_pct_g"] / v["cycle_count"] v["mean_pct_t"] = v["sum_pct_t"] / v["cycle_count"] # Filter to strip out ignored sample names self.picard_baseDistributionByCycle_data = self.ignore_samples(self.picard_baseDistributionByCycle_data) if len(self.picard_baseDistributionByCycle_data) > 0: # Write parsed data to a file self.write_data_file(self.picard_baseDistributionByCycle_samplestats, "multiqc_picard_baseContent") # Plot the data and add section pconfig = { "id": "picard_base_distribution_by_cycle", "title": "Picard: Base Distribution", "ylab": "%", "xlab": "Cycle #", "xDecimals": False, "tt_label": "<b>cycle {point.x}</b>: {point.y:.2f} %", "ymax": 100, "ymin": 0, "data_labels": [ {"name": "% Adenine", "ylab": "% Adenine"}, {"name": "% Cytosine", "ylab": "% Cytosine"}, {"name": "% Guanine", "ylab": "% Guanine"}, {"name": "% Thymine", "ylab": "% Thymine"}, {"name": "% Undetermined", "ylab": "% Undetermined"}, ], } # build list of linegraphs linegraph_data = [{}, {}, {}, {}, {}] for s_name, cycles in self.picard_baseDistributionByCycle_data.items(): reformat_items = lambda n: {cycle: tup[n] for cycle, tup in cycles.items()} for lg, index in zip(linegraph_data, range(5)): lg[s_name] = reformat_items(index) self.add_section( name="Base Distribution", anchor="picard-base-distribution-by-cycle", description="Plot shows the distribution of bases by cycle.", plot=linegraph.plot(linegraph_data, pconfig), ) # Return the number of detected samples to the parent module return len(self.picard_baseDistributionByCycle_data)
[ "def", "parse_reports", "(", "self", ")", ":", "# Set up vars", "self", ".", "picard_baseDistributionByCycle_data", "=", "dict", "(", ")", "self", ".", "picard_baseDistributionByCycle_samplestats", "=", "dict", "(", ")", "# Go through logs and find Metrics", "base_dist_fi...
https://github.com/ewels/MultiQC/blob/9b953261d3d684c24eef1827a5ce6718c847a5af/multiqc/modules/picard/BaseDistributionByCycleMetrics.py#L61-L176
stanislav-web/OpenDoor
fbdffd12b25c574785e9b8a7c6362037bf93cf98
src/core/helper/helper.py
python
Helper.filter_directory_string
(str)
return str.strip()
Filter directory string :param str string: input string :return: str
Filter directory string
[ "Filter", "directory", "string" ]
def filter_directory_string(str): """ Filter directory string :param str string: input string :return: str """ str = str.strip("\n") if True is str.startswith('/'): str = str[1:] return str.strip()
[ "def", "filter_directory_string", "(", "str", ")", ":", "str", "=", "str", ".", "strip", "(", "\"\\n\"", ")", "if", "True", "is", "str", ".", "startswith", "(", "'/'", ")", ":", "str", "=", "str", "[", "1", ":", "]", "return", "str", ".", "strip", ...
https://github.com/stanislav-web/OpenDoor/blob/fbdffd12b25c574785e9b8a7c6362037bf93cf98/src/core/helper/helper.py#L180-L192
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Mac/Demo/applescript/Disk_Copy/Utility_Events.py
python
Utility_Events_Events.log
(self, _object, _attributes={}, **_arguments)
log: Add a string to the log window Required argument: the string to add to the log window Keyword argument time_stamp: Should the log entry be time-stamped? (false if not supplied) Keyword argument _attributes: AppleEvent attribute dictionary
log: Add a string to the log window Required argument: the string to add to the log window Keyword argument time_stamp: Should the log entry be time-stamped? (false if not supplied) Keyword argument _attributes: AppleEvent attribute dictionary
[ "log", ":", "Add", "a", "string", "to", "the", "log", "window", "Required", "argument", ":", "the", "string", "to", "add", "to", "the", "log", "window", "Keyword", "argument", "time_stamp", ":", "Should", "the", "log", "entry", "be", "time", "-", "stampe...
def log(self, _object, _attributes={}, **_arguments): """log: Add a string to the log window Required argument: the string to add to the log window Keyword argument time_stamp: Should the log entry be time-stamped? (false if not supplied) Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'UTIL' _subcode = 'LOG ' aetools.keysubst(_arguments, self._argmap_log) _arguments['----'] = _object aetools.enumsubst(_arguments, 'TSMP', _Enum_bool) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "log", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'UTIL'", "_subcode", "=", "'LOG '", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_log", ")",...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Mac/Demo/applescript/Disk_Copy/Utility_Events.py#L175-L195
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site-packages/pip/_vendor/requests/api.py
python
put
(url, data=None, **kwargs)
return request('put', url, data=data, **kwargs)
r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends a PUT request.
[ "r", "Sends", "a", "PUT", "request", "." ]
def put(url, data=None, **kwargs): r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('put', url, data=data, **kwargs)
[ "def", "put", "(", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'put'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/pip/_vendor/requests/api.py#L119-L131
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pylibs/win32/gevent/greenlet.py
python
Greenlet.join
(self, timeout=None)
Wait until the greenlet finishes or *timeout* expires. Return ``None`` regardless.
Wait until the greenlet finishes or *timeout* expires. Return ``None`` regardless.
[ "Wait", "until", "the", "greenlet", "finishes", "or", "*", "timeout", "*", "expires", ".", "Return", "None", "regardless", "." ]
def join(self, timeout=None): """Wait until the greenlet finishes or *timeout* expires. Return ``None`` regardless. """ if self.ready(): return switch = getcurrent().switch self.rawlink(switch) try: t = Timeout._start_new_or_dummy(timeout) try: result = self.parent.switch() if result is not self: raise InvalidSwitchError('Invalid switch into Greenlet.join(): %r' % (result, )) finally: t.cancel() except Timeout as ex: self.unlink(switch) if ex is not t: raise except: self.unlink(switch) raise
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "ready", "(", ")", ":", "return", "switch", "=", "getcurrent", "(", ")", ".", "switch", "self", ".", "rawlink", "(", "switch", ")", "try", ":", "t", "=", "Timeo...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pylibs/win32/gevent/greenlet.py#L482-L505
jacoxu/encoder_decoder
6829c3bc42105aedfd1b8a81c81be19df4326c0a
keras/backend/tensorflow_backend.py
python
prod
(x, axis=None, keepdims=False)
return tf.reduce_prod(x, reduction_indices=axis, keep_dims=keepdims)
Multiply the values in a tensor, alongside the specified axis.
Multiply the values in a tensor, alongside the specified axis.
[ "Multiply", "the", "values", "in", "a", "tensor", "alongside", "the", "specified", "axis", "." ]
def prod(x, axis=None, keepdims=False): '''Multiply the values in a tensor, alongside the specified axis. ''' axis = normalize_axis(axis, ndim(x)) return tf.reduce_prod(x, reduction_indices=axis, keep_dims=keepdims)
[ "def", "prod", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "axis", "=", "normalize_axis", "(", "axis", ",", "ndim", "(", "x", ")", ")", "return", "tf", ".", "reduce_prod", "(", "x", ",", "reduction_indices", "=", "a...
https://github.com/jacoxu/encoder_decoder/blob/6829c3bc42105aedfd1b8a81c81be19df4326c0a/keras/backend/tensorflow_backend.py#L154-L158
vinta/haul
234024ab8452ea2f41b18561377295cf2879fb20
haul/finders/pipeline/css.py
python
background_image_finder
(pipeline_index, soup, finder_image_urls=[], *args, **kwargs)
return output
Find image URL in background-image Example: <div style="width: 100%; height: 100%; background-image: url(http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg);" class="Image iLoaded iWithTransition Frame" src="http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg"></div> to http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg
Find image URL in background-image
[ "Find", "image", "URL", "in", "background", "-", "image" ]
def background_image_finder(pipeline_index, soup, finder_image_urls=[], *args, **kwargs): """ Find image URL in background-image Example: <div style="width: 100%; height: 100%; background-image: url(http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg);" class="Image iLoaded iWithTransition Frame" src="http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg"></div> to http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg """ now_finder_image_urls = [] for tag in soup.find_all(style=True): style_string = tag['style'] if 'background-image' in style_string.lower(): style = cssutils.parseStyle(style_string) background_image = style.getProperty('background-image') if background_image: for property_value in background_image.propertyValue: background_image_url = str(property_value.value) if background_image_url: if (background_image_url not in finder_image_urls) and \ (background_image_url not in now_finder_image_urls): now_finder_image_urls.append(background_image_url) output = {} output['finder_image_urls'] = finder_image_urls + now_finder_image_urls return output
[ "def", "background_image_finder", "(", "pipeline_index", ",", "soup", ",", "finder_image_urls", "=", "[", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "now_finder_image_urls", "=", "[", "]", "for", "tag", "in", "soup", ".", "find_all", "(", ...
https://github.com/vinta/haul/blob/234024ab8452ea2f41b18561377295cf2879fb20/haul/finders/pipeline/css.py#L6-L37
sfepy/sfepy
02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25
sfepy/discrete/common/mappings.py
python
get_mapping_data
(name, field, integral, region=None, integration='volume')
return data
General helper function for accessing reference mapping data. Get data attribute `name` from reference mapping corresponding to `field` in `region` in quadrature points of the given `integral` and `integration` type. Parameters ---------- name : str The reference mapping attribute name. field : Field instance The field defining the reference mapping. integral : Integral instance The integral defining quadrature points. region : Region instance, optional If given, use the given region instead of `field` region. integration : one of ('volume', 'surface', 'surface_extra') The integration type. Returns ------- data : array The required data merged for all element groups. Notes ----- Assumes the same element geometry in all element groups of the field!
General helper function for accessing reference mapping data.
[ "General", "helper", "function", "for", "accessing", "reference", "mapping", "data", "." ]
def get_mapping_data(name, field, integral, region=None, integration='volume'): """ General helper function for accessing reference mapping data. Get data attribute `name` from reference mapping corresponding to `field` in `region` in quadrature points of the given `integral` and `integration` type. Parameters ---------- name : str The reference mapping attribute name. field : Field instance The field defining the reference mapping. integral : Integral instance The integral defining quadrature points. region : Region instance, optional If given, use the given region instead of `field` region. integration : one of ('volume', 'surface', 'surface_extra') The integration type. Returns ------- data : array The required data merged for all element groups. Notes ----- Assumes the same element geometry in all element groups of the field! """ data = None if region is None: region = field.region geo, _ = field.get_mapping(region, integral, integration) data = getattr(geo, name) return data
[ "def", "get_mapping_data", "(", "name", ",", "field", ",", "integral", ",", "region", "=", "None", ",", "integration", "=", "'volume'", ")", ":", "data", "=", "None", "if", "region", "is", "None", ":", "region", "=", "field", ".", "region", "geo", ",",...
https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/discrete/common/mappings.py#L124-L161
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/functions/combinatorial/factorials.py
python
binomial._eval_expand_func
(self, **hints)
Function to expand binomial(n,k) when m is positive integer Also, n is self.args[0] and k is self.args[1] while using binomial(n, k)
Function to expand binomial(n,k) when m is positive integer Also, n is self.args[0] and k is self.args[1] while using binomial(n, k)
[ "Function", "to", "expand", "binomial", "(", "n", "k", ")", "when", "m", "is", "positive", "integer", "Also", "n", "is", "self", ".", "args", "[", "0", "]", "and", "k", "is", "self", ".", "args", "[", "1", "]", "while", "using", "binomial", "(", ...
def _eval_expand_func(self, **hints): """ Function to expand binomial(n,k) when m is positive integer Also, n is self.args[0] and k is self.args[1] while using binomial(n, k) """ n = self.args[0] if n.is_Number: return binomial(*self.args) k = self.args[1] if k.is_Add and n in k.args: k = n - k if k.is_Integer: if k == S.Zero: return S.One elif k < 0: return S.Zero else: n = self.args[0] result = n - k + 1 for i in xrange(2, k + 1): result *= n - k + i result /= i return result else: return binomial(*self.args)
[ "def", "_eval_expand_func", "(", "self", ",", "*", "*", "hints", ")", ":", "n", "=", "self", ".", "args", "[", "0", "]", "if", "n", ".", "is_Number", ":", "return", "binomial", "(", "*", "self", ".", "args", ")", "k", "=", "self", ".", "args", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/combinatorial/factorials.py#L545-L572
microsoft/msticpy
2a401444ee529114004f496f4c0376ff25b5268a
msticpy/nbtools/nbinit.py
python
_err_output
(*args)
Output to IPython display or print - always output regardless of verbosity.
Output to IPython display or print - always output regardless of verbosity.
[ "Output", "to", "IPython", "display", "or", "print", "-", "always", "output", "regardless", "of", "verbosity", "." ]
def _err_output(*args): """Output to IPython display or print - always output regardless of verbosity.""" if is_ipython(): display(HTML(" ".join([*args, "<br>"]).replace("\n", "<br>"))) else: print(*args)
[ "def", "_err_output", "(", "*", "args", ")", ":", "if", "is_ipython", "(", ")", ":", "display", "(", "HTML", "(", "\" \"", ".", "join", "(", "[", "*", "args", ",", "\"<br>\"", "]", ")", ".", "replace", "(", "\"\\n\"", ",", "\"<br>\"", ")", ")", "...
https://github.com/microsoft/msticpy/blob/2a401444ee529114004f496f4c0376ff25b5268a/msticpy/nbtools/nbinit.py#L195-L200
facebookresearch/fastMRI
13560d2f198cc72f06e01675e9ecee509ce5639a
fastmri/evaluate.py
python
nmse
(gt: np.ndarray, pred: np.ndarray)
return np.linalg.norm(gt - pred) ** 2 / np.linalg.norm(gt) ** 2
Compute Normalized Mean Squared Error (NMSE)
Compute Normalized Mean Squared Error (NMSE)
[ "Compute", "Normalized", "Mean", "Squared", "Error", "(", "NMSE", ")" ]
def nmse(gt: np.ndarray, pred: np.ndarray) -> np.ndarray: """Compute Normalized Mean Squared Error (NMSE)""" return np.linalg.norm(gt - pred) ** 2 / np.linalg.norm(gt) ** 2
[ "def", "nmse", "(", "gt", ":", "np", ".", "ndarray", ",", "pred", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "return", "np", ".", "linalg", ".", "norm", "(", "gt", "-", "pred", ")", "**", "2", "/", "np", ".", "linalg", "...
https://github.com/facebookresearch/fastMRI/blob/13560d2f198cc72f06e01675e9ecee509ce5639a/fastmri/evaluate.py#L26-L28
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/distutils/cygwinccompiler.py
python
CygwinCCompiler._compile
(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
Compiles the source by spawning GCC and windres if needed.
Compiles the source by spawning GCC and windres if needed.
[ "Compiles", "the", "source", "by", "spawning", "GCC", "and", "windres", "if", "needed", "." ]
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compiles the source by spawning GCC and windres if needed.""" if ext == '.rc' or ext == '.res': # gcc needs '.res' and '.rc' compiled to object files !!! try: self.spawn(["windres", "-i", src, "-o", obj]) except DistutilsExecError as msg: raise CompileError(msg) else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) except DistutilsExecError as msg: raise CompileError(msg)
[ "def", "_compile", "(", "self", ",", "obj", ",", "src", ",", "ext", ",", "cc_args", ",", "extra_postargs", ",", "pp_opts", ")", ":", "if", "ext", "==", "'.rc'", "or", "ext", "==", "'.res'", ":", "# gcc needs '.res' and '.rc' compiled to object files !!!", "try...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/distutils/cygwinccompiler.py#L159-L172
quantumlib/OpenFermion
6187085f2a7707012b68370b625acaeed547e62b
dev_tools/incremental_coverage.py
python
determine_ignored_lines
(content: str)
return {e + 1 for e in result}
[]
def determine_ignored_lines(content: str) -> Set[int]: lines = content.split('\n') result = [] # type: List[int] i = 0 while i < len(lines): # Drop spacing, including internal spacing within the comment. joined_line = re.sub(r'\s+', '', lines[i]) if joined_line == EXPLICIT_OPT_OUT_COMMENT: # Ignore the rest of a block. end = naive_find_end_of_scope(lines, i) result.extend(range(i, end)) i = end elif joined_line.endswith(EXPLICIT_OPT_OUT_COMMENT): # Ignore a single line. result.append(i) i += 1 else: # Don't ignore. i += 1 # Line numbers start at 1, not 0. return {e + 1 for e in result}
[ "def", "determine_ignored_lines", "(", "content", ":", "str", ")", "->", "Set", "[", "int", "]", ":", "lines", "=", "content", ".", "split", "(", "'\\n'", ")", "result", "=", "[", "]", "# type: List[int]", "i", "=", "0", "while", "i", "<", "len", "("...
https://github.com/quantumlib/OpenFermion/blob/6187085f2a7707012b68370b625acaeed547e62b/dev_tools/incremental_coverage.py#L185-L208
mkeeter/kokopelli
c99b7909e138c42c7d5c99927f5031f021bffd77
koko/cam/panel.py
python
OutputPanel.construct
(self, title=None, parameters=[], start=False)
Constructs UI elements for an OutputPanel @param title Panel title @param parameters List of (label, name, type, checker) tuples @param start Boolean indicating if the panel should show a Start button
Constructs UI elements for an OutputPanel
[ "Constructs", "UI", "elements", "for", "an", "OutputPanel" ]
def construct(self, title=None, parameters=[], start=False): """ Constructs UI elements for an OutputPanel @param title Panel title @param parameters List of (label, name, type, checker) tuples @param start Boolean indicating if the panel should show a Start button """ if title is not None: FabPanel.construct(self, title, parameters) hs = wx.BoxSizer(wx.HORIZONTAL) ## @var gen_button # wx.Button to generate toolpath self.gen_button = wx.Button(self, id=wx.ID_ANY, label='Generate') self.gen_button.Bind(wx.EVT_BUTTON, self.parent.start) ## @var save_button # wx.Button to save toolpath self.save_button = wx.Button(self, id=wx.ID_ANY, label='Save') self.save_button.Enable(False) self.save_button.Bind(wx.EVT_BUTTON, self.save) hs.Add(self.gen_button, flag=wx.ALL, border=5) hs.Add(self.save_button, flag=wx.ALL, border=5) ## @var start_button # wx.Button to start machine running (optional) if start: self.start_button = wx.Button(self, id=wx.ID_ANY, label='Start') self.start_button.Enable(False) self.start_button.Bind(wx.EVT_BUTTON, self.start) hs.Add(self.start_button, flag=wx.ALL, border=5) else: self.start_button = None sizer = self.GetSizer() sizer.Add(hs, flag=wx.TOP|wx.CENTER, border=5) self.SetSizerAndFit(sizer)
[ "def", "construct", "(", "self", ",", "title", "=", "None", ",", "parameters", "=", "[", "]", ",", "start", "=", "False", ")", ":", "if", "title", "is", "not", "None", ":", "FabPanel", ".", "construct", "(", "self", ",", "title", ",", "parameters", ...
https://github.com/mkeeter/kokopelli/blob/c99b7909e138c42c7d5c99927f5031f021bffd77/koko/cam/panel.py#L197-L234
toandaominh1997/EfficientDet.Pytorch
fbe56e58c9a2749520303d2d380427e5f01305ba
models/efficientdet.py
python
EfficientDet.freeze_bn
(self)
Freeze BatchNorm layers.
Freeze BatchNorm layers.
[ "Freeze", "BatchNorm", "layers", "." ]
def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
[ "def", "freeze_bn", "(", "self", ")", ":", "for", "layer", "in", "self", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "layer", ",", "nn", ".", "BatchNorm2d", ")", ":", "layer", ".", "eval", "(", ")" ]
https://github.com/toandaominh1997/EfficientDet.Pytorch/blob/fbe56e58c9a2749520303d2d380427e5f01305ba/models/efficientdet.py#L88-L92
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/gtfs/sensor.py
python
GTFSDepartureSensor.icon
(self)
return self._icon
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
[ "Icon", "to", "use", "in", "the", "frontend", "if", "any", "." ]
def icon(self) -> str: """Icon to use in the frontend, if any.""" return self._icon
[ "def", "icon", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_icon" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/gtfs/sensor.py#L575-L577
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/webob/acceptparse.py
python
Accept.parse
(value)
Parse ``Accept-*`` style header. Return iterator of ``(value, quality)`` pairs. ``quality`` defaults to 1.
Parse ``Accept-*`` style header.
[ "Parse", "Accept", "-", "*", "style", "header", "." ]
def parse(value): """ Parse ``Accept-*`` style header. Return iterator of ``(value, quality)`` pairs. ``quality`` defaults to 1. """ for match in part_re.finditer(','+value): name = match.group(1) if name == 'q': continue quality = match.group(2) or '' if quality: try: quality = max(min(float(quality), 1), 0) yield (name, quality) continue except ValueError: pass yield (name, 1)
[ "def", "parse", "(", "value", ")", ":", "for", "match", "in", "part_re", ".", "finditer", "(", "','", "+", "value", ")", ":", "name", "=", "match", ".", "group", "(", "1", ")", "if", "name", "==", "'q'", ":", "continue", "quality", "=", "match", ...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/webob/acceptparse.py#L44-L63
devAmoghS/Machine-Learning-with-Python
4bd52836f48e1e52b878d64a39e89c31dc47bfb1
helpers/gradient_descent.py
python
negate
(f)
return lambda *args, **kwargs: -f(*args, **kwargs)
return a function that for any input x returns -f(x)
return a function that for any input x returns -f(x)
[ "return", "a", "function", "that", "for", "any", "input", "x", "returns", "-", "f", "(", "x", ")" ]
def negate(f): """return a function that for any input x returns -f(x)""" return lambda *args, **kwargs: -f(*args, **kwargs)
[ "def", "negate", "(", "f", ")", ":", "return", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "-", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/devAmoghS/Machine-Learning-with-Python/blob/4bd52836f48e1e52b878d64a39e89c31dc47bfb1/helpers/gradient_descent.py#L99-L101
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/lockfile/pidlockfile.py
python
PIDLockFile.release
(self)
Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock.
Release the lock.
[ "Release", "the", "lock", "." ]
def release(self): """ Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock. """ if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) if not self.i_am_locking(): raise NotMyLock("%s is locked, but not by me" % self.path) remove_existing_pidfile(self.path)
[ "def", "release", "(", "self", ")", ":", "if", "not", "self", ".", "is_locked", "(", ")", ":", "raise", "NotLocked", "(", "\"%s is not locked\"", "%", "self", ".", "path", ")", "if", "not", "self", ".", "i_am_locking", "(", ")", ":", "raise", "NotMyLoc...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/lockfile/pidlockfile.py#L95-L106
plasticityai/magnitude
7ac0baeaf181263b661c3ae00643d21e3fd90216
pymagnitude/third_party/allennlp/nn/util.py
python
batched_index_select
(target , indices , flattened_indices = None)
return selected_targets
u""" The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length, embedding_size)``. This function returns selected values in the target with respect to the provided indices, which have size ``(batch_size, d_1, ..., d_n, embedding_size)``. This can use the optionally precomputed :func:`~flattened_indices` with size ``(batch_size * d_1 * ... * d_n)`` if given. An example use case of this function is looking up the start and end indices of spans in a sequence tensor. This is used in the :class:`~allennlp.models.coreference_resolution.CoreferenceResolver`. Model to select contextual word representations corresponding to the start and end indices of mentions. The key reason this can't be done with basic torch functions is that we want to be able to use look-up tensors with an arbitrary number of dimensions (for example, in the coref model, we don't know a-priori how many spans we are looking up). Parameters ---------- target : ``torch.Tensor``, required. A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size). This is the tensor to be indexed. indices : ``torch.LongTensor`` A tensor of shape (batch_size, ...), where each element is an index into the ``sequence_length`` dimension of the ``target`` tensor. flattened_indices : Optional[torch.Tensor], optional (default = None) An optional tensor representing the result of calling :func:~`flatten_and_batch_shift_indices` on ``indices``. This is helpful in the case that the indices can be flattened once and cached for many batch lookups. Returns ------- selected_targets : ``torch.Tensor`` A tensor with shape [indices.size(), target.size(-1)] representing the embedded indices extracted from the batch flattened target tensor.
u""" The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length, embedding_size)``.
[ "u", "The", "given", "indices", "of", "size", "(", "batch_size", "d_1", "...", "d_n", ")", "indexes", "into", "the", "sequence", "dimension", "(", "dimension", "2", ")", "of", "the", "target", "which", "has", "size", "(", "batch_size", "sequence_length", "...
def batched_index_select(target , indices , flattened_indices = None) : u""" The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length, embedding_size)``. This function returns selected values in the target with respect to the provided indices, which have size ``(batch_size, d_1, ..., d_n, embedding_size)``. This can use the optionally precomputed :func:`~flattened_indices` with size ``(batch_size * d_1 * ... * d_n)`` if given. An example use case of this function is looking up the start and end indices of spans in a sequence tensor. This is used in the :class:`~allennlp.models.coreference_resolution.CoreferenceResolver`. Model to select contextual word representations corresponding to the start and end indices of mentions. The key reason this can't be done with basic torch functions is that we want to be able to use look-up tensors with an arbitrary number of dimensions (for example, in the coref model, we don't know a-priori how many spans we are looking up). Parameters ---------- target : ``torch.Tensor``, required. A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size). This is the tensor to be indexed. indices : ``torch.LongTensor`` A tensor of shape (batch_size, ...), where each element is an index into the ``sequence_length`` dimension of the ``target`` tensor. flattened_indices : Optional[torch.Tensor], optional (default = None) An optional tensor representing the result of calling :func:~`flatten_and_batch_shift_indices` on ``indices``. This is helpful in the case that the indices can be flattened once and cached for many batch lookups. Returns ------- selected_targets : ``torch.Tensor`` A tensor with shape [indices.size(), target.size(-1)] representing the embedded indices extracted from the batch flattened target tensor. """ if flattened_indices is None: # Shape: (batch_size * d_1 * ... * d_n) flattened_indices = flatten_and_batch_shift_indices(indices, target.size(1)) # Shape: (batch_size * sequence_length, embedding_size) flattened_target = target.view(-1, target.size(-1)) # Shape: (batch_size * d_1 * ... * d_n, embedding_size) flattened_selected = flattened_target.index_select(0, flattened_indices) selected_shape = list(indices.size()) + [target.size(-1)] # Shape: (batch_size, d_1, ..., d_n, embedding_size) selected_targets = flattened_selected.view(*selected_shape) return selected_targets
[ "def", "batched_index_select", "(", "target", ",", "indices", ",", "flattened_indices", "=", "None", ")", ":", "if", "flattened_indices", "is", "None", ":", "# Shape: (batch_size * d_1 * ... * d_n)", "flattened_indices", "=", "flatten_and_batch_shift_indices", "(", "indic...
https://github.com/plasticityai/magnitude/blob/7ac0baeaf181263b661c3ae00643d21e3fd90216/pymagnitude/third_party/allennlp/nn/util.py#L777-L828
prompt-toolkit/python-prompt-toolkit
e9eac2eb59ec385e81742fa2ac623d4b8de00925
prompt_toolkit/key_binding/bindings/named_commands.py
python
uppercase_word
(event: E)
Uppercase the current (or following) word.
Uppercase the current (or following) word.
[ "Uppercase", "the", "current", "(", "or", "following", ")", "word", "." ]
def uppercase_word(event: E) -> None: """ Uppercase the current (or following) word. """ buff = event.current_buffer for i in range(event.arg): pos = buff.document.find_next_word_ending() words = buff.document.text_after_cursor[:pos] buff.insert_text(words.upper(), overwrite=True)
[ "def", "uppercase_word", "(", "event", ":", "E", ")", "->", "None", ":", "buff", "=", "event", ".", "current_buffer", "for", "i", "in", "range", "(", "event", ".", "arg", ")", ":", "pos", "=", "buff", ".", "document", ".", "find_next_word_ending", "(",...
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/e9eac2eb59ec385e81742fa2ac623d4b8de00925/prompt_toolkit/key_binding/bindings/named_commands.py#L293-L302
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/elasticache/layer1.py
python
ElastiCacheConnection.delete_cache_security_group
(self, cache_security_group_name)
return self._make_request( action='DeleteCacheSecurityGroup', verb='POST', path='/', params=params)
The DeleteCacheSecurityGroup operation deletes a cache security group. You cannot delete a cache security group if it is associated with any cache clusters. :type cache_security_group_name: string :param cache_security_group_name: The name of the cache security group to delete. You cannot delete the default security group.
The DeleteCacheSecurityGroup operation deletes a cache security group. You cannot delete a cache security group if it is associated with any cache clusters.
[ "The", "DeleteCacheSecurityGroup", "operation", "deletes", "a", "cache", "security", "group", ".", "You", "cannot", "delete", "a", "cache", "security", "group", "if", "it", "is", "associated", "with", "any", "cache", "clusters", "." ]
def delete_cache_security_group(self, cache_security_group_name): """ The DeleteCacheSecurityGroup operation deletes a cache security group. You cannot delete a cache security group if it is associated with any cache clusters. :type cache_security_group_name: string :param cache_security_group_name: The name of the cache security group to delete. You cannot delete the default security group. """ params = { 'CacheSecurityGroupName': cache_security_group_name, } return self._make_request( action='DeleteCacheSecurityGroup', verb='POST', path='/', params=params)
[ "def", "delete_cache_security_group", "(", "self", ",", "cache_security_group_name", ")", ":", "params", "=", "{", "'CacheSecurityGroupName'", ":", "cache_security_group_name", ",", "}", "return", "self", ".", "_make_request", "(", "action", "=", "'DeleteCacheSecurityGr...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/elasticache/layer1.py#L483-L503
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_config_map_key_selector.py
python
V1ConfigMapKeySelector.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """For `print` and `pprint`""" return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_config_map_key_selector.py#L163-L165
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/cmd.py
python
Cmd.postcmd
(self, stop, line)
return stop
Hook method executed just after a command dispatch is finished.
Hook method executed just after a command dispatch is finished.
[ "Hook", "method", "executed", "just", "after", "a", "command", "dispatch", "is", "finished", "." ]
def postcmd(self, stop, line): """Hook method executed just after a command dispatch is finished.""" return stop
[ "def", "postcmd", "(", "self", ",", "stop", ",", "line", ")", ":", "return", "stop" ]
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/cmd.py#L167-L169
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/simple/_simpletable.py
python
SimpleTable.row_sort_val
(self, col, val)
Add a row of data to sort by.
Add a row of data to sort by.
[ "Add", "a", "row", "of", "data", "to", "sort", "by", "." ]
def row_sort_val(self, col, val): """ Add a row of data to sort by. """ self._sort_vals[col].append(val)
[ "def", "row_sort_val", "(", "self", ",", "col", ",", "val", ")", ":", "self", ".", "_sort_vals", "[", "col", "]", ".", "append", "(", "val", ")" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/simple/_simpletable.py#L75-L79
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/words/protocols/jabber/xmlstream.py
python
XmlStream.reset
(self)
Reset XML Stream. Resets the XML Parser for incoming data. This is to be used after successfully negotiating a new layer, e.g. TLS and SASL. Note that registered event observers will continue to be in place.
Reset XML Stream.
[ "Reset", "XML", "Stream", "." ]
def reset(self): """ Reset XML Stream. Resets the XML Parser for incoming data. This is to be used after successfully negotiating a new layer, e.g. TLS and SASL. Note that registered event observers will continue to be in place. """ self._headerSent = False self._initializeStream()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_headerSent", "=", "False", "self", ".", "_initializeStream", "(", ")" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/words/protocols/jabber/xmlstream.py#L526-L535
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
safe_version
(version)
Convert an arbitrary string to a standard version string
Convert an arbitrary string to a standard version string
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "version", "string" ]
def safe_version(version): """ Convert an arbitrary string to a standard version string """ try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
[ "def", "safe_version", "(", "version", ")", ":", "try", ":", "# normalize the version", "return", "str", "(", "packaging", ".", "version", ".", "Version", "(", "version", ")", ")", "except", "packaging", ".", "version", ".", "InvalidVersion", ":", "version", ...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1381-L1390
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
PyApp.SetMacAboutMenuItemId
(*args, **kwargs)
return _core.PyApp_SetMacAboutMenuItemId(*args, **kwargs)
SetMacAboutMenuItemId(long val)
SetMacAboutMenuItemId(long val)
[ "SetMacAboutMenuItemId", "(", "long", "val", ")" ]
def SetMacAboutMenuItemId(*args, **kwargs): """SetMacAboutMenuItemId(long val)""" return _core.PyApp_SetMacAboutMenuItemId(*args, **kwargs)
[ "def", "SetMacAboutMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core", ".", "PyApp_SetMacAboutMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L4765-L4767
nephila/djangocms-blog
d18382808766548c0ec1b9f0dabe443d5430aebf
djangocms_blog/cms_menus.py
python
BlogNavModifier.modify
(self, request, nodes, namespace, root_id, post_cut, breadcrumb)
return nodes
Actual modifier function :param request: request :param nodes: complete list of nodes :param namespace: Menu namespace :param root_id: eventual root_id :param post_cut: flag for modifier stage :param breadcrumb: flag for modifier stage :return: nodeslist
Actual modifier function :param request: request :param nodes: complete list of nodes :param namespace: Menu namespace :param root_id: eventual root_id :param post_cut: flag for modifier stage :param breadcrumb: flag for modifier stage :return: nodeslist
[ "Actual", "modifier", "function", ":", "param", "request", ":", "request", ":", "param", "nodes", ":", "complete", "list", "of", "nodes", ":", "param", "namespace", ":", "Menu", "namespace", ":", "param", "root_id", ":", "eventual", "root_id", ":", "param", ...
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): """ Actual modifier function :param request: request :param nodes: complete list of nodes :param namespace: Menu namespace :param root_id: eventual root_id :param post_cut: flag for modifier stage :param breadcrumb: flag for modifier stage :return: nodeslist """ app = None config = None if getattr(request, "current_page", None) and request.current_page.application_urls: app = apphook_pool.get_apphook(request.current_page.application_urls) if app and app.app_config: namespace = resolve(request.path).namespace if not self._config.get(namespace, False): self._config[namespace] = app.get_config(namespace) config = self._config[namespace] try: if config and (not isinstance(config, BlogConfig) or config.menu_structure != MENU_TYPE_CATEGORIES): return nodes except AttributeError: # pragma: no cover # in case `menu_structure` is not present in config return nodes if post_cut: return nodes current_post = getattr(request, get_setting("CURRENT_POST_IDENTIFIER"), None) category = None if current_post and current_post.__class__ == Post: category = current_post.categories.first() if not category: return nodes for node in nodes: if "{}-{}".format(category.__class__.__name__, category.pk) == node.id: node.selected = True return nodes
[ "def", "modify", "(", "self", ",", "request", ",", "nodes", ",", "namespace", ",", "root_id", ",", "post_cut", ",", "breadcrumb", ")", ":", "app", "=", "None", "config", "=", "None", "if", "getattr", "(", "request", ",", "\"current_page\"", ",", "None", ...
https://github.com/nephila/djangocms-blog/blob/d18382808766548c0ec1b9f0dabe443d5430aebf/djangocms_blog/cms_menus.py#L134-L173
galaxyproject/galaxy
4c03520f05062e0f4a1b3655dc0b7452fda69943
lib/galaxy/webapps/galaxy/api/annotations.py
python
BaseAnnotationsController._get_item_from_id
(self, trans: ProvidesHistoryContext, idstr)
Return item with annotation association.
Return item with annotation association.
[ "Return", "item", "with", "annotation", "association", "." ]
def _get_item_from_id(self, trans: ProvidesHistoryContext, idstr): """Return item with annotation association."""
[ "def", "_get_item_from_id", "(", "self", ",", "trans", ":", "ProvidesHistoryContext", ",", "idstr", ")", ":" ]
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/galaxy/webapps/galaxy/api/annotations.py#L61-L62
googleads/googleads-python-lib
b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee
examples/ad_manager/v202108/order_service/get_all_orders.py
python
main
(client)
[]
def main(client): # Initialize appropriate service. order_service = client.GetService('OrderService', version='v202108') # Create a statement to select orders. statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) if 'results' in response and len(response['results']): for order in response['results']: # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], order['name'])) statement.offset += statement.limit else: break print('\nNumber of results found: %s' % response['totalResultSetSize'])
[ "def", "main", "(", "client", ")", ":", "# Initialize appropriate service.", "order_service", "=", "client", ".", "GetService", "(", "'OrderService'", ",", "version", "=", "'v202108'", ")", "# Create a statement to select orders.", "statement", "=", "ad_manager", ".", ...
https://github.com/googleads/googleads-python-lib/blob/b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee/examples/ad_manager/v202108/order_service/get_all_orders.py#L23-L43
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/protocols/basic.py
python
NetstringReceiver._handleParseError
(self)
Terminates the connection and sets the flag C{self.brokenPeer}.
Terminates the connection and sets the flag C{self.brokenPeer}.
[ "Terminates", "the", "connection", "and", "sets", "the", "flag", "C", "{", "self", ".", "brokenPeer", "}", "." ]
def _handleParseError(self): """ Terminates the connection and sets the flag C{self.brokenPeer}. """ self.transport.loseConnection() self.brokenPeer = 1
[ "def", "_handleParseError", "(", "self", ")", ":", "self", ".", "transport", ".", "loseConnection", "(", ")", "self", ".", "brokenPeer", "=", "1" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/protocols/basic.py#L413-L418
capnproto/pycapnp
d1bd4cb2569bfde3a8aaf46729e9dc130aa00ca0
buildutils/bundle.py
python
fetch_archive
(savedir, url, fname, force=False)
return dest
download an archive to a specific location
download an archive to a specific location
[ "download", "an", "archive", "to", "a", "specific", "location" ]
def fetch_archive(savedir, url, fname, force=False): """download an archive to a specific location""" dest = pjoin(savedir, fname) if os.path.exists(dest) and not force: print("already have %s" % fname) return dest print("fetching %s into %s" % (url, savedir)) if not os.path.exists(savedir): os.makedirs(savedir) req = urlopen(url) with open(dest, "wb") as f: f.write(req.read()) return dest
[ "def", "fetch_archive", "(", "savedir", ",", "url", ",", "fname", ",", "force", "=", "False", ")", ":", "dest", "=", "pjoin", "(", "savedir", ",", "fname", ")", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", "and", "not", "force", ":", ...
https://github.com/capnproto/pycapnp/blob/d1bd4cb2569bfde3a8aaf46729e9dc130aa00ca0/buildutils/bundle.py#L53-L65
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/geometry/creation/gear.py
python
getToothProfileCylinder
(derivation, pitchRadius, teeth)
return getToothProfileCylinderByProfile(derivation, pitchRadius, teeth, toothProfileHalf)
Get profile for one tooth of a cylindrical gear.
Get profile for one tooth of a cylindrical gear.
[ "Get", "profile", "for", "one", "tooth", "of", "a", "cylindrical", "gear", "." ]
def getToothProfileCylinder(derivation, pitchRadius, teeth): 'Get profile for one tooth of a cylindrical gear.' toothProfileHalfCylinder = getToothProfileHalfCylinder(derivation, pitchRadius) toothProfileHalfCylinder = getThicknessMultipliedPath(toothProfileHalfCylinder, derivation.toothThicknessMultiplier) toothProfileHalf = [] innerRadius = pitchRadius - derivation.dedendum for point in toothProfileHalfCylinder: if abs(point) >= innerRadius: toothProfileHalf.append(point) return getToothProfileCylinderByProfile(derivation, pitchRadius, teeth, toothProfileHalf)
[ "def", "getToothProfileCylinder", "(", "derivation", ",", "pitchRadius", ",", "teeth", ")", ":", "toothProfileHalfCylinder", "=", "getToothProfileHalfCylinder", "(", "derivation", ",", "pitchRadius", ")", "toothProfileHalfCylinder", "=", "getThicknessMultipliedPath", "(", ...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/geometry/creation/gear.py#L932-L941
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/parser/nltk_lite/semantics/utilities.py
python
text_parse
(inputs, grammar, trace=0)
return parses
Convert input sentences into syntactic trees.
Convert input sentences into syntactic trees.
[ "Convert", "input", "sentences", "into", "syntactic", "trees", "." ]
def text_parse(inputs, grammar, trace=0): """ Convert input sentences into syntactic trees. """ parses = {} for sent in inputs: tokens = list(tokenize.whitespace(sent)) parser = grammar.earley_parser(trace=trace) syntrees = parser.get_parse_list(tokens) parses[sent] = syntrees return parses
[ "def", "text_parse", "(", "inputs", ",", "grammar", ",", "trace", "=", "0", ")", ":", "parses", "=", "{", "}", "for", "sent", "in", "inputs", ":", "tokens", "=", "list", "(", "tokenize", ".", "whitespace", "(", "sent", ")", ")", "parser", "=", "gra...
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/parser/nltk_lite/semantics/utilities.py#L26-L36
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/logging/__init__.py
python
Filterer.addFilter
(self, filter)
Add the specified filter to this handler.
Add the specified filter to this handler.
[ "Add", "the", "specified", "filter", "to", "this", "handler", "." ]
def addFilter(self, filter): """ Add the specified filter to this handler. """ if not (filter in self.filters): self.filters.append(filter)
[ "def", "addFilter", "(", "self", ",", "filter", ")", ":", "if", "not", "(", "filter", "in", "self", ".", "filters", ")", ":", "self", ".", "filters", ".", "append", "(", "filter", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/logging/__init__.py#L593-L598
PythonCharmers/python-future
80523f383fbba1c6de0551e19d0277e73e69573c
src/future/backports/email/message.py
python
Message.get_content_charset
(self, failobj=None)
return charset.lower()
Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.
Return the charset parameter of the Content-Type header.
[ "Return", "the", "charset", "parameter", "of", "the", "Content", "-", "Type", "header", "." ]
def get_content_charset(self, failobj=None): """Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. """ missing = object() charset = self.get_param('charset', missing) if charset is missing: return failobj if isinstance(charset, tuple): # RFC 2231 encoded, so decode it, and it better end up as ascii. pcharset = charset[0] or 'us-ascii' try: # LookupError will be raised if the charset isn't known to # Python. UnicodeError will be raised if the encoded text # contains a character not in the charset. as_bytes = charset[2].encode('raw-unicode-escape') charset = str(as_bytes, pcharset) except (LookupError, UnicodeError): charset = charset[2] # charset characters must be in us-ascii range try: charset.encode('us-ascii') except UnicodeError: return failobj # RFC 2046, $4.1.2 says charsets are not case sensitive return charset.lower()
[ "def", "get_content_charset", "(", "self", ",", "failobj", "=", "None", ")", ":", "missing", "=", "object", "(", ")", "charset", "=", "self", ".", "get_param", "(", "'charset'", ",", "missing", ")", "if", "charset", "is", "missing", ":", "return", "failo...
https://github.com/PythonCharmers/python-future/blob/80523f383fbba1c6de0551e19d0277e73e69573c/src/future/backports/email/message.py#L833-L861
lda-project/lda
b8afeda0bf740a86ce1f11f48f2a6a3735b978be
lda/lda.py
python
LDA.fit
(self, X, y=None)
return self
Fit the model with X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training data, where n_samples in the number of samples and n_features is the number of features. Sparse matrix allowed. Returns ------- self : object Returns the instance itself.
Fit the model with X.
[ "Fit", "the", "model", "with", "X", "." ]
def fit(self, X, y=None): """Fit the model with X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training data, where n_samples in the number of samples and n_features is the number of features. Sparse matrix allowed. Returns ------- self : object Returns the instance itself. """ self._fit(X) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "_fit", "(", "X", ")", "return", "self" ]
https://github.com/lda-project/lda/blob/b8afeda0bf740a86ce1f11f48f2a6a3735b978be/lda/lda.py#L116-L131
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/scrapy/commands/__init__.py
python
ScrapyCommand.long_desc
(self)
return self.short_desc()
A long description of the command. Return short description when not available. It cannot contain newlines, since contents will be formatted by optparser which removes newlines and wraps text.
A long description of the command. Return short description when not available. It cannot contain newlines, since contents will be formatted by optparser which removes newlines and wraps text.
[ "A", "long", "description", "of", "the", "command", ".", "Return", "short", "description", "when", "not", "available", ".", "It", "cannot", "contain", "newlines", "since", "contents", "will", "be", "formatted", "by", "optparser", "which", "removes", "newlines", ...
def long_desc(self): """A long description of the command. Return short description when not available. It cannot contain newlines, since contents will be formatted by optparser which removes newlines and wraps text. """ return self.short_desc()
[ "def", "long_desc", "(", "self", ")", ":", "return", "self", ".", "short_desc", "(", ")" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/scrapy/commands/__init__.py#L41-L46
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/configparser.py
python
InterpolationMissingOptionError.__init__
(self, option, section, rawval, reference)
[]
def __init__(self, option, section, rawval, reference): msg = ("Bad value substitution:\n" "\tsection: [%s]\n" "\toption : %s\n" "\tkey : %s\n" "\trawval : %s\n" % (section, option, reference, rawval)) InterpolationError.__init__(self, option, section, msg) self.reference = reference self.args = (option, section, rawval, reference)
[ "def", "__init__", "(", "self", ",", "option", ",", "section", ",", "rawval", ",", "reference", ")", ":", "msg", "=", "(", "\"Bad value substitution:\\n\"", "\"\\tsection: [%s]\\n\"", "\"\\toption : %s\\n\"", "\"\\tkey : %s\\n\"", "\"\\trawval : %s\\n\"", "%", "(", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/configparser.py#L260-L269
rlgraph/rlgraph
428fc136a9a075f29a397495b4226a491a287be2
rlgraph/components/policies/policy.py
python
Policy._graph_fn_get_distribution_entropies
(self, flat_key, parameters)
return self.distributions[flat_key].entropy(parameters)
Pushes `parameters` through the respective self.distributions' `entropy` API-methods and returns a DataOp with the entropy values. Args: parameters (DataOp): The parameters to define a distribution. This could be a ContainerDataOp, which container the parameter pieces for each action component. Returns: SingleDataOp: The DataOp with the `entropy` outputs for the given flat_key distribution.
Pushes `parameters` through the respective self.distributions' `entropy` API-methods and returns a DataOp with the entropy values.
[ "Pushes", "parameters", "through", "the", "respective", "self", ".", "distributions", "entropy", "API", "-", "methods", "and", "returns", "a", "DataOp", "with", "the", "entropy", "values", "." ]
def _graph_fn_get_distribution_entropies(self, flat_key, parameters): """ Pushes `parameters` through the respective self.distributions' `entropy` API-methods and returns a DataOp with the entropy values. Args: parameters (DataOp): The parameters to define a distribution. This could be a ContainerDataOp, which container the parameter pieces for each action component. Returns: SingleDataOp: The DataOp with the `entropy` outputs for the given flat_key distribution. """ return self.distributions[flat_key].entropy(parameters)
[ "def", "_graph_fn_get_distribution_entropies", "(", "self", ",", "flat_key", ",", "parameters", ")", ":", "return", "self", ".", "distributions", "[", "flat_key", "]", ".", "entropy", "(", "parameters", ")" ]
https://github.com/rlgraph/rlgraph/blob/428fc136a9a075f29a397495b4226a491a287be2/rlgraph/components/policies/policy.py#L382-L394
czhu95/ternarynet
1a67251f7f5a1cdf854f87f90f841655c7c9f11c
tensorpack/dataflow/imgaug/crop.py
python
CenterCrop.__init__
(self, crop_shape)
:param crop_shape: a shape like (h, w)
:param crop_shape: a shape like (h, w)
[ ":", "param", "crop_shape", ":", "a", "shape", "like", "(", "h", "w", ")" ]
def __init__(self, crop_shape): """ :param crop_shape: a shape like (h, w) """ self._init(locals())
[ "def", "__init__", "(", "self", ",", "crop_shape", ")", ":", "self", ".", "_init", "(", "locals", "(", ")", ")" ]
https://github.com/czhu95/ternarynet/blob/1a67251f7f5a1cdf854f87f90f841655c7c9f11c/tensorpack/dataflow/imgaug/crop.py#L42-L46
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/clustering/clustertree.py
python
ClusterNode._get_prof
(self)
return self._profile
[]
def _get_prof(self): if self._profile is None: self._calculate_avg_profile() return self._profile
[ "def", "_get_prof", "(", "self", ")", ":", "if", "self", ".", "_profile", "is", "None", ":", "self", ".", "_calculate_avg_profile", "(", ")", "return", "self", ".", "_profile" ]
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/clustering/clustertree.py#L83-L86
rmountjoy92/VectorCloud
29e705d6636412c44034baaf8d9020e01a11502a
vectorcloud/rest_api/resources.py
python
AddCommand.put
(self)
return {'Commands': command_list}
[]
def put(self): command = request.form['data'] db_command = Command(command=command) db.session.add(db_command) db.session.commit() commands = Command.query.all() command_list = [] for command in commands: command_list.append(command.command) return {'Commands': command_list}
[ "def", "put", "(", "self", ")", ":", "command", "=", "request", ".", "form", "[", "'data'", "]", "db_command", "=", "Command", "(", "command", "=", "command", ")", "db", ".", "session", ".", "add", "(", "db_command", ")", "db", ".", "session", ".", ...
https://github.com/rmountjoy92/VectorCloud/blob/29e705d6636412c44034baaf8d9020e01a11502a/vectorcloud/rest_api/resources.py#L72-L83
zhang-can/ECO-pytorch
355c3866b35cdaa5d451263c1f3291c150e22eeb
tf_model_zoo/models/im2txt/im2txt/show_and_tell_model.py
python
ShowAndTellModel.process_image
(self, encoded_image, thread_id=0)
return image_processing.process_image(encoded_image, is_training=self.is_training(), height=self.config.image_height, width=self.config.image_width, thread_id=thread_id, image_format=self.config.image_format)
Decodes and processes an image string. Args: encoded_image: A scalar string Tensor; the encoded image. thread_id: Preprocessing thread id used to select the ordering of color distortions. Returns: A float32 Tensor of shape [height, width, 3]; the processed image.
Decodes and processes an image string.
[ "Decodes", "and", "processes", "an", "image", "string", "." ]
def process_image(self, encoded_image, thread_id=0): """Decodes and processes an image string. Args: encoded_image: A scalar string Tensor; the encoded image. thread_id: Preprocessing thread id used to select the ordering of color distortions. Returns: A float32 Tensor of shape [height, width, 3]; the processed image. """ return image_processing.process_image(encoded_image, is_training=self.is_training(), height=self.config.image_height, width=self.config.image_width, thread_id=thread_id, image_format=self.config.image_format)
[ "def", "process_image", "(", "self", ",", "encoded_image", ",", "thread_id", "=", "0", ")", ":", "return", "image_processing", ".", "process_image", "(", "encoded_image", ",", "is_training", "=", "self", ".", "is_training", "(", ")", ",", "height", "=", "sel...
https://github.com/zhang-can/ECO-pytorch/blob/355c3866b35cdaa5d451263c1f3291c150e22eeb/tf_model_zoo/models/im2txt/im2txt/show_and_tell_model.py#L103-L119
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v2beta2_hpa_scaling_policy.py
python
V2beta2HPAScalingPolicy.period_seconds
(self)
return self._period_seconds
Gets the period_seconds of this V2beta2HPAScalingPolicy. # noqa: E501 PeriodSeconds specifies the window of time for which the policy should hold true. PeriodSeconds must be greater than zero and less than or equal to 1800 (30 min). # noqa: E501 :return: The period_seconds of this V2beta2HPAScalingPolicy. # noqa: E501 :rtype: int
Gets the period_seconds of this V2beta2HPAScalingPolicy. # noqa: E501
[ "Gets", "the", "period_seconds", "of", "this", "V2beta2HPAScalingPolicy", ".", "#", "noqa", ":", "E501" ]
def period_seconds(self): """Gets the period_seconds of this V2beta2HPAScalingPolicy. # noqa: E501 PeriodSeconds specifies the window of time for which the policy should hold true. PeriodSeconds must be greater than zero and less than or equal to 1800 (30 min). # noqa: E501 :return: The period_seconds of this V2beta2HPAScalingPolicy. # noqa: E501 :rtype: int """ return self._period_seconds
[ "def", "period_seconds", "(", "self", ")", ":", "return", "self", ".", "_period_seconds" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v2beta2_hpa_scaling_policy.py#L63-L71
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/controller_service_dto.py
python
ControllerServiceDTO.referencing_components
(self, referencing_components)
Sets the referencing_components of this ControllerServiceDTO. All components referencing this controller service. :param referencing_components: The referencing_components of this ControllerServiceDTO. :type: list[ControllerServiceReferencingComponentEntity]
Sets the referencing_components of this ControllerServiceDTO. All components referencing this controller service.
[ "Sets", "the", "referencing_components", "of", "this", "ControllerServiceDTO", ".", "All", "components", "referencing", "this", "controller", "service", "." ]
def referencing_components(self, referencing_components): """ Sets the referencing_components of this ControllerServiceDTO. All components referencing this controller service. :param referencing_components: The referencing_components of this ControllerServiceDTO. :type: list[ControllerServiceReferencingComponentEntity] """ self._referencing_components = referencing_components
[ "def", "referencing_components", "(", "self", ",", "referencing_components", ")", ":", "self", ".", "_referencing_components", "=", "referencing_components" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/controller_service_dto.py#L588-L597
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/pandas/tseries/holiday.py
python
next_monday_or_tuesday
(dt)
return dt
For second holiday of two adjacent ones! If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday or Monday, use following Tuesday instead (because Monday is already taken by adjacent holiday on the day before)
For second holiday of two adjacent ones! If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday or Monday, use following Tuesday instead (because Monday is already taken by adjacent holiday on the day before)
[ "For", "second", "holiday", "of", "two", "adjacent", "ones!", "If", "holiday", "falls", "on", "Saturday", "use", "following", "Monday", "instead", ";", "if", "holiday", "falls", "on", "Sunday", "or", "Monday", "use", "following", "Tuesday", "instead", "(", "...
def next_monday_or_tuesday(dt): """ For second holiday of two adjacent ones! If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday or Monday, use following Tuesday instead (because Monday is already taken by adjacent holiday on the day before) """ dow = dt.weekday() if dow == 5 or dow == 6: return dt + timedelta(2) elif dow == 0: return dt + timedelta(1) return dt
[ "def", "next_monday_or_tuesday", "(", "dt", ")", ":", "dow", "=", "dt", ".", "weekday", "(", ")", "if", "dow", "==", "5", "or", "dow", "==", "6", ":", "return", "dt", "+", "timedelta", "(", "2", ")", "elif", "dow", "==", "0", ":", "return", "dt",...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/tseries/holiday.py#L23-L35
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/core/management/base.py
python
BaseCommand.usage
(self, subcommand)
Return a brief description of how to use this command, by default from the attribute ``self.help``.
Return a brief description of how to use this command, by default from the attribute ``self.help``.
[ "Return", "a", "brief", "description", "of", "how", "to", "use", "this", "command", "by", "default", "from", "the", "attribute", "self", ".", "help", "." ]
def usage(self, subcommand): """ Return a brief description of how to use this command, by default from the attribute ``self.help``. """ usage = '%%prog %s [options] %s' % (subcommand, self.args) if self.help: return '%s\n\n%s' % (usage, self.help) else: return usage
[ "def", "usage", "(", "self", ",", "subcommand", ")", ":", "usage", "=", "'%%prog %s [options] %s'", "%", "(", "subcommand", ",", "self", ".", "args", ")", "if", "self", ".", "help", ":", "return", "'%s\\n\\n%s'", "%", "(", "usage", ",", "self", ".", "h...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/core/management/base.py#L179-L189
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/click/core.py
python
CommandCollection.add_source
(self, multi_cmd)
Adds a new multi command to the chain dispatcher.
Adds a new multi command to the chain dispatcher.
[ "Adds", "a", "new", "multi", "command", "to", "the", "chain", "dispatcher", "." ]
def add_source(self, multi_cmd): """Adds a new multi command to the chain dispatcher.""" self.sources.append(multi_cmd)
[ "def", "add_source", "(", "self", ",", "multi_cmd", ")", ":", "self", ".", "sources", ".", "append", "(", "multi_cmd", ")" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/click/core.py#L1199-L1201
edwardlib/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
observations/r/gaba.py
python
gaba
(path)
return x_train, metadata
Effect of pentazocine on post-operative pain (average VAS scores) The table shows, separately for males and females, the effect of pentazocine on post-operative pain profiles (average VAS scores), with (mbac and fbac) and without (mpl and fpl) preoperatively administered baclofen. Pain scores are recorded every 20 minutes, from 10 minutes to 170 minutes. A data frame with 9 observations on the following 7 variables. `min` a numeric vector `mbac` a numeric vector `mpl` a numeric vector `fbac` a numeric vector `fpl` a numeric vector `avbac` a numeric vector `avplac` a numeric vector Gordon, N. C. et al.(1995): 'Enhancement of Morphine Analgesia by the GABA\ *\_B* against Baclofen'. *Neuroscience* 69: 345-349. Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `gaba.csv`. Returns: Tuple of np.ndarray `x_train` with 9 rows and 7 columns and dictionary `metadata` of column headers (feature names).
Effect of pentazocine on post-operative pain (average VAS scores)
[ "Effect", "of", "pentazocine", "on", "post", "-", "operative", "pain", "(", "average", "VAS", "scores", ")" ]
def gaba(path): """Effect of pentazocine on post-operative pain (average VAS scores) The table shows, separately for males and females, the effect of pentazocine on post-operative pain profiles (average VAS scores), with (mbac and fbac) and without (mpl and fpl) preoperatively administered baclofen. Pain scores are recorded every 20 minutes, from 10 minutes to 170 minutes. A data frame with 9 observations on the following 7 variables. `min` a numeric vector `mbac` a numeric vector `mpl` a numeric vector `fbac` a numeric vector `fpl` a numeric vector `avbac` a numeric vector `avplac` a numeric vector Gordon, N. C. et al.(1995): 'Enhancement of Morphine Analgesia by the GABA\ *\_B* against Baclofen'. *Neuroscience* 69: 345-349. Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `gaba.csv`. Returns: Tuple of np.ndarray `x_train` with 9 rows and 7 columns and dictionary `metadata` of column headers (feature names). """ import pandas as pd path = os.path.expanduser(path) filename = 'gaba.csv' if not os.path.exists(os.path.join(path, filename)): url = 'http://dustintran.com/data/r/DAAG/gaba.csv' maybe_download_and_extract(path, url, save_file_name='gaba.csv', resume=False) data = pd.read_csv(os.path.join(path, filename), index_col=0, parse_dates=True) x_train = data.values metadata = {'columns': data.columns} return x_train, metadata
[ "def", "gaba", "(", "path", ")", ":", "import", "pandas", "as", "pd", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "filename", "=", "'gaba.csv'", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", ...
https://github.com/edwardlib/observations/blob/2c8b1ac31025938cb17762e540f2f592e302d5de/observations/r/gaba.py#L14-L74
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pkg_resources/_vendor/pyparsing.py
python
Group.__init__
( self, expr )
[]
def __init__( self, expr ): super(Group,self).__init__( expr ) self.saveAsList = True
[ "def", "__init__", "(", "self", ",", "expr", ")", ":", "super", "(", "Group", ",", "self", ")", ".", "__init__", "(", "expr", ")", "self", ".", "saveAsList", "=", "True" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pkg_resources/_vendor/pyparsing.py#L4251-L4253
dgk/django-business-logic
80c1ee24478bdc0dbb4916cf7603b6514f89af4b
business_logic/rest/serializers.py
python
ReferenceDescriptorListSerializer.get_verbose_name
(self, obj)
return obj.title or obj.content_type.model_class()._meta.verbose_name
[]
def get_verbose_name(self, obj): return obj.title or obj.content_type.model_class()._meta.verbose_name
[ "def", "get_verbose_name", "(", "self", ",", "obj", ")", ":", "return", "obj", ".", "title", "or", "obj", ".", "content_type", ".", "model_class", "(", ")", ".", "_meta", ".", "verbose_name" ]
https://github.com/dgk/django-business-logic/blob/80c1ee24478bdc0dbb4916cf7603b6514f89af4b/business_logic/rest/serializers.py#L179-L180
kevoreilly/CAPEv2
6cf79c33264624b3604d4cd432cde2a6b4536de6
modules/processing/network.py
python
payload_from_raw
(raw, linktype=1)
Get the payload from a packet, the data below TCP/UDP basically
Get the payload from a packet, the data below TCP/UDP basically
[ "Get", "the", "payload", "from", "a", "packet", "the", "data", "below", "TCP", "/", "UDP", "basically" ]
def payload_from_raw(raw, linktype=1): """Get the payload from a packet, the data below TCP/UDP basically""" ip = iplayer_from_raw(raw, linktype) try: return ip.data.data except Exception: return b""
[ "def", "payload_from_raw", "(", "raw", ",", "linktype", "=", "1", ")", ":", "ip", "=", "iplayer_from_raw", "(", "raw", ",", "linktype", ")", "try", ":", "return", "ip", ".", "data", ".", "data", "except", "Exception", ":", "return", "b\"\"" ]
https://github.com/kevoreilly/CAPEv2/blob/6cf79c33264624b3604d4cd432cde2a6b4536de6/modules/processing/network.py#L1274-L1280
nathanlopez/Stitch
8e22e91c94237959c02d521aab58dc7e3d994cea
Configuration/mss/linux.py
python
MSS.enum_display_monitors
(self, force=False)
return self.monitors
Get positions of monitors (see parent class).
Get positions of monitors (see parent class).
[ "Get", "positions", "of", "monitors", "(", "see", "parent", "class", ")", "." ]
def enum_display_monitors(self, force=False): ''' Get positions of monitors (see parent class). ''' if not self.monitors or force: self.monitors = [] # All monitors gwa = XWindowAttributes() self.xlib.XGetWindowAttributes(self.display, self.root, byref(gwa)) self.monitors.append({ 'left': int(gwa.x), 'top': int(gwa.y), 'width': int(gwa.width), 'height': int(gwa.height), 'monitor': 0 }) # Each monitors # Fix for XRRGetScreenResources: # expected LP_Display instance instead of LP_XWindowAttributes root = cast(self.root, POINTER(Display)) mon = self.xrandr.XRRGetScreenResources(self.display, root) for num in range(mon.contents.ncrtc): crtc = self.xrandr.XRRGetCrtcInfo(self.display, mon, mon.contents.crtcs[num]) self.monitors.append({ 'left': int(crtc.contents.x), 'top': int(crtc.contents.y), 'width': int(crtc.contents.width), 'height': int(crtc.contents.height), 'monitor': num }) self.xrandr.XRRFreeCrtcInfo(crtc) self.xrandr.XRRFreeScreenResources(mon) return self.monitors
[ "def", "enum_display_monitors", "(", "self", ",", "force", "=", "False", ")", ":", "if", "not", "self", ".", "monitors", "or", "force", ":", "self", ".", "monitors", "=", "[", "]", "# All monitors", "gwa", "=", "XWindowAttributes", "(", ")", "self", ".",...
https://github.com/nathanlopez/Stitch/blob/8e22e91c94237959c02d521aab58dc7e3d994cea/Configuration/mss/linux.py#L213-L248
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/codeop.py
python
_compile
(source, filename, symbol)
return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT)
[]
def _compile(source, filename, symbol): return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT)
[ "def", "_compile", "(", "source", ",", "filename", ",", "symbol", ")", ":", "return", "compile", "(", "source", ",", "filename", ",", "symbol", ",", "PyCF_DONT_IMPLY_DEDENT", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/codeop.py#L101-L102
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_volume.py
python
Yedit.get_entry
(data, key, sep='.')
return data
Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c
Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c
[ "Get", "an", "item", "from", "a", "dictionary", "with", "key", "notation", "a", ".", "b", ".", "c", "d", "=", "{", "a", ":", "{", "b", ":", "c", "}}}", "key", "=", "a", ".", "b", "return", "c" ]
def get_entry(data, key, sep='.'): ''' Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c ''' if key == '': pass elif (not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict))): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None return data
[ "def", "get_entry", "(", "data", ",", "key", ",", "sep", "=", "'.'", ")", ":", "if", "key", "==", "''", ":", "pass", "elif", "(", "not", "(", "key", "and", "Yedit", ".", "valid_key", "(", "key", ",", "sep", ")", ")", "and", "isinstance", "(", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_volume.py#L359-L381
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/papylib/Worker.py
python
Worker._handle_action_add_group
(self, name)
handle Action.ACTION_ADD_GROUP
handle Action.ACTION_ADD_GROUP
[ "handle", "Action", ".", "ACTION_ADD_GROUP" ]
def _handle_action_add_group(self, name): '''handle Action.ACTION_ADD_GROUP ''' def add_group_fail(*args): log.error("Error adding a group: %s", args) #group name self.session.group_add_failed('') def add_group_succeed(*args): #group id self.session.group_add_succeed(args[0].id) callback_vect = [add_group_succeed,name] self.address_book.add_group(name, failed_cb=add_group_fail, done_cb=tuple(callback_vect))
[ "def", "_handle_action_add_group", "(", "self", ",", "name", ")", ":", "def", "add_group_fail", "(", "*", "args", ")", ":", "log", ".", "error", "(", "\"Error adding a group: %s\"", ",", "args", ")", "#group name", "self", ".", "session", ".", "group_add_faile...
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/papylib/Worker.py#L964-L977
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pymongo/message.py
python
_randint
()
return random.randint(MIN_INT32, MAX_INT32)
Generate a pseudo random 32 bit integer.
Generate a pseudo random 32 bit integer.
[ "Generate", "a", "pseudo", "random", "32", "bit", "integer", "." ]
def _randint(): """Generate a pseudo random 32 bit integer.""" return random.randint(MIN_INT32, MAX_INT32)
[ "def", "_randint", "(", ")", ":", "return", "random", ".", "randint", "(", "MIN_INT32", ",", "MAX_INT32", ")" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pymongo/message.py#L88-L90
python-cmd2/cmd2
c1f6114d52161a3b8a32d3cee1c495d79052e1fb
cmd2/argparse_completer.py
python
ArgparseCompleter._complete_flags
(self, text: str, line: str, begidx: int, endidx: int, matched_flags: List[str])
return matches
Tab completion routine for a parsers unused flags
Tab completion routine for a parsers unused flags
[ "Tab", "completion", "routine", "for", "a", "parsers", "unused", "flags" ]
def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, matched_flags: List[str]) -> List[str]: """Tab completion routine for a parsers unused flags""" # Build a list of flags that can be tab completed match_against = [] for flag in self._flags: # Make sure this flag hasn't already been used if flag not in matched_flags: # Make sure this flag isn't considered hidden action = self._flag_to_action[flag] if action.help != argparse.SUPPRESS: match_against.append(flag) matches = self._cmd2_app.basic_complete(text, line, begidx, endidx, match_against) # Build a dictionary linking actions with their matched flag names matched_actions: Dict[argparse.Action, List[str]] = dict() for flag in matches: action = self._flag_to_action[flag] matched_actions.setdefault(action, []) matched_actions[action].append(flag) # For tab completion suggestions, group matched flags by action for action, option_strings in matched_actions.items(): flag_text = ', '.join(option_strings) # Mark optional flags with brackets if not action.required: flag_text = '[' + flag_text + ']' self._cmd2_app.display_matches.append(flag_text) return matches
[ "def", "_complete_flags", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ",", "matched_flags", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "# Build a l...
https://github.com/python-cmd2/cmd2/blob/c1f6114d52161a3b8a32d3cee1c495d79052e1fb/cmd2/argparse_completer.py#L516-L548
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/misc/hookset.py
python
HookedMethod.__call__
(self, *args, **kwargs)
[]
def __call__(self, *args, **kwargs): if self.pending: current_hook = self.pending.pop() try: result = current_hook(self.func.__self__, *args, **kwargs) finally: self.pending.append(current_hook) return result else: return self.func(*args, **kwargs)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "pending", ":", "current_hook", "=", "self", ".", "pending", ".", "pop", "(", ")", "try", ":", "result", "=", "current_hook", "(", "self", ".", ...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/misc/hookset.py#L71-L80
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow/Detection/SSD/models/research/object_detection/core/region_similarity_calculator.py
python
RegionSimilarityCalculator.compare
(self, boxlist1, boxlist2, scope=None)
Computes matrix of pairwise similarity between BoxLists. This op (to be overridden) computes a measure of pairwise similarity between the boxes in the given BoxLists. Higher values indicate more similarity. Note that this method simply measures similarity and does not explicitly perform a matching. Args: boxlist1: BoxList holding N boxes. boxlist2: BoxList holding M boxes. scope: Op scope name. Defaults to 'Compare' if None. Returns: a (float32) tensor of shape [N, M] with pairwise similarity score.
Computes matrix of pairwise similarity between BoxLists.
[ "Computes", "matrix", "of", "pairwise", "similarity", "between", "BoxLists", "." ]
def compare(self, boxlist1, boxlist2, scope=None): """Computes matrix of pairwise similarity between BoxLists. This op (to be overridden) computes a measure of pairwise similarity between the boxes in the given BoxLists. Higher values indicate more similarity. Note that this method simply measures similarity and does not explicitly perform a matching. Args: boxlist1: BoxList holding N boxes. boxlist2: BoxList holding M boxes. scope: Op scope name. Defaults to 'Compare' if None. Returns: a (float32) tensor of shape [N, M] with pairwise similarity score. """ with tf.name_scope(scope, 'Compare', [boxlist1, boxlist2]) as scope: return self._compare(boxlist1, boxlist2)
[ "def", "compare", "(", "self", ",", "boxlist1", ",", "boxlist2", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'Compare'", ",", "[", "boxlist1", ",", "boxlist2", "]", ")", "as", "scope", ":", "return", "sel...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/Detection/SSD/models/research/object_detection/core/region_similarity_calculator.py#L34-L52
Alfanous-team/alfanous
594514729473c24efa3908e3107b45a38255de4b
src/alfanous/Support/whoosh/support/levenshtein.py
python
relative
(a, b)
return r
Returns the relative distance between two strings, in the range [0-1] where 1 means total equality.
Returns the relative distance between two strings, in the range [0-1] where 1 means total equality.
[ "Returns", "the", "relative", "distance", "between", "two", "strings", "in", "the", "range", "[", "0", "-", "1", "]", "where", "1", "means", "total", "equality", "." ]
def relative(a, b): """Returns the relative distance between two strings, in the range [0-1] where 1 means total equality. """ d = distance(a,b) longer = float(max((len(a), len(b)))) shorter = float(min((len(a), len(b)))) r = ((longer - d) / longer) * (shorter / longer) return r
[ "def", "relative", "(", "a", ",", "b", ")", ":", "d", "=", "distance", "(", "a", ",", "b", ")", "longer", "=", "float", "(", "max", "(", "(", "len", "(", "a", ")", ",", "len", "(", "b", ")", ")", ")", ")", "shorter", "=", "float", "(", "m...
https://github.com/Alfanous-team/alfanous/blob/594514729473c24efa3908e3107b45a38255de4b/src/alfanous/Support/whoosh/support/levenshtein.py#L5-L13
matplotlib/viscm
e9c1f5336706634f8c90c69a99da69dd19c7c45b
viscm/bezierbuilder.py
python
ControlPointModel.remove_point
(self, i)
[]
def remove_point(self, i): if i == self._fixed: return del self._xp[i] del self._yp[i] if self._fixed is not None and i < self._fixed: self._fixed -= 1 self.trigger.fire()
[ "def", "remove_point", "(", "self", ",", "i", ")", ":", "if", "i", "==", "self", ".", "_fixed", ":", "return", "del", "self", ".", "_xp", "[", "i", "]", "del", "self", ".", "_yp", "[", "i", "]", "if", "self", ".", "_fixed", "is", "not", "None",...
https://github.com/matplotlib/viscm/blob/e9c1f5336706634f8c90c69a99da69dd19c7c45b/viscm/bezierbuilder.py#L64-L71
yanzhou/CnkiSpider
348d7114f3ffee7b0a134cf6c5d01150433f3fde
src/bs4/builder/_html5lib.py
python
HTML5TreeBuilder.test_fragment_to_document
(self, fragment)
return u'<html><head></head><body>%s</body></html>' % fragment
See `TreeBuilder`.
See `TreeBuilder`.
[ "See", "TreeBuilder", "." ]
def test_fragment_to_document(self, fragment): """See `TreeBuilder`.""" return u'<html><head></head><body>%s</body></html>' % fragment
[ "def", "test_fragment_to_document", "(", "self", ",", "fragment", ")", ":", "return", "u'<html><head></head><body>%s</body></html>'", "%", "fragment" ]
https://github.com/yanzhou/CnkiSpider/blob/348d7114f3ffee7b0a134cf6c5d01150433f3fde/src/bs4/builder/_html5lib.py#L52-L54
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/vendor/pygraph/classes/hypergraph.py
python
hypergraph.has_hyperedge
(self, hyperedge)
return hyperedge in self.edge_links
Return whether the requested node exists. @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier @rtype: boolean @return: Truth-value for hyperedge existence.
Return whether the requested node exists.
[ "Return", "whether", "the", "requested", "node", "exists", "." ]
def has_hyperedge(self, hyperedge): """ Return whether the requested node exists. @type hyperedge: hyperedge @param hyperedge: Hyperedge identifier @rtype: boolean @return: Truth-value for hyperedge existence. """ return hyperedge in self.edge_links
[ "def", "has_hyperedge", "(", "self", ",", "hyperedge", ")", ":", "return", "hyperedge", "in", "self", ".", "edge_links" ]
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/pygraph/classes/hypergraph.py#L109-L119
EtienneCmb/visbrain
b599038e095919dc193b12d5e502d127de7d03c9
visbrain/io/read_data.py
python
read_pickle
(path, vars=None)
Read data from a Pickle (pickle) file.
Read data from a Pickle (pickle) file.
[ "Read", "data", "from", "a", "Pickle", "(", "pickle", ")", "file", "." ]
def read_pickle(path, vars=None): """Read data from a Pickle (pickle) file.""" # np.loads? ou depuis import pickle pass
[ "def", "read_pickle", "(", "path", ",", "vars", "=", "None", ")", ":", "# np.loads? ou depuis import pickle", "pass" ]
https://github.com/EtienneCmb/visbrain/blob/b599038e095919dc193b12d5e502d127de7d03c9/visbrain/io/read_data.py#L32-L35
qmlcode/qml
8bb833cdbbe69405384d6796920c5418dc53b6ba
qml/arad.py
python
get_atomic_symmetric_kernels_arad
(X1, sigmas, width=0.2, cut_distance=5.0, r_width=1.0, c_width=0.5)
return fget_atomic_symmetric_kernels_arad(X1, Z1_arad, N1, sigmas, na1, nsigmas, width, cut_distance, r_width, c_width)
Calculates the Gaussian kernel matrix K for atomic ARAD descriptors for a list of different sigmas. For atomic properties, e.g. partial charges, chemical shifts, etc. K is calculated using an OpenMP parallel Fortran routine. :param X1: ARAD descriptors for molecules in set 1. shape=(number_atoms,5,size) :type X1: numpy array :param sigmas: List of sigmas for which to calculate the Kernel matrices. :type sigmas: list :return: The kernel matrices for each sigma - shape (number_sigmas, number_atoms1, number_atoms1) :rtype: numpy array
Calculates the Gaussian kernel matrix K for atomic ARAD descriptors for a list of different sigmas. For atomic properties, e.g. partial charges, chemical shifts, etc.
[ "Calculates", "the", "Gaussian", "kernel", "matrix", "K", "for", "atomic", "ARAD", "descriptors", "for", "a", "list", "of", "different", "sigmas", ".", "For", "atomic", "properties", "e", ".", "g", ".", "partial", "charges", "chemical", "shifts", "etc", "." ...
def get_atomic_symmetric_kernels_arad(X1, sigmas, width=0.2, cut_distance=5.0, r_width=1.0, c_width=0.5): """ Calculates the Gaussian kernel matrix K for atomic ARAD descriptors for a list of different sigmas. For atomic properties, e.g. partial charges, chemical shifts, etc. K is calculated using an OpenMP parallel Fortran routine. :param X1: ARAD descriptors for molecules in set 1. shape=(number_atoms,5,size) :type X1: numpy array :param sigmas: List of sigmas for which to calculate the Kernel matrices. :type sigmas: list :return: The kernel matrices for each sigma - shape (number_sigmas, number_atoms1, number_atoms1) :rtype: numpy array """ assert len(X1.shape) == 3 na1 = X1.shape[0] N1 = np.empty(na1, dtype = np.int32) Z1_arad = np.zeros((na1, 2)) for i in range(na1): N1[i] = len(np.where(X1[i,0,:] < cut_distance)[0]) Z1_arad[i] = X1[i,1:3,0] sigmas = np.array(sigmas) nsigmas = sigmas.size return fget_atomic_symmetric_kernels_arad(X1, Z1_arad, N1, sigmas, na1, nsigmas, width, cut_distance, r_width, c_width)
[ "def", "get_atomic_symmetric_kernels_arad", "(", "X1", ",", "sigmas", ",", "width", "=", "0.2", ",", "cut_distance", "=", "5.0", ",", "r_width", "=", "1.0", ",", "c_width", "=", "0.5", ")", ":", "assert", "len", "(", "X1", ".", "shape", ")", "==", "3",...
https://github.com/qmlcode/qml/blob/8bb833cdbbe69405384d6796920c5418dc53b6ba/qml/arad.py#L343-L374
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/kms/layer1.py
python
KMSConnection.retire_grant
(self, grant_token)
return self.make_request(action='RetireGrant', body=json.dumps(params))
Retires a grant. You can retire a grant when you're done using it to clean up. You should revoke a grant when you intend to actively deny operations that depend on it. :type grant_token: string :param grant_token: Token that identifies the grant to be retired.
Retires a grant. You can retire a grant when you're done using it to clean up. You should revoke a grant when you intend to actively deny operations that depend on it.
[ "Retires", "a", "grant", ".", "You", "can", "retire", "a", "grant", "when", "you", "re", "done", "using", "it", "to", "clean", "up", ".", "You", "should", "revoke", "a", "grant", "when", "you", "intend", "to", "actively", "deny", "operations", "that", ...
def retire_grant(self, grant_token): """ Retires a grant. You can retire a grant when you're done using it to clean up. You should revoke a grant when you intend to actively deny operations that depend on it. :type grant_token: string :param grant_token: Token that identifies the grant to be retired. """ params = {'GrantToken': grant_token, } return self.make_request(action='RetireGrant', body=json.dumps(params))
[ "def", "retire_grant", "(", "self", ",", "grant_token", ")", ":", "params", "=", "{", "'GrantToken'", ":", "grant_token", ",", "}", "return", "self", ".", "make_request", "(", "action", "=", "'RetireGrant'", ",", "body", "=", "json", ".", "dumps", "(", "...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/kms/layer1.py#L753-L765
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/app_manager/models.py
python
Application.set_translations
(self, lang, translations)
[]
def set_translations(self, lang, translations): self.translations[lang] = translations
[ "def", "set_translations", "(", "self", ",", "lang", ",", "translations", ")", ":", "self", ".", "translations", "[", "lang", "]", "=", "translations" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/models.py#L4953-L4954
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/lib/takeover/udf.py
python
UDF.__init__
(self)
[]
def __init__(self): self.createdUdf = set() self.udfs = {} self.udfToCreate = set()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "createdUdf", "=", "set", "(", ")", "self", ".", "udfs", "=", "{", "}", "self", ".", "udfToCreate", "=", "set", "(", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/lib/takeover/udf.py#L37-L40
sabnzbd/sabnzbd
52d21e94d3cc6e30764a833fe2a256783d1a8931
sabnzbd/api.py
python
_api_change_opts
(name, kwargs)
return report(keyword="status", data=bool(result > 0))
API: accepts value(=nzo_id), value2(=pp)
API: accepts value(=nzo_id), value2(=pp)
[ "API", ":", "accepts", "value", "(", "=", "nzo_id", ")", "value2", "(", "=", "pp", ")" ]
def _api_change_opts(name, kwargs): """API: accepts value(=nzo_id), value2(=pp)""" value = kwargs.get("value") value2 = kwargs.get("value2") result = 0 if value and value2 and value2.isdigit(): result = sabnzbd.NzbQueue.change_opts(value, int(value2)) return report(keyword="status", data=bool(result > 0))
[ "def", "_api_change_opts", "(", "name", ",", "kwargs", ")", ":", "value", "=", "kwargs", ".", "get", "(", "\"value\"", ")", "value2", "=", "kwargs", ".", "get", "(", "\"value2\"", ")", "result", "=", "0", "if", "value", "and", "value2", "and", "value2"...
https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/api.py#L452-L459
BillBillBillBill/Tickeys-linux
2df31b8665004c58a5d4ab05277f245267d96364
tickeys/kivy/core/spelling/__init__.py
python
SpellingBase.check
(self, word)
If `word` is a valid word in `self._language` (the currently active language), returns True. If the word shouldn't be checked, returns None (e.g. for ''). If it is not a valid word in `self._language`, return False. :Parameters: `word` : str The word to check.
If `word` is a valid word in `self._language` (the currently active language), returns True. If the word shouldn't be checked, returns None (e.g. for ''). If it is not a valid word in `self._language`, return False.
[ "If", "word", "is", "a", "valid", "word", "in", "self", ".", "_language", "(", "the", "currently", "active", "language", ")", "returns", "True", ".", "If", "the", "word", "shouldn", "t", "be", "checked", "returns", "None", "(", "e", ".", "g", ".", "f...
def check(self, word): ''' If `word` is a valid word in `self._language` (the currently active language), returns True. If the word shouldn't be checked, returns None (e.g. for ''). If it is not a valid word in `self._language`, return False. :Parameters: `word` : str The word to check. ''' raise NotImplementedError('check() not implemented by abstract ' + 'spelling base class!')
[ "def", "check", "(", "self", ",", "word", ")", ":", "raise", "NotImplementedError", "(", "'check() not implemented by abstract '", "+", "'spelling base class!'", ")" ]
https://github.com/BillBillBillBill/Tickeys-linux/blob/2df31b8665004c58a5d4ab05277f245267d96364/tickeys/kivy/core/spelling/__init__.py#L101-L113
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/scsgate/cover.py
python
setup_platform
( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )
Set up the SCSGate cover.
Set up the SCSGate cover.
[ "Set", "up", "the", "SCSGate", "cover", "." ]
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the SCSGate cover.""" devices = config.get(CONF_DEVICES) covers = [] logger = logging.getLogger(__name__) scsgate = hass.data[DOMAIN] if devices: for entity_info in devices.values(): if entity_info[CONF_SCS_ID] in scsgate.devices: continue name = entity_info[CONF_NAME] scs_id = entity_info[CONF_SCS_ID] logger.info("Adding %s scsgate.cover", name) cover = SCSGateCover( name=name, scs_id=scs_id, logger=logger, scsgate=scsgate ) scsgate.add_device(cover) covers.append(cover) add_entities(covers)
[ "def", "setup_platform", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "add_entities", ":", "AddEntitiesCallback", ",", "discovery_info", ":", "DiscoveryInfoType", "|", "None", "=", "None", ",", ")", "->", "None", ":", "devices", "=...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/scsgate/cover.py#L27-L55
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/shutil.py
python
_get_uid
(name)
Returns an uid, given a user name.
Returns an uid, given a user name.
[ "Returns", "an", "uid", "given", "a", "user", "name", "." ]
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return else: try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "else", ":", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result...
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/shutil.py#L342-L354