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
hovel/pybbm
6cf297ea7cf23d52baba2a76a73c5fdddf19cf8e
pybb/permissions.py
python
DefaultPermissionHandler.filter_forums
(self, user, qs)
return qs.filter(Q(hidden=False) & Q(category__hidden=False))
return a queryset with forums `user` is allowed to see
return a queryset with forums `user` is allowed to see
[ "return", "a", "queryset", "with", "forums", "user", "is", "allowed", "to", "see" ]
def filter_forums(self, user, qs): """ return a queryset with forums `user` is allowed to see """ if user.is_superuser or user.is_staff: # FIXME: is_staff only allow user to access /admin but does not mean user has extra # permissions on pybb models. We should add pybb perm test return qs return qs.filter(Q(hidden=False) & Q(category__hidden=False))
[ "def", "filter_forums", "(", "self", ",", "user", ",", "qs", ")", ":", "if", "user", ".", "is_superuser", "or", "user", ".", "is_staff", ":", "# FIXME: is_staff only allow user to access /admin but does not mean user has extra", "# permissions on pybb models. We should add py...
https://github.com/hovel/pybbm/blob/6cf297ea7cf23d52baba2a76a73c5fdddf19cf8e/pybb/permissions.py#L47-L53
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/contrib/sitemaps/__init__.py
python
Sitemap.get_urls
(self, page=1, site=None, protocol=None)
return urls
[]
def get_urls(self, page=1, site=None, protocol=None): # Determine protocol if self.protocol is not None: protocol = self.protocol if protocol is None: protocol = 'http' # Determine domain if site is None: if django_apps.is_installed('django.contrib.sites'): Site = django_apps.get_model('sites.Site') try: site = Site.objects.get_current() except Site.DoesNotExist: pass if site is None: raise ImproperlyConfigured( "To use sitemaps, either enable the sites framework or pass " "a Site/RequestSite object in your view." ) domain = site.domain if getattr(self, 'i18n', False): urls = [] current_lang_code = translation.get_language() for lang_code, lang_name in settings.LANGUAGES: translation.activate(lang_code) urls += self._urls(page, protocol, domain) translation.activate(current_lang_code) else: urls = self._urls(page, protocol, domain) return urls
[ "def", "get_urls", "(", "self", ",", "page", "=", "1", ",", "site", "=", "None", ",", "protocol", "=", "None", ")", ":", "# Determine protocol", "if", "self", ".", "protocol", "is", "not", "None", ":", "protocol", "=", "self", ".", "protocol", "if", ...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/sitemaps/__init__.py#L80-L112
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/wx/table_editor.py
python
TableEditor._create_toolbar
(self, parent, sizer)
Creates the table editing toolbar.
Creates the table editing toolbar.
[ "Creates", "the", "table", "editing", "toolbar", "." ]
def _create_toolbar(self, parent, sizer): """Creates the table editing toolbar.""" factory = self.factory if not factory.show_toolbar: return toolbar = TableEditorToolbar(parent=parent, editor=self) if (toolbar.control is not None) or (len(factory.filters) > 0): tb_sizer = wx.BoxSizer(wx.HORIZONTAL) if len(factory.filters) > 0: view = View( [ Item( "filter<250>{View}", editor=factory._filter_editor ), "_", Item( "filter_summary<100>{Results}~", object="model", resizable=False, ), "_", "-", ], resizable=True, ) self.toolbar_ui = ui = view.ui( context={"object": self, "model": self.model}, parent=parent, kind="subpanel", ).trait_set(parent=self.ui) tb_sizer.Add(ui.control, 0) if toolbar.control is not None: self.toolbar = toolbar # add padding so the toolbar is right aligned tb_sizer.Add((1, 1), 1, wx.EXPAND) tb_sizer.Add(toolbar.control, 0) sizer.Add(tb_sizer, 0, wx.EXPAND)
[ "def", "_create_toolbar", "(", "self", ",", "parent", ",", "sizer", ")", ":", "factory", "=", "self", ".", "factory", "if", "not", "factory", ".", "show_toolbar", ":", "return", "toolbar", "=", "TableEditorToolbar", "(", "parent", "=", "parent", ",", "edit...
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/wx/table_editor.py#L406-L447
marian-margeta/gait-recognition
a9d1a738d4ca9c37355e0de4768a32c5f040d7fc
gait_nn.py
python
GaitNN.restore
(self, checkpoint_path)
[]
def restore(self, checkpoint_path): all_vars = tf.get_collection(tf.GraphKeys.MODEL_VARIABLES, scope = 'GaitNN') saver = tf.train.Saver(all_vars) saver.restore(self.sess, checkpoint_path)
[ "def", "restore", "(", "self", ",", "checkpoint_path", ")", ":", "all_vars", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "MODEL_VARIABLES", ",", "scope", "=", "'GaitNN'", ")", "saver", "=", "tf", ".", "train", ".", "Saver", "(", ...
https://github.com/marian-margeta/gait-recognition/blob/a9d1a738d4ca9c37355e0de4768a32c5f040d7fc/gait_nn.py#L171-L175
optuna/optuna
2c44c1a405ba059efd53f4b9c8e849d20fb95c0a
optuna/storages/_rdb/storage.py
python
RDBStorage.get_all_study_summaries
(self)
return study_summaries
[]
def get_all_study_summaries(self) -> List[StudySummary]: with _create_scoped_session(self.scoped_session) as session: summarized_trial = ( session.query( models.TrialModel.study_id, functions.min(models.TrialModel.datetime_start).label("datetime_start"), functions.count(models.TrialModel.trial_id).label("n_trial"), ) .group_by(models.TrialModel.study_id) .with_labels() .subquery() ) study_summary_stmt = session.query( models.StudyModel.study_id, models.StudyModel.study_name, summarized_trial.c.datetime_start, functions.coalesce(summarized_trial.c.n_trial, 0).label("n_trial"), ).select_from(orm.outerjoin(models.StudyModel, summarized_trial)) study_summary = study_summary_stmt.all() _directions = defaultdict(list) for d in session.query(models.StudyDirectionModel).all(): _directions[d.study_id].append(d.direction) _user_attrs = defaultdict(list) for a in session.query(models.StudyUserAttributeModel).all(): _user_attrs[d.study_id].append(a) _system_attrs = defaultdict(list) for a in session.query(models.StudySystemAttributeModel).all(): _system_attrs[d.study_id].append(a) study_summaries = [] for study in study_summary: directions = _directions[study.study_id] best_trial: Optional[models.TrialModel] = None try: if len(directions) > 1: raise ValueError elif directions[0] == StudyDirection.MAXIMIZE: best_trial = models.TrialModel.find_max_value_trial( study.study_id, 0, session ) else: best_trial = models.TrialModel.find_min_value_trial( study.study_id, 0, session ) except ValueError: best_trial_frozen: Optional[FrozenTrial] = None if best_trial: value = models.TrialValueModel.find_by_trial_and_objective( best_trial, 0, session ) assert value params = ( session.query( models.TrialParamModel.param_name, models.TrialParamModel.param_value, models.TrialParamModel.distribution_json, ) .filter(models.TrialParamModel.trial_id == best_trial.trial_id) .all() ) param_dict = {} param_distributions = {} for param in params: distribution = distributions.json_to_distribution(param.distribution_json) param_dict[param.param_name] = distribution.to_external_repr( param.param_value ) param_distributions[param.param_name] = distribution user_attrs = models.TrialUserAttributeModel.where_trial_id( best_trial.trial_id, session ) system_attrs = models.TrialSystemAttributeModel.where_trial_id( best_trial.trial_id, session ) intermediate = models.TrialIntermediateValueModel.where_trial_id( best_trial.trial_id, session ) best_trial_frozen = FrozenTrial( best_trial.number, TrialState.COMPLETE, value.value, best_trial.datetime_start, best_trial.datetime_complete, param_dict, param_distributions, {i.key: json.loads(i.value_json) for i in user_attrs}, {i.key: json.loads(i.value_json) for i in system_attrs}, {value.step: value.intermediate_value for value in intermediate}, best_trial.trial_id, ) user_attrs = _user_attrs.get(study.study_id, []) system_attrs = _system_attrs.get(study.study_id, []) study_summaries.append( StudySummary( study_name=study.study_name, direction=None, directions=directions, best_trial=best_trial_frozen, user_attrs={i.key: json.loads(i.value_json) for i in user_attrs}, system_attrs={i.key: json.loads(i.value_json) for i in system_attrs}, n_trials=study.n_trial, datetime_start=study.datetime_start, study_id=study.study_id, ) ) return study_summaries
[ "def", "get_all_study_summaries", "(", "self", ")", "->", "List", "[", "StudySummary", "]", ":", "with", "_create_scoped_session", "(", "self", ".", "scoped_session", ")", "as", "session", ":", "summarized_trial", "=", "(", "session", ".", "query", "(", "model...
https://github.com/optuna/optuna/blob/2c44c1a405ba059efd53f4b9c8e849d20fb95c0a/optuna/storages/_rdb/storage.py#L389-L500
mehdilauters/wifiScanMap
9adcd08e43db5dcb7700450abed00c97e140ef21
src/AirodumpPoller.py
python
AirodumpPoller.is_too_old
(self, date, sleep)
return diff.total_seconds() > sleep
[]
def is_too_old(self, date, sleep): diff = datetime.datetime.now() - self.date_from_str(date) return diff.total_seconds() > sleep
[ "def", "is_too_old", "(", "self", ",", "date", ",", "sleep", ")", ":", "diff", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "date_from_str", "(", "date", ")", "return", "diff", ".", "total_seconds", "(", ")", ">", "sleep"...
https://github.com/mehdilauters/wifiScanMap/blob/9adcd08e43db5dcb7700450abed00c97e140ef21/src/AirodumpPoller.py#L38-L40
dragonfly/dragonfly
a579b5eadf452e23b07d4caf27b402703b0012b7
dragonfly/exd/experiment_caller.py
python
EuclideanFunctionCaller.__init__
(self, func, *args, **kwargs)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, func, *args, **kwargs): """ Constructor. """ self.func = func super(EuclideanFunctionCaller, self).__init__(func, *args, **kwargs)
[ "def", "__init__", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "func", "=", "func", "super", "(", "EuclideanFunctionCaller", ",", "self", ")", ".", "__init__", "(", "func", ",", "*", "args", ",", "*",...
https://github.com/dragonfly/dragonfly/blob/a579b5eadf452e23b07d4caf27b402703b0012b7/dragonfly/exd/experiment_caller.py#L612-L615
gpiozero/gpiozero
2b6aa5314830fedf3701113b6713161086defa38
gpiozero/input_devices.py
python
InputDevice.pull_up
(self)
If :data:`True`, the device uses a pull-up resistor to set the GPIO pin "high" by default.
If :data:`True`, the device uses a pull-up resistor to set the GPIO pin "high" by default.
[ "If", ":", "data", ":", "True", "the", "device", "uses", "a", "pull", "-", "up", "resistor", "to", "set", "the", "GPIO", "pin", "high", "by", "default", "." ]
def pull_up(self): """ If :data:`True`, the device uses a pull-up resistor to set the GPIO pin "high" by default. """ pull = self.pin.pull if pull == 'floating': return None else: return pull == 'up'
[ "def", "pull_up", "(", "self", ")", ":", "pull", "=", "self", ".", "pin", ".", "pull", "if", "pull", "==", "'floating'", ":", "return", "None", "else", ":", "return", "pull", "==", "'up'" ]
https://github.com/gpiozero/gpiozero/blob/2b6aa5314830fedf3701113b6713161086defa38/gpiozero/input_devices.py#L98-L107
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/nn/models/tgn.py
python
TGNMemory.__init__
(self, num_nodes: int, raw_msg_dim: int, memory_dim: int, time_dim: int, message_module: Callable, aggregator_module: Callable)
[]
def __init__(self, num_nodes: int, raw_msg_dim: int, memory_dim: int, time_dim: int, message_module: Callable, aggregator_module: Callable): super().__init__() self.num_nodes = num_nodes self.raw_msg_dim = raw_msg_dim self.memory_dim = memory_dim self.time_dim = time_dim self.msg_s_module = message_module self.msg_d_module = copy.deepcopy(message_module) self.aggr_module = aggregator_module self.time_enc = TimeEncoder(time_dim) self.gru = GRUCell(message_module.out_channels, memory_dim) self.register_buffer('memory', torch.empty(num_nodes, memory_dim)) last_update = torch.empty(self.num_nodes, dtype=torch.long) self.register_buffer('last_update', last_update) self.register_buffer('__assoc__', torch.empty(num_nodes, dtype=torch.long)) self.msg_s_store = {} self.msg_d_store = {} self.reset_parameters()
[ "def", "__init__", "(", "self", ",", "num_nodes", ":", "int", ",", "raw_msg_dim", ":", "int", ",", "memory_dim", ":", "int", ",", "time_dim", ":", "int", ",", "message_module", ":", "Callable", ",", "aggregator_module", ":", "Callable", ")", ":", "super", ...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/nn/models/tgn.py#L35-L60
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
examples/dgcnn_segmentation.py
python
Net.forward
(self, data)
return F.log_softmax(out, dim=1)
[]
def forward(self, data): x, pos, batch = data.x, data.pos, data.batch x0 = torch.cat([x, pos], dim=-1) x1 = self.conv1(x0, batch) x2 = self.conv2(x1, batch) x3 = self.conv3(x2, batch) out = self.mlp(torch.cat([x1, x2, x3], dim=1)) return F.log_softmax(out, dim=1)
[ "def", "forward", "(", "self", ",", "data", ")", ":", "x", ",", "pos", ",", "batch", "=", "data", ".", "x", ",", "data", ".", "pos", ",", "data", ".", "batch", "x0", "=", "torch", ".", "cat", "(", "[", "x", ",", "pos", "]", ",", "dim", "=",...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/examples/dgcnn_segmentation.py#L41-L48
roclark/sportsipy
c19f545d3376d62ded6304b137dc69238ac620a9
sportsipy/mlb/teams.py
python
Team.last_ten_games_record
(self)
return self._last_ten_games_record
Returns a ``string`` of the team's record over the last ten games. Record is in the format 'W-L'.
Returns a ``string`` of the team's record over the last ten games. Record is in the format 'W-L'.
[ "Returns", "a", "string", "of", "the", "team", "s", "record", "over", "the", "last", "ten", "games", ".", "Record", "is", "in", "the", "format", "W", "-", "L", "." ]
def last_ten_games_record(self): """ Returns a ``string`` of the team's record over the last ten games. Record is in the format 'W-L'. """ return self._last_ten_games_record
[ "def", "last_ten_games_record", "(", "self", ")", ":", "return", "self", ".", "_last_ten_games_record" ]
https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/mlb/teams.py#L734-L739
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/exprs/Exprs.py
python
is_pure_expr
(expr)
return is_Expr(expr) and not expr_is_Instance(expr)
is expr an Expr (py class or py instance), but not an Instance?
is expr an Expr (py class or py instance), but not an Instance?
[ "is", "expr", "an", "Expr", "(", "py", "class", "or", "py", "instance", ")", "but", "not", "an", "Instance?" ]
def is_pure_expr(expr): ##e why not is_pure_Expr? is lowercase expr a generic term of some sort? [070207 terminology Q] """ is expr an Expr (py class or py instance), but not an Instance? """ return is_Expr(expr) and not expr_is_Instance(expr)
[ "def", "is_pure_expr", "(", "expr", ")", ":", "##e why not is_pure_Expr? is lowercase expr a generic term of some sort? [070207 terminology Q]", "return", "is_Expr", "(", "expr", ")", "and", "not", "expr_is_Instance", "(", "expr", ")" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/exprs/Exprs.py#L99-L103
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/addrspaces/amd64.py
python
AMD64PagedMemory.get_pdpi
(self, vaddr, pml4e)
return self.read_long_long_phys(pdpte_paddr)
This method returns the Page Directory Pointer entry for the virtual address. Bits 32:30 are used to select the appropriate 8 byte entry in the Page Directory Pointer table. "Bits 51:12 are from the PML4E" [Intel] "Bits 11:3 are bits 38:30 of the linear address" [Intel] "Bits 2:0 are all 0" [Intel]
This method returns the Page Directory Pointer entry for the virtual address. Bits 32:30 are used to select the appropriate 8 byte entry in the Page Directory Pointer table. "Bits 51:12 are from the PML4E" [Intel] "Bits 11:3 are bits 38:30 of the linear address" [Intel] "Bits 2:0 are all 0" [Intel]
[ "This", "method", "returns", "the", "Page", "Directory", "Pointer", "entry", "for", "the", "virtual", "address", ".", "Bits", "32", ":", "30", "are", "used", "to", "select", "the", "appropriate", "8", "byte", "entry", "in", "the", "Page", "Directory", "Poi...
def get_pdpi(self, vaddr, pml4e): ''' This method returns the Page Directory Pointer entry for the virtual address. Bits 32:30 are used to select the appropriate 8 byte entry in the Page Directory Pointer table. "Bits 51:12 are from the PML4E" [Intel] "Bits 11:3 are bits 38:30 of the linear address" [Intel] "Bits 2:0 are all 0" [Intel] ''' pdpte_paddr = (pml4e & 0xffffffffff000) | ((vaddr & 0x7FC0000000) >> 27) return self.read_long_long_phys(pdpte_paddr)
[ "def", "get_pdpi", "(", "self", ",", "vaddr", ",", "pml4e", ")", ":", "pdpte_paddr", "=", "(", "pml4e", "&", "0xffffffffff000", ")", "|", "(", "(", "vaddr", "&", "0x7FC0000000", ")", ">>", "27", ")", "return", "self", ".", "read_long_long_phys", "(", "...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/addrspaces/amd64.py#L119-L130
aaronjanse/asciidots
9c6a7d6a68c5e7870d574ab8ae94aa9ad7f53012
dots/__main__.py
python
DefaultIOCallbacks.get_input
(self, ascii_char=False)
Get an input from the user.
Get an input from the user.
[ "Get", "an", "input", "from", "the", "user", "." ]
def get_input(self, ascii_char=False): """Get an input from the user.""" if not self.debug or self.compat_debug: if ascii_char: return getch() else: if not sys.stdin.isatty(): return input('') else: return input('?: ') else: return self.curses_input(self.stdscr, curses.LINES - 3, 2, '?: ', ascii_char)
[ "def", "get_input", "(", "self", ",", "ascii_char", "=", "False", ")", ":", "if", "not", "self", ".", "debug", "or", "self", ".", "compat_debug", ":", "if", "ascii_char", ":", "return", "getch", "(", ")", "else", ":", "if", "not", "sys", ".", "stdin"...
https://github.com/aaronjanse/asciidots/blob/9c6a7d6a68c5e7870d574ab8ae94aa9ad7f53012/dots/__main__.py#L114-L125
svenkreiss/pysparkling
f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78
pysparkling/sql/types.py
python
MapType.__init__
(self, keyType, valueType, valueContainsNull=True)
>>> (MapType(StringType(), IntegerType()) ... == MapType(StringType(), IntegerType(), True)) True >>> (MapType(StringType(), IntegerType(), False) ... == MapType(StringType(), FloatType())) False
>>> (MapType(StringType(), IntegerType()) ... == MapType(StringType(), IntegerType(), True)) True >>> (MapType(StringType(), IntegerType(), False) ... == MapType(StringType(), FloatType())) False
[ ">>>", "(", "MapType", "(", "StringType", "()", "IntegerType", "()", ")", "...", "==", "MapType", "(", "StringType", "()", "IntegerType", "()", "True", "))", "True", ">>>", "(", "MapType", "(", "StringType", "()", "IntegerType", "()", "False", ")", "...", ...
def __init__(self, keyType, valueType, valueContainsNull=True): """ >>> (MapType(StringType(), IntegerType()) ... == MapType(StringType(), IntegerType(), True)) True >>> (MapType(StringType(), IntegerType(), False) ... == MapType(StringType(), FloatType())) False """ assert isinstance(keyType, DataType), \ "keyType %s should be an instance of %s" % (keyType, DataType) assert isinstance(valueType, DataType), \ "valueType %s should be an instance of %s" % (valueType, DataType) self.keyType = keyType self.valueType = valueType self.valueContainsNull = valueContainsNull
[ "def", "__init__", "(", "self", ",", "keyType", ",", "valueType", ",", "valueContainsNull", "=", "True", ")", ":", "assert", "isinstance", "(", "keyType", ",", "DataType", ")", ",", "\"keyType %s should be an instance of %s\"", "%", "(", "keyType", ",", "DataTyp...
https://github.com/svenkreiss/pysparkling/blob/f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78/pysparkling/sql/types.py#L325-L340
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
weioLib/weioUserApi.py
python
WeioSharedVar.__init__
(self, procFnc, procArgs)
[]
def __init__ (self, procFnc, procArgs) : self.dict = None self.Val = None self.Array = None
[ "def", "__init__", "(", "self", ",", "procFnc", ",", "procArgs", ")", ":", "self", ".", "dict", "=", "None", "self", ".", "Val", "=", "None", "self", ".", "Array", "=", "None" ]
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/weioLib/weioUserApi.py#L102-L105
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/tuner.py
python
HyperparameterTuner._get_best_training_job
(self)
Return the best training job for the latest hyperparameter tuning job. Raises: Exception: If there is no best training job available for the hyperparameter tuning job.
Return the best training job for the latest hyperparameter tuning job.
[ "Return", "the", "best", "training", "job", "for", "the", "latest", "hyperparameter", "tuning", "job", "." ]
def _get_best_training_job(self): """Return the best training job for the latest hyperparameter tuning job. Raises: Exception: If there is no best training job available for the hyperparameter tuning job. """ self._ensure_last_tuning_job() tuning_job_describe_result = self.sagemaker_session.sagemaker_client.describe_hyper_parameter_tuning_job( # noqa: E501 # pylint: disable=line-too-long HyperParameterTuningJobName=self.latest_tuning_job.name ) try: return tuning_job_describe_result["BestTrainingJob"] except KeyError: raise Exception( "Best training job not available for tuning job: {}".format( self.latest_tuning_job.name ) )
[ "def", "_get_best_training_job", "(", "self", ")", ":", "self", ".", "_ensure_last_tuning_job", "(", ")", "tuning_job_describe_result", "=", "self", ".", "sagemaker_session", ".", "sagemaker_client", ".", "describe_hyper_parameter_tuning_job", "(", "# noqa: E501 # pylint: d...
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/tuner.py#L859-L879
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/types/fixed.py
python
_FixedGreaterThan.__init__
(self, left, right)
[]
def __init__(self, left, right): left, right = self.init(left, right) vtypes.GreaterThan.__init__(self, left, right)
[ "def", "__init__", "(", "self", ",", "left", ",", "right", ")", ":", "left", ",", "right", "=", "self", ".", "init", "(", "left", ",", "right", ")", "vtypes", ".", "GreaterThan", ".", "__init__", "(", "self", ",", "left", ",", "right", ")" ]
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/types/fixed.py#L599-L601
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/venv/lib/python2.7/site-packages/pip/index.py
python
Link.is_artifact
(self)
return True
Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location.
Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location.
[ "Determines", "if", "this", "points", "to", "an", "actual", "artifact", "(", "e", ".", "g", ".", "a", "tarball", ")", "or", "if", "it", "points", "to", "an", "abstract", "thing", "like", "a", "path", "or", "a", "VCS", "location", "." ]
def is_artifact(self): """ Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. """ from pip.vcs import vcs if self.scheme in vcs.all_schemes: return False return True
[ "def", "is_artifact", "(", "self", ")", ":", "from", "pip", ".", "vcs", "import", "vcs", "if", "self", ".", "scheme", "in", "vcs", ".", "all_schemes", ":", "return", "False", "return", "True" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/pip/index.py#L1027-L1037
Blazemeter/taurus
6e36b20397cf3e730e181cfebde0c8f19eb31fed
bzt/utils.py
python
get_host_ips
(filter_loopbacks=True)
return ips
Returns a list of all IP addresses assigned to this host. :param filter_loopbacks: filter out loopback addresses
Returns a list of all IP addresses assigned to this host.
[ "Returns", "a", "list", "of", "all", "IP", "addresses", "assigned", "to", "this", "host", "." ]
def get_host_ips(filter_loopbacks=True): """ Returns a list of all IP addresses assigned to this host. :param filter_loopbacks: filter out loopback addresses """ ips = [] for _, interfaces in iteritems(psutil.net_if_addrs()): for iface in interfaces: addr = str(iface.address) try: ip = ipaddress.ip_address(addr) if filter_loopbacks and ip.is_loopback: continue except ValueError: continue ips.append(iface.address) return ips
[ "def", "get_host_ips", "(", "filter_loopbacks", "=", "True", ")", ":", "ips", "=", "[", "]", "for", "_", ",", "interfaces", "in", "iteritems", "(", "psutil", ".", "net_if_addrs", "(", ")", ")", ":", "for", "iface", "in", "interfaces", ":", "addr", "=",...
https://github.com/Blazemeter/taurus/blob/6e36b20397cf3e730e181cfebde0c8f19eb31fed/bzt/utils.py#L1747-L1764
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/xml/dom/expatbuilder.py
python
ExpatBuilder.createParser
(self)
return expat.ParserCreate()
Create a new parser object.
Create a new parser object.
[ "Create", "a", "new", "parser", "object", "." ]
def createParser(self): """Create a new parser object.""" return expat.ParserCreate()
[ "def", "createParser", "(", "self", ")", ":", "return", "expat", ".", "ParserCreate", "(", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xml/dom/expatbuilder.py#L151-L153
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/site-packages/win32/lib/win32timezone.py
python
resolveMUITimeZone
(spec)
return result
Resolve a multilingual user interface resource for the time zone name >>> #some pre-amble for the doc-tests to be py2k and py3k aware) >>> try: unicode and None ... except NameError: unicode=str ... >>> result = resolveMUITimeZone('@tzres.dll,-110') >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)] >>> type(result) is expectedResultType True spec should be of the format @path,-stringID[;comment] see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
Resolve a multilingual user interface resource for the time zone name >>> #some pre-amble for the doc-tests to be py2k and py3k aware) >>> try: unicode and None ... except NameError: unicode=str ... >>> result = resolveMUITimeZone('
[ "Resolve", "a", "multilingual", "user", "interface", "resource", "for", "the", "time", "zone", "name", ">>>", "#some", "pre", "-", "amble", "for", "the", "doc", "-", "tests", "to", "be", "py2k", "and", "py3k", "aware", ")", ">>>", "try", ":", "unicode", ...
def resolveMUITimeZone(spec): """Resolve a multilingual user interface resource for the time zone name >>> #some pre-amble for the doc-tests to be py2k and py3k aware) >>> try: unicode and None ... except NameError: unicode=str ... >>> result = resolveMUITimeZone('@tzres.dll,-110') >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)] >>> type(result) is expectedResultType True spec should be of the format @path,-stringID[;comment] see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details """ pattern = re.compile('@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?') matcher = pattern.match(spec) assert matcher, 'Could not parse MUI spec' try: handle = DLLCache[matcher.groupdict()['dllname']] result = win32api.LoadString(handle, int(matcher.groupdict()['index'])) except win32api.error, e: result = None return result
[ "def", "resolveMUITimeZone", "(", "spec", ")", ":", "pattern", "=", "re", ".", "compile", "(", "'@(?P<dllname>.*),-(?P<index>\\d+)(?:;(?P<comment>.*))?'", ")", "matcher", "=", "pattern", ".", "match", "(", "spec", ")", "assert", "matcher", ",", "'Could not parse MUI...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/site-packages/win32/lib/win32timezone.py#L706-L729
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/fileserver/roots.py
python
find_file
(path, saltenv="base", **kwargs)
return fnd
Search the environment for the relative path.
Search the environment for the relative path.
[ "Search", "the", "environment", "for", "the", "relative", "path", "." ]
def find_file(path, saltenv="base", **kwargs): """ Search the environment for the relative path. """ if "env" in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop("env") path = os.path.normpath(path) fnd = {"path": "", "rel": ""} if os.path.isabs(path): return fnd if saltenv not in __opts__["file_roots"]: if "__env__" in __opts__["file_roots"]: log.debug( "salt environment '%s' maps to __env__ file_roots directory", saltenv ) saltenv = "__env__" else: return fnd def _add_file_stat(fnd): """ Stat the file and, assuming no errors were found, convert the stat result to a list of values and add to the return dict. Converting the stat result to a list, the elements of the list correspond to the following stat_result params: 0 => st_mode=33188 1 => st_ino=10227377 2 => st_dev=65026 3 => st_nlink=1 4 => st_uid=1000 5 => st_gid=1000 6 => st_size=1056233 7 => st_atime=1468284229 8 => st_mtime=1456338235 9 => st_ctime=1456338235 """ try: fnd["stat"] = list(os.stat(fnd["path"])) except Exception as exc: # pylint: disable=broad-except log.error("Unable to stat file: %s", exc) return fnd if "index" in kwargs: try: root = __opts__["file_roots"][saltenv][int(kwargs["index"])] except IndexError: # An invalid index was passed return fnd except ValueError: # An invalid index option was passed return fnd full = os.path.join(root, path) if os.path.isfile(full) and not salt.fileserver.is_file_ignored(__opts__, full): fnd["path"] = full fnd["rel"] = path return _add_file_stat(fnd) return fnd for root in __opts__["file_roots"][saltenv]: full = os.path.join(root, path) if os.path.isfile(full) and not salt.fileserver.is_file_ignored(__opts__, full): fnd["path"] = full fnd["rel"] = path return _add_file_stat(fnd) return fnd
[ "def", "find_file", "(", "path", ",", "saltenv", "=", "\"base\"", ",", "*", "*", "kwargs", ")", ":", "if", "\"env\"", "in", "kwargs", ":", "# \"env\" is not supported; Use \"saltenv\".", "kwargs", ".", "pop", "(", "\"env\"", ")", "path", "=", "os", ".", "p...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/fileserver/roots.py#L35-L102
pculture/mirovideoconverter3
27efad91845c8ae544dc27034adb0d3e18ca8f1f
mvc/widgets/gtk/tableview.py
python
TableView.get_path
(self, iter_)
return self._model.get_path(iter_)
Always use this rather than the model's get_path directly - if the iter isn't valid, a GTK assertion causes us to exit without warning; this wrapper changes that to a much more useful AssertionError. Example related bug: #17362.
Always use this rather than the model's get_path directly - if the iter isn't valid, a GTK assertion causes us to exit without warning; this wrapper changes that to a much more useful AssertionError. Example related bug: #17362.
[ "Always", "use", "this", "rather", "than", "the", "model", "s", "get_path", "directly", "-", "if", "the", "iter", "isn", "t", "valid", "a", "GTK", "assertion", "causes", "us", "to", "exit", "without", "warning", ";", "this", "wrapper", "changes", "that", ...
def get_path(self, iter_): """Always use this rather than the model's get_path directly - if the iter isn't valid, a GTK assertion causes us to exit without warning; this wrapper changes that to a much more useful AssertionError. Example related bug: #17362. """ assert self.model.iter_is_valid(iter_) return self._model.get_path(iter_)
[ "def", "get_path", "(", "self", ",", "iter_", ")", ":", "assert", "self", ".", "model", ".", "iter_is_valid", "(", "iter_", ")", "return", "self", ".", "_model", ".", "get_path", "(", "iter_", ")" ]
https://github.com/pculture/mirovideoconverter3/blob/27efad91845c8ae544dc27034adb0d3e18ca8f1f/mvc/widgets/gtk/tableview.py#L1409-L1416
chrippa/python-librtmp
6efefd5edd76cad7a3b53f7c87c1c7350448224d
librtmp/packet.py
python
RTMPPacket.timestamp
(self)
return self.packet.m_nTimeStamp
Timestamp of the packet.
Timestamp of the packet.
[ "Timestamp", "of", "the", "packet", "." ]
def timestamp(self): """Timestamp of the packet.""" return self.packet.m_nTimeStamp
[ "def", "timestamp", "(", "self", ")", ":", "return", "self", ".", "packet", ".", "m_nTimeStamp" ]
https://github.com/chrippa/python-librtmp/blob/6efefd5edd76cad7a3b53f7c87c1c7350448224d/librtmp/packet.py#L85-L87
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
examples/pytorch/pointcloud/pointnet/pointnet2.py
python
FixedRadiusNearNeighbors.forward
(self, pos, centroids)
return group_idx
Adapted from https://github.com/yanx27/Pointnet_Pointnet2_pytorch
Adapted from https://github.com/yanx27/Pointnet_Pointnet2_pytorch
[ "Adapted", "from", "https", ":", "//", "github", ".", "com", "/", "yanx27", "/", "Pointnet_Pointnet2_pytorch" ]
def forward(self, pos, centroids): ''' Adapted from https://github.com/yanx27/Pointnet_Pointnet2_pytorch ''' device = pos.device B, N, _ = pos.shape center_pos = index_points(pos, centroids) _, S, _ = center_pos.shape group_idx = torch.arange(N, dtype=torch.long).to(device).view(1, 1, N).repeat([B, S, 1]) sqrdists = square_distance(center_pos, pos) group_idx[sqrdists > self.radius ** 2] = N group_idx = group_idx.sort(dim=-1)[0][:, :, :self.n_neighbor] group_first = group_idx[:, :, 0].view(B, S, 1).repeat([1, 1, self.n_neighbor]) mask = group_idx == N group_idx[mask] = group_first[mask] return group_idx
[ "def", "forward", "(", "self", ",", "pos", ",", "centroids", ")", ":", "device", "=", "pos", ".", "device", "B", ",", "N", ",", "_", "=", "pos", ".", "shape", "center_pos", "=", "index_points", "(", "pos", ",", "centroids", ")", "_", ",", "S", ",...
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/pointcloud/pointnet/pointnet2.py#L49-L64
giswqs/whitebox-python
b4df0bbb10a1dee3bd0f6b3482511f7c829b38fe
whitebox/whitebox_tools.py
python
WhiteboxTools.difference
(self, i, overlay, output, callback=None)
return self.run_tool('difference', args, callback)
Outputs the features that occur in one of the two vector inputs but not both, i.e. no overlapping features. Keyword arguments: i -- Input vector file. overlay -- Input overlay vector file. output -- Output vector file. callback -- Custom function for handling tool text outputs.
Outputs the features that occur in one of the two vector inputs but not both, i.e. no overlapping features.
[ "Outputs", "the", "features", "that", "occur", "in", "one", "of", "the", "two", "vector", "inputs", "but", "not", "both", "i", ".", "e", ".", "no", "overlapping", "features", "." ]
def difference(self, i, overlay, output, callback=None): """Outputs the features that occur in one of the two vector inputs but not both, i.e. no overlapping features. Keyword arguments: i -- Input vector file. overlay -- Input overlay vector file. output -- Output vector file. callback -- Custom function for handling tool text outputs. """ args = [] args.append("--input='{}'".format(i)) args.append("--overlay='{}'".format(overlay)) args.append("--output='{}'".format(output)) return self.run_tool('difference', args, callback)
[ "def", "difference", "(", "self", ",", "i", ",", "overlay", ",", "output", ",", "callback", "=", "None", ")", ":", "args", "=", "[", "]", "args", ".", "append", "(", "\"--input='{}'\"", ".", "format", "(", "i", ")", ")", "args", ".", "append", "(",...
https://github.com/giswqs/whitebox-python/blob/b4df0bbb10a1dee3bd0f6b3482511f7c829b38fe/whitebox/whitebox_tools.py#L1955-L1969
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbZhiHuiYuanQu.alibaba_campus_acl_updategrantroletouser
( self, company_id, system_id, campus_id, account_id, role, user_id='' )
return self._top_request( "alibaba.campus.acl.updategrantroletouser", { "company_id": company_id, "system_id": system_id, "campus_id": campus_id, "account_id": account_id, "role": role, "user_id": user_id } )
修改用户到角色关系 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=32231 :param company_id: 公司id :param system_id: 系统id :param campus_id: 园区id :param account_id: 用户账号 :param role: 角色 :param user_id: 操作人id(不填默认appCode)
修改用户到角色关系 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=32231
[ "修改用户到角色关系", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "32231" ]
def alibaba_campus_acl_updategrantroletouser( self, company_id, system_id, campus_id, account_id, role, user_id='' ): """ 修改用户到角色关系 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=32231 :param company_id: 公司id :param system_id: 系统id :param campus_id: 园区id :param account_id: 用户账号 :param role: 角色 :param user_id: 操作人id(不填默认appCode) """ return self._top_request( "alibaba.campus.acl.updategrantroletouser", { "company_id": company_id, "system_id": system_id, "campus_id": campus_id, "account_id": account_id, "role": role, "user_id": user_id } )
[ "def", "alibaba_campus_acl_updategrantroletouser", "(", "self", ",", "company_id", ",", "system_id", ",", "campus_id", ",", "account_id", ",", "role", ",", "user_id", "=", "''", ")", ":", "return", "self", ".", "_top_request", "(", "\"alibaba.campus.acl.updategrantr...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L94199-L94229
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/utils.py
python
ConnectionHandler.__setitem__
(self, key, value)
[]
def __setitem__(self, key, value): setattr(self._connections, key, value)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "setattr", "(", "self", ".", "_connections", ",", "key", ",", "value", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/utils.py#L216-L217
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /scripts/sshbackdoors/rpyc/experimental/splitbrain.py
python
RoutedModule.__init__
(self, realmod)
[]
def __init__(self, realmod): ModuleType.__init__(self, realmod.__name__, getattr(realmod, "__doc__", None)) object.__setattr__(self, "__realmod__", realmod) object.__setattr__(self, "__file__", getattr(realmod, "__file__", None))
[ "def", "__init__", "(", "self", ",", "realmod", ")", ":", "ModuleType", ".", "__init__", "(", "self", ",", "realmod", ".", "__name__", ",", "getattr", "(", "realmod", ",", "\"__doc__\"", ",", "None", ")", ")", "object", ".", "__setattr__", "(", "self", ...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /scripts/sshbackdoors/rpyc/experimental/splitbrain.py#L28-L31
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
scripts/monitoring/cron-send-create-app.py
python
getPod
(name)
return result
get Pod from all possible pods
get Pod from all possible pods
[ "get", "Pod", "from", "all", "possible", "pods" ]
def getPod(name): """ get Pod from all possible pods """ pods = ocutil.get_pods() result = None for pod in pods['items']: if pod and pod['metadata']['name'] and pod['metadata']['name'].startswith(name): # if we have a pod already, and this one is a build or deploy pod, don't worry about it # we want podname-xyz12 to be priority # if we dont already have a pod, then this one will do if result: if pod['metadata']['name'].endswith("build"): continue if pod['metadata']['name'].endswith("deploy"): continue result = pod return result
[ "def", "getPod", "(", "name", ")", ":", "pods", "=", "ocutil", ".", "get_pods", "(", ")", "result", "=", "None", "for", "pod", "in", "pods", "[", "'items'", "]", ":", "if", "pod", "and", "pod", "[", "'metadata'", "]", "[", "'name'", "]", "and", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/scripts/monitoring/cron-send-create-app.py#L152-L171
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/encodings/mac_greek.py
python
getregentry
()
return codecs.CodecInfo( name='mac-greek', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
[]
def getregentry(): return codecs.CodecInfo( name='mac-greek', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
[ "def", "getregentry", "(", ")", ":", "return", "codecs", ".", "CodecInfo", "(", "name", "=", "'mac-greek'", ",", "encode", "=", "Codec", "(", ")", ".", "encode", ",", "decode", "=", "Codec", "(", ")", ".", "decode", ",", "incrementalencoder", "=", "Inc...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/encodings/mac_greek.py#L33-L42
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/db/models/query.py
python
QuerySet.db
(self)
return self._db or router.db_for_read(self.model)
Return the database that will be used if this query is executed now
Return the database that will be used if this query is executed now
[ "Return", "the", "database", "that", "will", "be", "used", "if", "this", "query", "is", "executed", "now" ]
def db(self): "Return the database that will be used if this query is executed now" if self._for_write: return self._db or router.db_for_write(self.model) return self._db or router.db_for_read(self.model)
[ "def", "db", "(", "self", ")", ":", "if", "self", ".", "_for_write", ":", "return", "self", ".", "_db", "or", "router", ".", "db_for_write", "(", "self", ".", "model", ")", "return", "self", ".", "_db", "or", "router", ".", "db_for_read", "(", "self"...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/db/models/query.py#L892-L896
sopel-irc/sopel
787baa6e39f9dad57d94600c92e10761c41b21ef
sopel/modules/wikipedia.py
python
wpclang
(bot, trigger)
[]
def wpclang(bot, trigger): if not (trigger.admin or bot.channels[trigger.sender.lower()].privileges[trigger.nick.lower()] >= plugin.OP): bot.reply("You don't have permission to change this channel's Wikipedia language setting.") return plugin.NOLIMIT if not trigger.group(3): bot.say( "{}'s current Wikipedia language is: {}" .format( trigger.sender, bot.db.get_nick_value( trigger.nick, 'wikipedia_lang', bot.config.wikipedia.default_lang) ) ) return bot.db.set_channel_value(trigger.sender, 'wikipedia_lang', trigger.group(3)) bot.say( "Set {}'s Wikipedia language to: {}" .format(trigger.sender, trigger.group(3)) )
[ "def", "wpclang", "(", "bot", ",", "trigger", ")", ":", "if", "not", "(", "trigger", ".", "admin", "or", "bot", ".", "channels", "[", "trigger", ".", "sender", ".", "lower", "(", ")", "]", ".", "privileges", "[", "trigger", ".", "nick", ".", "lower...
https://github.com/sopel-irc/sopel/blob/787baa6e39f9dad57d94600c92e10761c41b21ef/sopel/modules/wikipedia.py#L337-L358
Project-Platypus/Platypus
a4e56410a772798e905407e99f80d03b86296ad3
examples/plot_operators.py
python
generate
(variator, parents)
return to_points(result)
[]
def generate(variator, parents): result = [] while len(result) < 10000: result.extend(variator.evolve(parents)) return to_points(result)
[ "def", "generate", "(", "variator", ",", "parents", ")", ":", "result", "=", "[", "]", "while", "len", "(", "result", ")", "<", "10000", ":", "result", ".", "extend", "(", "variator", ".", "evolve", "(", "parents", ")", ")", "return", "to_points", "(...
https://github.com/Project-Platypus/Platypus/blob/a4e56410a772798e905407e99f80d03b86296ad3/examples/plot_operators.py#L17-L23
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/stats/_continuous_distns.py
python
crystalball_gen._munp
(self, n, beta, m)
return N * _lazywhere(n + 1 < m, (n, beta, m), np.vectorize(n_th_moment, otypes=[np.float64]), np.inf)
Returns the n-th non-central moment of the crystalball function.
Returns the n-th non-central moment of the crystalball function.
[ "Returns", "the", "n", "-", "th", "non", "-", "central", "moment", "of", "the", "crystalball", "function", "." ]
def _munp(self, n, beta, m): """ Returns the n-th non-central moment of the crystalball function. """ N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + _norm_pdf_C * _norm_cdf(beta)) def n_th_moment(n, beta, m): """ Returns n-th moment. Defined only if n+1 < m Function cannot broadcast due to the loop over n """ A = (m/beta)**m * np.exp(-beta**2 / 2.0) B = m/beta - beta rhs = (2**((n-1)/2.0) * sc.gamma((n+1)/2) * (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2))) lhs = np.zeros(rhs.shape) for k in range(n + 1): lhs += (sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) * (m/beta)**(-m + k + 1)) return A * lhs + rhs return N * _lazywhere(n + 1 < m, (n, beta, m), np.vectorize(n_th_moment, otypes=[np.float64]), np.inf)
[ "def", "_munp", "(", "self", ",", "n", ",", "beta", ",", "m", ")", ":", "N", "=", "1.0", "/", "(", "m", "/", "beta", "/", "(", "m", "-", "1", ")", "*", "np", ".", "exp", "(", "-", "beta", "**", "2", "/", "2.0", ")", "+", "_norm_pdf_C", ...
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/stats/_continuous_distns.py#L8609-L8633
Yelp/kafka-utils
74831206648512db1a29426c6ebb428b33820d04
kafka_utils/util/config.py
python
iter_configurations
(kafka_topology_base_path=None)
Cluster topology iterator. Iterate over all the topologies available in config.
Cluster topology iterator. Iterate over all the topologies available in config.
[ "Cluster", "topology", "iterator", ".", "Iterate", "over", "all", "the", "topologies", "available", "in", "config", "." ]
def iter_configurations(kafka_topology_base_path=None): """Cluster topology iterator. Iterate over all the topologies available in config. """ if not kafka_topology_base_path: config_dirs = get_conf_dirs() else: config_dirs = [kafka_topology_base_path] types = set() for config_dir in config_dirs: new_types = [x for x in map( lambda x: os.path.basename(x)[:-5], glob.glob('{0}/*.yaml'.format(config_dir)), ) if x not in types] for cluster_type in new_types: try: topology = TopologyConfiguration( cluster_type, config_dir, ) except ConfigurationError: continue types.add(cluster_type) yield topology
[ "def", "iter_configurations", "(", "kafka_topology_base_path", "=", "None", ")", ":", "if", "not", "kafka_topology_base_path", ":", "config_dirs", "=", "get_conf_dirs", "(", ")", "else", ":", "config_dirs", "=", "[", "kafka_topology_base_path", "]", "types", "=", ...
https://github.com/Yelp/kafka-utils/blob/74831206648512db1a29426c6ebb428b33820d04/kafka_utils/util/config.py#L255-L279
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/sysconfig.py
python
_init_non_posix
(vars)
Initialize the module as appropriate for NT
Initialize the module as appropriate for NT
[ "Initialize", "the", "module", "as", "appropriate", "for", "NT" ]
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories import _imp vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['EXT_SUFFIX'] = _imp.extension_suffixes()[0] vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable)) vars['TZPATH'] = ''
[ "def", "_init_non_posix", "(", "vars", ")", ":", "# set basic install directories", "import", "_imp", "vars", "[", "'LIBDEST'", "]", "=", "get_path", "(", "'stdlib'", ")", "vars", "[", "'BINLIBDEST'", "]", "=", "get_path", "(", "'platstdlib'", ")", "vars", "["...
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/sysconfig.py#L481-L492
wanggrun/Adaptively-Connected-Neural-Networks
e27066ef52301bdafa5932f43af8feeb23647edb
tensorpack-installed/tensorpack/dataflow/raw.py
python
DataFromList.__init__
(self, lst, shuffle=True)
Args: lst (list): input list. Each element is a datapoint. shuffle (bool): shuffle data.
Args: lst (list): input list. Each element is a datapoint. shuffle (bool): shuffle data.
[ "Args", ":", "lst", "(", "list", ")", ":", "input", "list", ".", "Each", "element", "is", "a", "datapoint", ".", "shuffle", "(", "bool", ")", ":", "shuffle", "data", "." ]
def __init__(self, lst, shuffle=True): """ Args: lst (list): input list. Each element is a datapoint. shuffle (bool): shuffle data. """ super(DataFromList, self).__init__() self.lst = lst self.shuffle = shuffle
[ "def", "__init__", "(", "self", ",", "lst", ",", "shuffle", "=", "True", ")", ":", "super", "(", "DataFromList", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "lst", "=", "lst", "self", ".", "shuffle", "=", "shuffle" ]
https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/tensorpack/dataflow/raw.py#L75-L83
stanislavkozlovski/Red-Black-Tree
cb3cefb420bfa6c1d1fc703cefad54e209c7438c
rb_tree.py
python
RedBlackTree._remove
(self, node)
Receives a node with 0 or 1 children (typically some sort of successor) and removes it according to its color/children :param node: Node with 0 or 1 children
Receives a node with 0 or 1 children (typically some sort of successor) and removes it according to its color/children :param node: Node with 0 or 1 children
[ "Receives", "a", "node", "with", "0", "or", "1", "children", "(", "typically", "some", "sort", "of", "successor", ")", "and", "removes", "it", "according", "to", "its", "color", "/", "children", ":", "param", "node", ":", "Node", "with", "0", "or", "1"...
def _remove(self, node): """ Receives a node with 0 or 1 children (typically some sort of successor) and removes it according to its color/children :param node: Node with 0 or 1 children """ left_child = node.left right_child = node.right not_nil_child = left_child if left_child != self.NIL_LEAF else right_child if node == self.root: if not_nil_child != self.NIL_LEAF: # if we're removing the root and it has one valid child, simply make that child the root self.root = not_nil_child self.root.parent = None self.root.color = BLACK else: self.root = None elif node.color == RED: if not node.has_children(): # Red node with no children, the simplest remove self._remove_leaf(node) else: """ Since the node is red he cannot have a child. If he had a child, it'd need to be black, but that would mean that the black height would be bigger on the one side and that would make our tree invalid """ raise Exception('Unexpected behavior') else: # node is black! if right_child.has_children() or left_child.has_children(): # sanity check raise Exception('The red child of a black node with 0 or 1 children' ' cannot have children, otherwise the black height of the tree becomes invalid! ') if not_nil_child.color == RED: """ Swap the values with the red child and remove it (basically un-link it) Since we're a node with one child only, we can be sure that there are no nodes below the red child. """ node.value = not_nil_child.value node.left = not_nil_child.left node.right = not_nil_child.right else: # BLACK child # 6 cases :o self._remove_black_node(node)
[ "def", "_remove", "(", "self", ",", "node", ")", ":", "left_child", "=", "node", ".", "left", "right_child", "=", "node", ".", "right", "not_nil_child", "=", "left_child", "if", "left_child", "!=", "self", ".", "NIL_LEAF", "else", "right_child", "if", "nod...
https://github.com/stanislavkozlovski/Red-Black-Tree/blob/cb3cefb420bfa6c1d1fc703cefad54e209c7438c/rb_tree.py#L162-L204
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/s3/bucket.py
python
Bucket.set_as_logging_target
(self, headers=None)
Setup the current bucket as a logging target by granting the necessary permissions to the LogDelivery group to write log files to this bucket.
Setup the current bucket as a logging target by granting the necessary permissions to the LogDelivery group to write log files to this bucket.
[ "Setup", "the", "current", "bucket", "as", "a", "logging", "target", "by", "granting", "the", "necessary", "permissions", "to", "the", "LogDelivery", "group", "to", "write", "log", "files", "to", "this", "bucket", "." ]
def set_as_logging_target(self, headers=None): """ Setup the current bucket as a logging target by granting the necessary permissions to the LogDelivery group to write log files to this bucket. """ policy = self.get_acl(headers=headers) g1 = Grant(permission='WRITE', type='Group', uri=self.LoggingGroup) g2 = Grant(permission='READ_ACP', type='Group', uri=self.LoggingGroup) policy.acl.add_grant(g1) policy.acl.add_grant(g2) self.set_acl(policy, headers=headers)
[ "def", "set_as_logging_target", "(", "self", ",", "headers", "=", "None", ")", ":", "policy", "=", "self", ".", "get_acl", "(", "headers", "=", "headers", ")", "g1", "=", "Grant", "(", "permission", "=", "'WRITE'", ",", "type", "=", "'Group'", ",", "ur...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/s3/bucket.py#L1232-L1242
openstack/manila
142990edc027e14839d5deaf4954dd6fc88de15e
manila/share/drivers/nexenta/ns4/nexenta_nfs_helper.py
python
NFSHelper.update_access
(self, share_name, access_rules)
Update access to the share.
Update access to the share.
[ "Update", "access", "to", "the", "share", "." ]
def update_access(self, share_name, access_rules): """Update access to the share.""" rw_list = [] ro_list = [] for rule in access_rules: if rule['access_type'].lower() != 'ip': msg = _('Only IP access type is supported.') raise exception.InvalidShareAccess(reason=msg) else: if rule['access_level'] == common.ACCESS_LEVEL_RW: rw_list.append(rule['access_to']) else: ro_list.append(rule['access_to']) share_opts = { 'auth_type': 'none', 'read_write': ':'.join(rw_list), 'read_only': ':'.join(ro_list), 'recursive': 'true', 'anonymous_rw': 'true', 'anonymous': 'true', 'extra_options': 'anon=0', } self.nms.netstorsvc.share_folder( 'svc:/network/nfs/server:default', self._get_share_path(share_name), share_opts)
[ "def", "update_access", "(", "self", ",", "share_name", ",", "access_rules", ")", ":", "rw_list", "=", "[", "]", "ro_list", "=", "[", "]", "for", "rule", "in", "access_rules", ":", "if", "rule", "[", "'access_type'", "]", ".", "lower", "(", ")", "!=", ...
https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/share/drivers/nexenta/ns4/nexenta_nfs_helper.py#L165-L190
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/vpc/vpc_peering_connection.py
python
VpcPeeringConnection.__init__
(self, connection=None)
Represents a VPC peering connection. :ivar id: The unique ID of the VPC peering connection. :ivar accepter_vpc_info: Information on peer Vpc. :ivar requester_vpc_info: Information on requester Vpc. :ivar expiration_time: The expiration date and time for the VPC peering connection. :ivar status_code: The status of the VPC peering connection. :ivar status_message: A message that provides more information about the status of the VPC peering connection, if applicable.
Represents a VPC peering connection.
[ "Represents", "a", "VPC", "peering", "connection", "." ]
def __init__(self, connection=None): """ Represents a VPC peering connection. :ivar id: The unique ID of the VPC peering connection. :ivar accepter_vpc_info: Information on peer Vpc. :ivar requester_vpc_info: Information on requester Vpc. :ivar expiration_time: The expiration date and time for the VPC peering connection. :ivar status_code: The status of the VPC peering connection. :ivar status_message: A message that provides more information about the status of the VPC peering connection, if applicable. """ super(VpcPeeringConnection, self).__init__(connection) self.id = None self.accepter_vpc_info = VpcInfo() self.requester_vpc_info = VpcInfo() self.expiration_time = None self._status = VpcPeeringConnectionStatus()
[ "def", "__init__", "(", "self", ",", "connection", "=", "None", ")", ":", "super", "(", "VpcPeeringConnection", ",", "self", ")", ".", "__init__", "(", "connection", ")", "self", ".", "id", "=", "None", "self", ".", "accepter_vpc_info", "=", "VpcInfo", "...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/vpc/vpc_peering_connection.py#L96-L112
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/contrib/pyros/util.py
python
substitute_ssv_in_dr_constraints
(model, constraint)
return model.dr_substituted_constraints[max(model.dr_substituted_constraints.keys())]
Generate the standard_repn for the dr constraints. Generate new expression with replace_expression to ignore the ssv component. Then, replace_expression with substitution_map between ssv and the new expression. Deactivate or del_component the original dr equation. Then, return modified model and do coefficient matching as normal. :param model: the working_model :param constraint: an equality constraint from the working model identified to be of the form h(x,z,q) = 0. :return:
Generate the standard_repn for the dr constraints. Generate new expression with replace_expression to ignore the ssv component. Then, replace_expression with substitution_map between ssv and the new expression. Deactivate or del_component the original dr equation. Then, return modified model and do coefficient matching as normal. :param model: the working_model :param constraint: an equality constraint from the working model identified to be of the form h(x,z,q) = 0. :return:
[ "Generate", "the", "standard_repn", "for", "the", "dr", "constraints", ".", "Generate", "new", "expression", "with", "replace_expression", "to", "ignore", "the", "ssv", "component", ".", "Then", "replace_expression", "with", "substitution_map", "between", "ssv", "an...
def substitute_ssv_in_dr_constraints(model, constraint): ''' Generate the standard_repn for the dr constraints. Generate new expression with replace_expression to ignore the ssv component. Then, replace_expression with substitution_map between ssv and the new expression. Deactivate or del_component the original dr equation. Then, return modified model and do coefficient matching as normal. :param model: the working_model :param constraint: an equality constraint from the working model identified to be of the form h(x,z,q) = 0. :return: ''' dr_eqns = model.util.decision_rule_eqns fsv = ComponentSet(model.util.first_stage_variables) if not hasattr(model, "dr_substituted_constraints"): model.dr_substituted_constraints = ConstraintList() for eqn in dr_eqns: repn = generate_standard_repn(eqn.body, compute_values=False) new_expression = 0 map_linear_coeff_to_var = [x for x in zip(repn.linear_coefs, repn.linear_vars) if x[1] in ComponentSet(fsv)] map_quad_coeff_to_var = [x for x in zip(repn.quadratic_coefs, repn.quadratic_vars) if x[1] in ComponentSet(fsv)] if repn.linear_coefs: for coeff, var in map_linear_coeff_to_var: new_expression += coeff * var if repn.quadratic_coefs: for coeff, var in map_quad_coeff_to_var: new_expression += coeff * var[0] * var[1] # var here is a 2-tuple model.no_ssv_dr_expr = Expression(expr=new_expression) substitution_map = {} substitution_map[id(repn.linear_vars[-1])] = model.no_ssv_dr_expr.expr model.dr_substituted_constraints.add( replace_expressions(expr=constraint.lower, substitution_map=substitution_map) == replace_expressions(expr=constraint.body, substitution_map=substitution_map)) # === Delete the original constraint model.del_component(constraint.name) model.del_component("no_ssv_dr_expr") return model.dr_substituted_constraints[max(model.dr_substituted_constraints.keys())]
[ "def", "substitute_ssv_in_dr_constraints", "(", "model", ",", "constraint", ")", ":", "dr_eqns", "=", "model", ".", "util", ".", "decision_rule_eqns", "fsv", "=", "ComponentSet", "(", "model", ".", "util", ".", "first_stage_variables", ")", "if", "not", "hasattr...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/contrib/pyros/util.py#L455-L496
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/urllib3/contrib/appengine.py
python
AppEngineManager.__exit__
(self, exc_type, exc_val, exc_tb)
return False
[]
def __exit__(self, exc_type, exc_val, exc_tb): # Return False to re-raise any potential exceptions return False
[ "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_val", ",", "exc_tb", ")", ":", "# Return False to re-raise any potential exceptions", "return", "False" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/urllib3/contrib/appengine.py#L127-L129
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/optparse.py
python
OptionParser.parse_args
(self, args=None, values=None)
return self.check_values(values, args)
parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options.
parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string])
[ "parse_args", "(", "args", ":", "[", "string", "]", "=", "sys", ".", "argv", "[", "1", ":", "]", "values", ":", "Values", "=", "None", ")", "-", ">", "(", "values", ":", "Values", "args", ":", "[", "string", "]", ")" ]
def parse_args(self, args=None, values=None): """ parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options. """ rargs = self._get_args(args) if values is None: values = self.get_default_values() # Store the halves of the argument list as attributes for the # convenience of callbacks: # rargs # the rest of the command-line (the "r" stands for # "remaining" or "right-hand") # largs # the leftover arguments -- ie. what's left after removing # options and their arguments (the "l" stands for "leftover" # or "left-hand") self.rargs = rargs self.largs = largs = [] self.values = values try: stop = self._process_args(largs, rargs, values) except (BadOptionError, OptionValueError), err: self.error(str(err)) args = largs + rargs return self.check_values(values, args)
[ "def", "parse_args", "(", "self", ",", "args", "=", "None", ",", "values", "=", "None", ")", ":", "rargs", "=", "self", ".", "_get_args", "(", "args", ")", "if", "values", "is", "None", ":", "values", "=", "self", ".", "get_default_values", "(", ")",...
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/optparse.py#L1355-L1392
vlachoudis/bCNC
67126b4894dabf6579baf47af8d0f9b7de35e6e3
bCNC/plugins/intersection.py
python
Tool.__init__
(self, master)
[]
def __init__(self, master): Plugin.__init__(self, master,"Intersection") #Helical_Descent: is the name of the plugin show in the tool ribbon button self.icon = "intersection" #<<< This is the name of png file used as icon for the ribbon button. It will be search in the "icons" subfolder self.group = "Development" #<<< This is the name of group that plugin belongs self.oneshot = True #Here we are creating the widgets presented to the user inside the plugin #Name, Type , Default value, Description self.variables = [ #<<< Define a list of components for the GUI ("name" , "db" , "", _("Name")), #used to store plugin settings in the internal database ] self.buttons.append("exe")
[ "def", "__init__", "(", "self", ",", "master", ")", ":", "Plugin", ".", "__init__", "(", "self", ",", "master", ",", "\"Intersection\"", ")", "#Helical_Descent: is the name of the plugin show in the tool ribbon button", "self", ".", "icon", "=", "\"intersection\"", "#...
https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/plugins/intersection.py#L27-L38
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/pygments/util.py
python
make_analysator
(f)
return staticmethod(text_analyse)
Return a static text analysation function that returns float values.
Return a static text analysation function that returns float values.
[ "Return", "a", "static", "text", "analysation", "function", "that", "returns", "float", "values", "." ]
def make_analysator(f): """ Return a static text analysation function that returns float values. """ def text_analyse(text): rv = f(text) if not rv: return 0.0 return min(1.0, max(0.0, float(rv))) text_analyse.__doc__ = f.__doc__ return staticmethod(text_analyse)
[ "def", "make_analysator", "(", "f", ")", ":", "def", "text_analyse", "(", "text", ")", ":", "rv", "=", "f", "(", "text", ")", "if", "not", "rv", ":", "return", "0.0", "return", "min", "(", "1.0", ",", "max", "(", "0.0", ",", "float", "(", "rv", ...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/pygments/util.py#L107-L118
GNS3/gns3-gui
da8adbaa18ab60e053af2a619efd468f4c8950f3
gns3/local_server_config.py
python
LocalServerConfig.saveSettings
(self, section, settings)
Save all the settings in a given section. :param section: section name :param settings: settings to save (dict)
Save all the settings in a given section.
[ "Save", "all", "the", "settings", "in", "a", "given", "section", "." ]
def saveSettings(self, section, settings): """ Save all the settings in a given section. :param section: section name :param settings: settings to save (dict) """ changed = False if section not in self._config: self._config[section] = {} changed = True for name, value in settings.items(): if name not in self._config[section] or self._config[section][name] != str(value): self._config[section][name] = str(value) changed = True if changed: self.writeConfig()
[ "def", "saveSettings", "(", "self", ",", "section", ",", "settings", ")", ":", "changed", "=", "False", "if", "section", "not", "in", "self", ".", "_config", ":", "self", ".", "_config", "[", "section", "]", "=", "{", "}", "changed", "=", "True", "fo...
https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/local_server_config.py#L120-L139
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/outtakes/MMKit.py
python
MMKit.show_hybrid_btngrp
(self)
Show the hybrid button group and label above it. This is a companion method to hide_hybrid_btngrp(). It includes workarounds for Qt layout issues that crop up when hiding/showing the hybrid button groupbox using Qt's hide() and show() methods. See bug 2407 for more information.
Show the hybrid button group and label above it. This is a companion method to hide_hybrid_btngrp(). It includes workarounds for Qt layout issues that crop up when hiding/showing the hybrid button groupbox using Qt's hide() and show() methods. See bug 2407 for more information.
[ "Show", "the", "hybrid", "button", "group", "and", "label", "above", "it", ".", "This", "is", "a", "companion", "method", "to", "hide_hybrid_btngrp", "()", ".", "It", "includes", "workarounds", "for", "Qt", "layout", "issues", "that", "crop", "up", "when", ...
def show_hybrid_btngrp(self): # Mark 2007-06-20 """Show the hybrid button group and label above it. This is a companion method to hide_hybrid_btngrp(). It includes workarounds for Qt layout issues that crop up when hiding/showing the hybrid button groupbox using Qt's hide() and show() methods. See bug 2407 for more information. """ if 1: self.hybrid_btngrp.show() else: self.hybrid_btngrp.show() self.atomic_hybrids_label.show()
[ "def", "show_hybrid_btngrp", "(", "self", ")", ":", "# Mark 2007-06-20", "if", "1", ":", "self", ".", "hybrid_btngrp", ".", "show", "(", ")", "else", ":", "self", ".", "hybrid_btngrp", ".", "show", "(", ")", "self", ".", "atomic_hybrids_label", ".", "show"...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/outtakes/MMKit.py#L555-L566
getavalon/core
31e8cb4760e00e3db64443f6f932b7fd8e96d41d
avalon/vendor/qtawesome/iconic_font.py
python
CharIconPainter._paint_icon
(self, iconic, painter, rect, mode, state, options)
Paint a single icon
Paint a single icon
[ "Paint", "a", "single", "icon" ]
def _paint_icon(self, iconic, painter, rect, mode, state, options): """Paint a single icon""" painter.save() color, char = options['color'], options['char'] if mode == QtGui.QIcon.Disabled: color = options.get('color_disabled', color) char = options.get('disabled', char) elif mode == QtGui.QIcon.Active: color = options.get('color_active', color) char = options.get('active', char) elif mode == QtGui.QIcon.Selected: color = options.get('color_selected', color) char = options.get('selected', char) painter.setPen(QtGui.QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason for not using full-sized glyphs is the negative bearing of # fonts. draw_size = 0.875 * round(rect.height() * options['scale_factor']) prefix = options['prefix'] # Animation setup hook animation = options.get('animation') if animation is not None: animation.setup(self, painter, rect) painter.setFont(iconic.font(prefix, draw_size)) if 'offset' in options: rect = QtCore.QRect(rect) rect.translate(options['offset'][0] * rect.width(), options['offset'][1] * rect.height()) painter.setOpacity(options.get('opacity', 1.0)) painter.drawText(rect, QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, char) painter.restore()
[ "def", "_paint_icon", "(", "self", ",", "iconic", ",", "painter", ",", "rect", ",", "mode", ",", "state", ",", "options", ")", ":", "painter", ".", "save", "(", ")", "color", ",", "char", "=", "options", "[", "'color'", "]", ",", "options", "[", "'...
https://github.com/getavalon/core/blob/31e8cb4760e00e3db64443f6f932b7fd8e96d41d/avalon/vendor/qtawesome/iconic_font.py#L42-L81
dagrz/aws_pwn
e90d6089adc99a0298549d173d17f01b76b22449
reconnaissance/validate_accounts.py
python
validate_account_signin
(account)
return result
[]
def validate_account_signin(account): result = { 'accountAlias': None, 'accountId': None, 'signinUri': 'https://' + account + '.signin.aws.amazon.com/', 'exists': False, 'error': None } if re.match(r'\d{12}', account): result['accountId'] = account else: result['accountAlias'] = account if not validators.url(result['signinUri']): result['error'] = 'Invalid URI' return result try: r = requests.get(result['signinUri'], allow_redirects=False) if r.status_code == 302: result['exists'] = True except requests.exceptions.RequestException as e: result['error'] = e return result
[ "def", "validate_account_signin", "(", "account", ")", ":", "result", "=", "{", "'accountAlias'", ":", "None", ",", "'accountId'", ":", "None", ",", "'signinUri'", ":", "'https://'", "+", "account", "+", "'.signin.aws.amazon.com/'", ",", "'exists'", ":", "False"...
https://github.com/dagrz/aws_pwn/blob/e90d6089adc99a0298549d173d17f01b76b22449/reconnaissance/validate_accounts.py#L34-L59
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/dcdb/v20180411/models.py
python
CreateDCDBInstanceRequest.__init__
(self)
r""" :param Zones: 分片节点可用区分布,最多可填两个可用区。当分片规格为一主两从时,其中两个节点在第一个可用区。 注意当前可售卖的可用区需要通过DescribeDCDBSaleInfo接口拉取。 :type Zones: list of str :param Period: 欲购买的时长,单位:月。 :type Period: int :param ShardMemory: 分片内存大小,单位:GB,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardMemory: int :param ShardStorage: 分片存储空间大小,单位:GB,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardStorage: int :param ShardNodeCount: 单个分片节点个数,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardNodeCount: int :param ShardCount: 实例分片个数,可选范围2-8,可以通过升级实例进行新增分片到最多64个分片。 :type ShardCount: int :param Count: 欲购买实例的数量 :type Count: int :param ProjectId: 项目 ID,可以通过查看项目列表获取,不传则关联到默认项目 :type ProjectId: int :param VpcId: 虚拟私有网络 ID,不传或传空表示创建为基础网络 :type VpcId: str :param SubnetId: 虚拟私有网络子网 ID,VpcId不为空时必填 :type SubnetId: str :param DbVersionId: 数据库引擎版本,当前可选:8.0.18,10.1.9,5.7.17。 8.0.18 - MySQL 8.0.18; 10.1.9 - Mariadb 10.1.9; 5.7.17 - Percona 5.7.17。 如果不填的话,默认为5.7.17,表示Percona 5.7.17。 :type DbVersionId: str :param AutoVoucher: 是否自动使用代金券进行支付,默认不使用。 :type AutoVoucher: bool :param VoucherIds: 代金券ID列表,目前仅支持指定一张代金券。 :type VoucherIds: list of str :param SecurityGroupId: 安全组id :type SecurityGroupId: str :param InstanceName: 实例名称, 可以通过该字段自主的设置实例的名字 :type InstanceName: str :param Ipv6Flag: 是否支持IPv6 :type Ipv6Flag: int :param ResourceTags: 标签键值对数组 :type ResourceTags: list of ResourceTag :param InitParams: 参数列表。本接口的可选值为:character_set_server(字符集,必传),lower_case_table_names(表名大小写敏感,必传,0 - 敏感;1-不敏感),innodb_page_size(innodb数据页,默认16K),sync_mode(同步模式:0 - 异步; 1 - 强同步;2 - 强同步可退化。默认为强同步可退化)。 :type InitParams: list of DBParamValue :param DcnRegion: DCN源地域 :type DcnRegion: str :param DcnInstanceId: DCN源实例ID :type DcnInstanceId: str :param AutoRenewFlag: 自动续费标记,0表示默认状态(用户未设置,即初始状态即手动续费,用户开通了预付费不停服特权也会进行自动续费), 1表示自动续费,2表示明确不自动续费(用户设置),若业务无续费概念或无需自动续费,需要设置为0 :type AutoRenewFlag: int
r""" :param Zones: 分片节点可用区分布,最多可填两个可用区。当分片规格为一主两从时,其中两个节点在第一个可用区。 注意当前可售卖的可用区需要通过DescribeDCDBSaleInfo接口拉取。 :type Zones: list of str :param Period: 欲购买的时长,单位:月。 :type Period: int :param ShardMemory: 分片内存大小,单位:GB,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardMemory: int :param ShardStorage: 分片存储空间大小,单位:GB,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardStorage: int :param ShardNodeCount: 单个分片节点个数,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardNodeCount: int :param ShardCount: 实例分片个数,可选范围2-8,可以通过升级实例进行新增分片到最多64个分片。 :type ShardCount: int :param Count: 欲购买实例的数量 :type Count: int :param ProjectId: 项目 ID,可以通过查看项目列表获取,不传则关联到默认项目 :type ProjectId: int :param VpcId: 虚拟私有网络 ID,不传或传空表示创建为基础网络 :type VpcId: str :param SubnetId: 虚拟私有网络子网 ID,VpcId不为空时必填 :type SubnetId: str :param DbVersionId: 数据库引擎版本,当前可选:8.0.18,10.1.9,5.7.17。 8.0.18 - MySQL 8.0.18; 10.1.9 - Mariadb 10.1.9; 5.7.17 - Percona 5.7.17。 如果不填的话,默认为5.7.17,表示Percona 5.7.17。 :type DbVersionId: str :param AutoVoucher: 是否自动使用代金券进行支付,默认不使用。 :type AutoVoucher: bool :param VoucherIds: 代金券ID列表,目前仅支持指定一张代金券。 :type VoucherIds: list of str :param SecurityGroupId: 安全组id :type SecurityGroupId: str :param InstanceName: 实例名称, 可以通过该字段自主的设置实例的名字 :type InstanceName: str :param Ipv6Flag: 是否支持IPv6 :type Ipv6Flag: int :param ResourceTags: 标签键值对数组 :type ResourceTags: list of ResourceTag :param InitParams: 参数列表。本接口的可选值为:character_set_server(字符集,必传),lower_case_table_names(表名大小写敏感,必传,0 - 敏感;1-不敏感),innodb_page_size(innodb数据页,默认16K),sync_mode(同步模式:0 - 异步; 1 - 强同步;2 - 强同步可退化。默认为强同步可退化)。 :type InitParams: list of DBParamValue :param DcnRegion: DCN源地域 :type DcnRegion: str :param DcnInstanceId: DCN源实例ID :type DcnInstanceId: str :param AutoRenewFlag: 自动续费标记,0表示默认状态(用户未设置,即初始状态即手动续费,用户开通了预付费不停服特权也会进行自动续费), 1表示自动续费,2表示明确不自动续费(用户设置),若业务无续费概念或无需自动续费,需要设置为0 :type AutoRenewFlag: int
[ "r", ":", "param", "Zones", ":", "分片节点可用区分布,最多可填两个可用区。当分片规格为一主两从时,其中两个节点在第一个可用区。", "注意当前可售卖的可用区需要通过DescribeDCDBSaleInfo接口拉取。", ":", "type", "Zones", ":", "list", "of", "str", ":", "param", "Period", ":", "欲购买的时长,单位:月。", ":", "type", "Period", ":", "int", ":", "param...
def __init__(self): r""" :param Zones: 分片节点可用区分布,最多可填两个可用区。当分片规格为一主两从时,其中两个节点在第一个可用区。 注意当前可售卖的可用区需要通过DescribeDCDBSaleInfo接口拉取。 :type Zones: list of str :param Period: 欲购买的时长,单位:月。 :type Period: int :param ShardMemory: 分片内存大小,单位:GB,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardMemory: int :param ShardStorage: 分片存储空间大小,单位:GB,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardStorage: int :param ShardNodeCount: 单个分片节点个数,可以通过 DescribeShardSpec 查询实例规格获得。 :type ShardNodeCount: int :param ShardCount: 实例分片个数,可选范围2-8,可以通过升级实例进行新增分片到最多64个分片。 :type ShardCount: int :param Count: 欲购买实例的数量 :type Count: int :param ProjectId: 项目 ID,可以通过查看项目列表获取,不传则关联到默认项目 :type ProjectId: int :param VpcId: 虚拟私有网络 ID,不传或传空表示创建为基础网络 :type VpcId: str :param SubnetId: 虚拟私有网络子网 ID,VpcId不为空时必填 :type SubnetId: str :param DbVersionId: 数据库引擎版本,当前可选:8.0.18,10.1.9,5.7.17。 8.0.18 - MySQL 8.0.18; 10.1.9 - Mariadb 10.1.9; 5.7.17 - Percona 5.7.17。 如果不填的话,默认为5.7.17,表示Percona 5.7.17。 :type DbVersionId: str :param AutoVoucher: 是否自动使用代金券进行支付,默认不使用。 :type AutoVoucher: bool :param VoucherIds: 代金券ID列表,目前仅支持指定一张代金券。 :type VoucherIds: list of str :param SecurityGroupId: 安全组id :type SecurityGroupId: str :param InstanceName: 实例名称, 可以通过该字段自主的设置实例的名字 :type InstanceName: str :param Ipv6Flag: 是否支持IPv6 :type Ipv6Flag: int :param ResourceTags: 标签键值对数组 :type ResourceTags: list of ResourceTag :param InitParams: 参数列表。本接口的可选值为:character_set_server(字符集,必传),lower_case_table_names(表名大小写敏感,必传,0 - 敏感;1-不敏感),innodb_page_size(innodb数据页,默认16K),sync_mode(同步模式:0 - 异步; 1 - 强同步;2 - 强同步可退化。默认为强同步可退化)。 :type InitParams: list of DBParamValue :param DcnRegion: DCN源地域 :type DcnRegion: str :param DcnInstanceId: DCN源实例ID :type DcnInstanceId: str :param AutoRenewFlag: 自动续费标记,0表示默认状态(用户未设置,即初始状态即手动续费,用户开通了预付费不停服特权也会进行自动续费), 1表示自动续费,2表示明确不自动续费(用户设置),若业务无续费概念或无需自动续费,需要设置为0 :type AutoRenewFlag: int """ self.Zones = None self.Period = None self.ShardMemory = None self.ShardStorage = None self.ShardNodeCount = None self.ShardCount = None self.Count = None self.ProjectId = None self.VpcId = None self.SubnetId = None self.DbVersionId = None self.AutoVoucher = None self.VoucherIds = None self.SecurityGroupId = None self.InstanceName = None self.Ipv6Flag = None self.ResourceTags = None self.InitParams = None self.DcnRegion = None self.DcnInstanceId = None self.AutoRenewFlag = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Zones", "=", "None", "self", ".", "Period", "=", "None", "self", ".", "ShardMemory", "=", "None", "self", ".", "ShardStorage", "=", "None", "self", ".", "ShardNodeCount", "=", "None", "self", ".",...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/dcdb/v20180411/models.py#L473-L546
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/ext/blobstore/blobstore.py
python
BlobReader.__read_from_buffer
(self, size)
return data, size
Reads at most size bytes from the buffer. Args: size: Number of bytes to read, or negative to read the entire buffer. Returns: Tuple (data, size): data: The bytes read from the buffer. size: The remaining unread byte count. Negative when size is negative. Thus when remaining size != 0, the calling method may choose to fill the buffer again and keep reading.
Reads at most size bytes from the buffer.
[ "Reads", "at", "most", "size", "bytes", "from", "the", "buffer", "." ]
def __read_from_buffer(self, size): """Reads at most size bytes from the buffer. Args: size: Number of bytes to read, or negative to read the entire buffer. Returns: Tuple (data, size): data: The bytes read from the buffer. size: The remaining unread byte count. Negative when size is negative. Thus when remaining size != 0, the calling method may choose to fill the buffer again and keep reading. """ if not self.__blob_key: raise ValueError("File is closed") if size < 0: end_pos = len(self.__buffer) else: end_pos = self.__buffer_position + size data = self.__buffer[self.__buffer_position:end_pos] data_length = len(data) size -= data_length self.__position += data_length self.__buffer_position += data_length if self.__buffer_position == len(self.__buffer): self.__buffer = "" self.__buffer_position = 0 return data, size
[ "def", "__read_from_buffer", "(", "self", ",", "size", ")", ":", "if", "not", "self", ".", "__blob_key", ":", "raise", "ValueError", "(", "\"File is closed\"", ")", "if", "size", "<", "0", ":", "end_pos", "=", "len", "(", "self", ".", "__buffer", ")", ...
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/ext/blobstore/blobstore.py#L788-L821
isocpp/CppCoreGuidelines
171fda35972cb0678c26274547be3d5dfaf73156
scripts/python/cpplint.py
python
NestingState.SeenOpenBrace
(self)
return (not self.stack) or self.stack[-1].seen_open_brace
Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace.
Check if we have seen the opening brace for the innermost block.
[ "Check", "if", "we", "have", "seen", "the", "opening", "brace", "for", "the", "innermost", "block", "." ]
def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace
[ "def", "SeenOpenBrace", "(", "self", ")", ":", "return", "(", "not", "self", ".", "stack", ")", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace" ]
https://github.com/isocpp/CppCoreGuidelines/blob/171fda35972cb0678c26274547be3d5dfaf73156/scripts/python/cpplint.py#L2540-L2547
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
ParserElement.transformString
( self, instring )
Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
[ "Extension", "to", "C", "{", "L", "{", "scanString", "}}", "to", "modify", "matching", "text", "with", "modified", "tokens", "that", "may", "be", "returned", "from", "a", "parse", "action", ".", "To", "use", "C", "{", "transformString", "}", "define", "a...
def transformString( self, instring ): """ Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. """ out = [] lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to # keep string locs straight between transformString and scanString self.keepTabs = True try: for t,s,e in self.scanString( instring ): out.append( instring[lastE:s] ) if t: if isinstance(t,ParseResults): out += t.asList() elif isinstance(t,list): out += t else: out.append(t) lastE = e out.append(instring[lastE:]) out = [o for o in out if o] return "".join(map(_ustr,_flatten(out))) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
[ "def", "transformString", "(", "self", ",", "instring", ")", ":", "out", "=", "[", "]", "lastE", "=", "0", "# force preservation of <TAB>s, to minimize unwanted transformation of string, and to", "# keep string locs straight between transformString and scanString", "self", ".", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py#L1692-L1733
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/meta/lib/oe/utils.py
python
ThreadedPool.add_task
(self, func, *args, **kargs)
Add a task to the queue
Add a task to the queue
[ "Add", "a", "task", "to", "the", "queue" ]
def add_task(self, func, *args, **kargs): """Add a task to the queue""" self.tasks.put((func, args, kargs))
[ "def", "add_task", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "self", ".", "tasks", ".", "put", "(", "(", "func", ",", "args", ",", "kargs", ")", ")" ]
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/meta/lib/oe/utils.py#L530-L532
merenlab/anvio
9b792e2cedc49ecb7c0bed768261595a0d87c012
anvio/structureops.py
python
ExternalStructuresFile.is_gene_caller_ids_ok
(self)
Returns True if all gene_callers_ids in external structures file are in the contigs database and are coding
Returns True if all gene_callers_ids in external structures file are in the contigs database and are coding
[ "Returns", "True", "if", "all", "gene_callers_ids", "in", "external", "structures", "file", "are", "in", "the", "contigs", "database", "and", "are", "coding" ]
def is_gene_caller_ids_ok(self): """Returns True if all gene_callers_ids in external structures file are in the contigs database and are coding""" contigs_db = db.DB(self.contigs_db_path, client_version=None, ignore_version=True) table = contigs_db.get_table_as_dataframe('gene_amino_acid_sequences') genes_in_contigs_db_with_aa_seqs = table.loc[table['sequence'] != '', 'gene_callers_id'].tolist() missing_in_contigs = [x for x in self.content['gene_callers_id'] if x not in genes_in_contigs_db_with_aa_seqs] if len(missing_in_contigs): raise ConfigError(f"Some gene caller ids in your external structures file are either missing from your contigs database " f"or are non-coding (they have no corresponding amino acid sequence). This is a show stopper. " f"Here are the gene caller ids: {missing_in_contigs}")
[ "def", "is_gene_caller_ids_ok", "(", "self", ")", ":", "contigs_db", "=", "db", ".", "DB", "(", "self", ".", "contigs_db_path", ",", "client_version", "=", "None", ",", "ignore_version", "=", "True", ")", "table", "=", "contigs_db", ".", "get_table_as_datafram...
https://github.com/merenlab/anvio/blob/9b792e2cedc49ecb7c0bed768261595a0d87c012/anvio/structureops.py#L1997-L2008
Anaconda-Platform/anaconda-project
df5ec33c12591e6512436d38d36c6132fa2e9618
anaconda_project/internal/cli/download_commands.py
python
main_add
(args)
return add_download(args.directory, args.env_spec, args.filename_variable, args.download_url, args.filename, args.hash_algorithm, args.hash_value)
Start the download command and return exit status code.
Start the download command and return exit status code.
[ "Start", "the", "download", "command", "and", "return", "exit", "status", "code", "." ]
def main_add(args): """Start the download command and return exit status code.""" return add_download(args.directory, args.env_spec, args.filename_variable, args.download_url, args.filename, args.hash_algorithm, args.hash_value)
[ "def", "main_add", "(", "args", ")", ":", "return", "add_download", "(", "args", ".", "directory", ",", "args", ".", "env_spec", ",", "args", ".", "filename_variable", ",", "args", ".", "download_url", ",", "args", ".", "filename", ",", "args", ".", "has...
https://github.com/Anaconda-Platform/anaconda-project/blob/df5ec33c12591e6512436d38d36c6132fa2e9618/anaconda_project/internal/cli/download_commands.py#L76-L79
python-telegram-bot/python-telegram-bot
ade1529986f5b6d394a65372d6a27045a70725b2
telegram/base.py
python
TelegramObject.de_json
(cls: Type[TO], data: Optional[JSONDict], bot: 'Bot')
return cls(bot=bot, **data)
Converts JSON data to a Telegram object. Args: data (Dict[:obj:`str`, ...]): The JSON data. bot (:class:`telegram.Bot`): The bot associated with this object. Returns: The Telegram object.
Converts JSON data to a Telegram object.
[ "Converts", "JSON", "data", "to", "a", "Telegram", "object", "." ]
def de_json(cls: Type[TO], data: Optional[JSONDict], bot: 'Bot') -> Optional[TO]: """Converts JSON data to a Telegram object. Args: data (Dict[:obj:`str`, ...]): The JSON data. bot (:class:`telegram.Bot`): The bot associated with this object. Returns: The Telegram object. """ data = cls._parse_data(data) if data is None: return None if cls == TelegramObject: return cls() return cls(bot=bot, **data)
[ "def", "de_json", "(", "cls", ":", "Type", "[", "TO", "]", ",", "data", ":", "Optional", "[", "JSONDict", "]", ",", "bot", ":", "'Bot'", ")", "->", "Optional", "[", "TO", "]", ":", "data", "=", "cls", ".", "_parse_data", "(", "data", ")", "if", ...
https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/telegram/base.py#L61-L79
niosus/EasyClangComplete
3b16eb17735aaa3f56bb295fc5481b269ee9f2ef
plugin/clang/cindex35.py
python
AccessSpecifier.name
(self)
return self._name_map[self]
Get the enumeration name of this access specifier.
Get the enumeration name of this access specifier.
[ "Get", "the", "enumeration", "name", "of", "this", "access", "specifier", "." ]
def name(self): """Get the enumeration name of this access specifier.""" if self._name_map is None: self._name_map = {} for key,value in list(AccessSpecifier.__dict__.items()): if isinstance(value,AccessSpecifier): self._name_map[value] = key return self._name_map[self]
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "_name_map", "is", "None", ":", "self", ".", "_name_map", "=", "{", "}", "for", "key", ",", "value", "in", "list", "(", "AccessSpecifier", ".", "__dict__", ".", "items", "(", ")", ")", ":", ...
https://github.com/niosus/EasyClangComplete/blob/3b16eb17735aaa3f56bb295fc5481b269ee9f2ef/plugin/clang/cindex35.py#L1480-L1487
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/query/qcore.py
python
Highest.__eq__
(self, other)
return self.__class__ is type(other)
[]
def __eq__(self, other): return self.__class__ is type(other)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "__class__", "is", "type", "(", "other", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/query/qcore.py#L121-L122
analyticalmindsltd/smote_variants
dedbc3d00b266954fedac0ae87775e1643bc920a
smote_variants/_smote_variants.py
python
kmeans_SMOTE.get_params
(self, deep=False)
return {'proportion': self.proportion, 'n_neighbors': self.n_neighbors, 'n_clusters': self.n_clusters, 'irt': self.irt, 'n_jobs': self.n_jobs, 'random_state': self._random_state_init}
Returns: dict: the parameters of the current sampling object
Returns: dict: the parameters of the current sampling object
[ "Returns", ":", "dict", ":", "the", "parameters", "of", "the", "current", "sampling", "object" ]
def get_params(self, deep=False): """ Returns: dict: the parameters of the current sampling object """ return {'proportion': self.proportion, 'n_neighbors': self.n_neighbors, 'n_clusters': self.n_clusters, 'irt': self.irt, 'n_jobs': self.n_jobs, 'random_state': self._random_state_init}
[ "def", "get_params", "(", "self", ",", "deep", "=", "False", ")", ":", "return", "{", "'proportion'", ":", "self", ".", "proportion", ",", "'n_neighbors'", ":", "self", ".", "n_neighbors", ",", "'n_clusters'", ":", "self", ".", "n_clusters", ",", "'irt'", ...
https://github.com/analyticalmindsltd/smote_variants/blob/dedbc3d00b266954fedac0ae87775e1643bc920a/smote_variants/_smote_variants.py#L18063-L18073
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.py
python
FactorAnalysis.transform
(self, X)
return X_transformed
Apply dimensionality reduction to X using the model. Compute the expected mean of the latent variables. See Barber, 21.2.33 (or Bishop, 12.66). Parameters ---------- X : array-like, shape (n_samples, n_features) Training data. Returns ------- X_new : array-like, shape (n_samples, n_components) The latent variables of X.
Apply dimensionality reduction to X using the model.
[ "Apply", "dimensionality", "reduction", "to", "X", "using", "the", "model", "." ]
def transform(self, X): """Apply dimensionality reduction to X using the model. Compute the expected mean of the latent variables. See Barber, 21.2.33 (or Bishop, 12.66). Parameters ---------- X : array-like, shape (n_samples, n_features) Training data. Returns ------- X_new : array-like, shape (n_samples, n_components) The latent variables of X. """ check_is_fitted(self, 'components_') X = check_array(X) Ih = np.eye(len(self.components_)) X_transformed = X - self.mean_ Wpsi = self.components_ / self.noise_variance_ cov_z = linalg.inv(Ih + np.dot(Wpsi, self.components_.T)) tmp = fast_dot(X_transformed, Wpsi.T) X_transformed = fast_dot(tmp, cov_z) return X_transformed
[ "def", "transform", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'components_'", ")", "X", "=", "check_array", "(", "X", ")", "Ih", "=", "np", ".", "eye", "(", "len", "(", "self", ".", "components_", ")", ")", "X_transformed...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/decomposition/factor_analysis.py#L232-L260
ring04h/wyportmap
c4201e2313504e780a7f25238eba2a2d3223e739
sqlalchemy/sql/selectable.py
python
Select.append_from
(self, fromclause)
append the given FromClause expression to this select() construct's FROM clause. This is an **in-place** mutation method; the :meth:`~.Select.select_from` method is preferred, as it provides standard :term:`method chaining`.
append the given FromClause expression to this select() construct's FROM clause.
[ "append", "the", "given", "FromClause", "expression", "to", "this", "select", "()", "construct", "s", "FROM", "clause", "." ]
def append_from(self, fromclause): """append the given FromClause expression to this select() construct's FROM clause. This is an **in-place** mutation method; the :meth:`~.Select.select_from` method is preferred, as it provides standard :term:`method chaining`. """ self._reset_exported() fromclause = _interpret_as_from(fromclause) self._from_obj = self._from_obj.union([fromclause])
[ "def", "append_from", "(", "self", ",", "fromclause", ")", ":", "self", ".", "_reset_exported", "(", ")", "fromclause", "=", "_interpret_as_from", "(", "fromclause", ")", "self", ".", "_from_obj", "=", "self", ".", "_from_obj", ".", "union", "(", "[", "fro...
https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/sqlalchemy/sql/selectable.py#L2931-L2942
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/mailbox.py
python
_PartialFile.tell
(self)
return _ProxyFile.tell(self) - self._start
Return the position with respect to start.
Return the position with respect to start.
[ "Return", "the", "position", "with", "respect", "to", "start", "." ]
def tell(self): """Return the position with respect to start.""" return _ProxyFile.tell(self) - self._start
[ "def", "tell", "(", "self", ")", ":", "return", "_ProxyFile", ".", "tell", "(", "self", ")", "-", "self", ".", "_start" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/mailbox.py#L2028-L2030
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/util.py
python
EventMixin.add
(self, event, subscriber, append=True)
Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend the subscriber to an existing subscriber list for the event.
Add a subscriber for an event.
[ "Add", "a", "subscriber", "for", "an", "event", "." ]
def add(self, event, subscriber, append=True): """ Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend the subscriber to an existing subscriber list for the event. """ subs = self._subscribers if event not in subs: subs[event] = deque([subscriber]) else: sq = subs[event] if append: sq.append(subscriber) else: sq.appendleft(subscriber)
[ "def", "add", "(", "self", ",", "event", ",", "subscriber", ",", "append", "=", "True", ")", ":", "subs", "=", "self", ".", "_subscribers", "if", "event", "not", "in", "subs", ":", "subs", "[", "event", "]", "=", "deque", "(", "[", "subscriber", "]...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/util.py#L846-L864
PanJinquan/tensorflow_models_learning
e7a2773d526e01c76fc8366868099ca3d7a819b4
slim/nets/inception_resnet_v2.py
python
inception_resnet_v2_arg_scope
( weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, activation_fn=tf.nn.relu, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS)
Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. activation_fn: Activation function for conv2d. batch_norm_updates_collections: Collection for the update ops for batch norm. Returns: a arg_scope with the parameters needed for inception_resnet_v2.
Returns the scope with the default parameters for inception_resnet_v2.
[ "Returns", "the", "scope", "with", "the", "default", "parameters", "for", "inception_resnet_v2", "." ]
def inception_resnet_v2_arg_scope( weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, activation_fn=tf.nn.relu, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. activation_fn: Activation function for conv2d. batch_norm_updates_collections: Collection for the update ops for batch norm. Returns: a arg_scope with the parameters needed for inception_resnet_v2. """ # Set weight_decay for weights in conv2d and fully_connected layers. with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), biases_regularizer=slim.l2_regularizer(weight_decay)): batch_norm_params = { 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'updates_collections': batch_norm_updates_collections, 'fused': None, # Use fused batch norm if possible. } # Set activation_fn and parameters for batch_norm. with slim.arg_scope([slim.conv2d], activation_fn=activation_fn, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params) as scope: return scope
[ "def", "inception_resnet_v2_arg_scope", "(", "weight_decay", "=", "0.00004", ",", "batch_norm_decay", "=", "0.9997", ",", "batch_norm_epsilon", "=", "0.001", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "batch_norm_updates_collections", "=", "tf", ...
https://github.com/PanJinquan/tensorflow_models_learning/blob/e7a2773d526e01c76fc8366868099ca3d7a819b4/slim/nets/inception_resnet_v2.py#L368-L402
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/storage/databases/main/search.py
python
SearchBackgroundUpdateStore._background_reindex_gin_search
(self, progress, batch_size)
return 1
This handles old synapses which used GIST indexes, if any; converting them back to be GIN as per the actual schema.
This handles old synapses which used GIST indexes, if any; converting them back to be GIN as per the actual schema.
[ "This", "handles", "old", "synapses", "which", "used", "GIST", "indexes", "if", "any", ";", "converting", "them", "back", "to", "be", "GIN", "as", "per", "the", "actual", "schema", "." ]
async def _background_reindex_gin_search(self, progress, batch_size): """This handles old synapses which used GIST indexes, if any; converting them back to be GIN as per the actual schema. """ def create_index(conn): conn.rollback() # we have to set autocommit, because postgres refuses to # CREATE INDEX CONCURRENTLY without it. conn.set_session(autocommit=True) try: c = conn.cursor() # if we skipped the conversion to GIST, we may already/still # have an event_search_fts_idx; unfortunately postgres 9.4 # doesn't support CREATE INDEX IF EXISTS so we just catch the # exception and ignore it. import psycopg2 try: c.execute( "CREATE INDEX CONCURRENTLY event_search_fts_idx" " ON event_search USING GIN (vector)" ) except psycopg2.ProgrammingError as e: logger.warning( "Ignoring error %r when trying to switch from GIST to GIN", e ) # we should now be able to delete the GIST index. c.execute("DROP INDEX IF EXISTS event_search_fts_idx_gist") finally: conn.set_session(autocommit=False) if isinstance(self.database_engine, PostgresEngine): await self.db_pool.runWithConnection(create_index) await self.db_pool.updates._end_background_update( self.EVENT_SEARCH_USE_GIN_POSTGRES_NAME ) return 1
[ "async", "def", "_background_reindex_gin_search", "(", "self", ",", "progress", ",", "batch_size", ")", ":", "def", "create_index", "(", "conn", ")", ":", "conn", ".", "rollback", "(", ")", "# we have to set autocommit, because postgres refuses to", "# CREATE INDEX CONC...
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/storage/databases/main/search.py#L251-L293
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/urllib2.py
python
request_host
(request)
return host.lower()
Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison.
Return request-host, as defined by RFC 2965.
[ "Return", "request", "-", "host", "as", "defined", "by", "RFC", "2965", "." ]
def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() host = urlparse.urlparse(url)[1] if host == "": host = request.get_header("Host", "") # remove port, if present host = _cut_port_re.sub("", host, 1) return host.lower()
[ "def", "request_host", "(", "request", ")", ":", "url", "=", "request", ".", "get_full_url", "(", ")", "host", "=", "urlparse", ".", "urlparse", "(", "url", ")", "[", "1", "]", "if", "host", "==", "\"\"", ":", "host", "=", "request", ".", "get_header...
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/urllib2.py#L172-L186
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pylibs/win32/gevent/hub.py
python
Hub.run
(self)
Entry-point to running the loop. This method is called automatically when the hub greenlet is scheduled; do not call it directly. :raises LoopExit: If the loop finishes running. This means that there are no other scheduled greenlets, and no active watchers or servers. In some situations, this indicates a programming error.
Entry-point to running the loop. This method is called automatically when the hub greenlet is scheduled; do not call it directly.
[ "Entry", "-", "point", "to", "running", "the", "loop", ".", "This", "method", "is", "called", "automatically", "when", "the", "hub", "greenlet", "is", "scheduled", ";", "do", "not", "call", "it", "directly", "." ]
def run(self): """ Entry-point to running the loop. This method is called automatically when the hub greenlet is scheduled; do not call it directly. :raises LoopExit: If the loop finishes running. This means that there are no other scheduled greenlets, and no active watchers or servers. In some situations, this indicates a programming error. """ assert self is getcurrent(), 'Do not call Hub.run() directly' while True: loop = self.loop loop.error_handler = self try: loop.run() finally: loop.error_handler = None # break the refcount cycle self.parent.throw(LoopExit('This operation would block forever', self))
[ "def", "run", "(", "self", ")", ":", "assert", "self", "is", "getcurrent", "(", ")", ",", "'Do not call Hub.run() directly'", "while", "True", ":", "loop", "=", "self", ".", "loop", "loop", ".", "error_handler", "=", "self", "try", ":", "loop", ".", "run...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pylibs/win32/gevent/hub.py#L652-L670
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/api/v3/snapshots.py
python
SnapshotsController.create
(self, req, body)
return self._view_builder.detail(req, new_snapshot)
Creates a new snapshot.
Creates a new snapshot.
[ "Creates", "a", "new", "snapshot", "." ]
def create(self, req, body): """Creates a new snapshot.""" kwargs = {} context = req.environ['cinder.context'] snapshot = body['snapshot'] kwargs['metadata'] = snapshot.get('metadata', None) volume_id = snapshot['volume_id'] volume = self.volume_api.get(context, volume_id) req_version = req.api_version_request force_flag = snapshot.get('force') force = False if force_flag is not None: # note: this won't raise because it passed schema validation force = strutils.bool_from_string(force_flag, strict=True) if req_version.matches(mv.SNAPSHOT_IN_USE): # strictly speaking, the 'force' flag is invalid for # mv.SNAPSHOT_IN_USE, but we silently ignore a True # value for backward compatibility if force is False: raise exc.HTTPBadRequest( explanation=SNAPSHOT_IN_USE_FLAG_MSG) LOG.info("Create snapshot from volume %s", volume_id) self.validate_name_and_description(snapshot, check_length=False) if 'name' in snapshot: snapshot['display_name'] = snapshot.pop('name') if force: new_snapshot = self.volume_api.create_snapshot_force( context, volume, snapshot.get('display_name'), snapshot.get('description'), **kwargs) else: if req_version.matches(mv.SNAPSHOT_IN_USE): kwargs['allow_in_use'] = True new_snapshot = self.volume_api.create_snapshot( context, volume, snapshot.get('display_name'), snapshot.get('description'), **kwargs) req.cache_db_snapshot(new_snapshot) return self._view_builder.detail(req, new_snapshot)
[ "def", "create", "(", "self", ",", "req", ",", "body", ")", ":", "kwargs", "=", "{", "}", "context", "=", "req", ".", "environ", "[", "'cinder.context'", "]", "snapshot", "=", "body", "[", "'snapshot'", "]", "kwargs", "[", "'metadata'", "]", "=", "sn...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/api/v3/snapshots.py#L147-L195
tartiflette/tartiflette
e292c28ed4fa279ecedb8980fc3741965bd28c87
tartiflette/schema/schema.py
python
GraphQLSchema._validate_arguments_have_valid_type
(self)
return errors
Validates that argument definitions of fields and directives refer to an input type. :return: a list of errors :rtype: List[str]
Validates that argument definitions of fields and directives refer to an input type. :return: a list of errors :rtype: List[str]
[ "Validates", "that", "argument", "definitions", "of", "fields", "and", "directives", "refer", "to", "an", "input", "type", ".", ":", "return", ":", "a", "list", "of", "errors", ":", "rtype", ":", "List", "[", "str", "]" ]
def _validate_arguments_have_valid_type(self) -> List[str]: """ Validates that argument definitions of fields and directives refer to an input type. :return: a list of errors :rtype: List[str] """ errors = [] for gqltype in self.type_definitions.values(): try: for field in gqltype.implemented_fields.values(): for arg in field.arguments.values(): errors.extend( self._validate_type_is_an_input_types( arg, f"Argument < {arg.name} > of Field < {gqltype}.{field.name} >", ) ) except AttributeError: pass for directive in self._directive_definitions.values(): for arg in directive.arguments.values(): errors.extend( self._validate_type_is_an_input_types( arg, f"Argument < {arg.name} > of Directive < {directive.name} >", ) ) return errors
[ "def", "_validate_arguments_have_valid_type", "(", "self", ")", "->", "List", "[", "str", "]", ":", "errors", "=", "[", "]", "for", "gqltype", "in", "self", ".", "type_definitions", ".", "values", "(", ")", ":", "try", ":", "for", "field", "in", "gqltype...
https://github.com/tartiflette/tartiflette/blob/e292c28ed4fa279ecedb8980fc3741965bd28c87/tartiflette/schema/schema.py#L679-L709
sveitser/kaggle_diabetic
e6f1cf3109eaf87db12d77d48f73e62a084fd10a
data.py
python
fast_warp
(img, tf, output_shape, mode='constant', order=0)
return t_img
This wrapper function is faster than skimage.transform.warp
This wrapper function is faster than skimage.transform.warp
[ "This", "wrapper", "function", "is", "faster", "than", "skimage", ".", "transform", ".", "warp" ]
def fast_warp(img, tf, output_shape, mode='constant', order=0): """ This wrapper function is faster than skimage.transform.warp """ m = tf.params t_img = np.zeros((img.shape[0],) + output_shape, img.dtype) for i in range(t_img.shape[0]): t_img[i] = _warp_fast(img[i], m, output_shape=output_shape, mode=mode, order=order) return t_img
[ "def", "fast_warp", "(", "img", ",", "tf", ",", "output_shape", ",", "mode", "=", "'constant'", ",", "order", "=", "0", ")", ":", "m", "=", "tf", ".", "params", "t_img", "=", "np", ".", "zeros", "(", "(", "img", ".", "shape", "[", "0", "]", ","...
https://github.com/sveitser/kaggle_diabetic/blob/e6f1cf3109eaf87db12d77d48f73e62a084fd10a/data.py#L50-L59
harpribot/deep-summarization
9b3bb1daae11a1db2386dbe4a71848714e6127f8
models/stacked_bidirectional.py
python
StackedBidirectional._split_train_tst
(self)
divide the data into training and testing data Create the X_trn, X_tst, for both forward and backward, and Y_trn and Y_tst Note that only the reviews are changed, and not the summary. :return: None
divide the data into training and testing data Create the X_trn, X_tst, for both forward and backward, and Y_trn and Y_tst Note that only the reviews are changed, and not the summary.
[ "divide", "the", "data", "into", "training", "and", "testing", "data", "Create", "the", "X_trn", "X_tst", "for", "both", "forward", "and", "backward", "and", "Y_trn", "and", "Y_tst", "Note", "that", "only", "the", "reviews", "are", "changed", "and", "not", ...
def _split_train_tst(self): """ divide the data into training and testing data Create the X_trn, X_tst, for both forward and backward, and Y_trn and Y_tst Note that only the reviews are changed, and not the summary. :return: None """ num_samples = self.Y.shape[0] mapper_file = self.checkpointer.get_mapper_file_location() if not self.checkpointer.is_mapper_checkpointed(): print 'No mapper checkpoint found. Fresh loading in progress ...' # Now shuffle the data sample_id = range(num_samples) random.shuffle(sample_id) print 'Dumping the mapper shuffle for reuse.' Pickle.dump(sample_id, open(mapper_file, 'wb')) print 'Dump complete. Moving Forward...' else: print 'Mapper Checkpoint found... Reading from mapper dump' sample_id = Pickle.load(open(mapper_file, 'rb')) print 'Mapping unpickling complete.. Moving forward...' self.X_fwd = self.X_fwd[sample_id] self.X_bwd = self.X_bwd[sample_id] self.Y = self.Y[sample_id] # Now divide the data into test ans train set test_fraction = 0.01 self.test_size = int(test_fraction * num_samples) self.train_size = num_samples - self.test_size # Forward review self.X_trn_fwd = self.X_fwd[0:self.train_size] self.X_tst_fwd = self.X_fwd[self.train_size:num_samples] # Backward review self.X_trn_bwd = self.X_bwd[0:self.train_size] self.X_tst_bwd = self.X_bwd[self.train_size:num_samples] # Summary self.Y_trn = self.Y[0:self.train_size] self.Y_tst = self.Y[self.train_size:num_samples]
[ "def", "_split_train_tst", "(", "self", ")", ":", "num_samples", "=", "self", ".", "Y", ".", "shape", "[", "0", "]", "mapper_file", "=", "self", ".", "checkpointer", ".", "get_mapper_file_location", "(", ")", "if", "not", "self", ".", "checkpointer", ".", ...
https://github.com/harpribot/deep-summarization/blob/9b3bb1daae11a1db2386dbe4a71848714e6127f8/models/stacked_bidirectional.py#L57-L95
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/idna/compat.py
python
ToUnicode
(label)
return decode(label)
[]
def ToUnicode(label): return decode(label)
[ "def", "ToUnicode", "(", "label", ")", ":", "return", "decode", "(", "label", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/idna/compat.py#L7-L8
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/elliptic_curves/ell_generic.py
python
EllipticCurve_generic.rst_transform
(self, r, s, t)
return self.change_weierstrass_model(1, r, s, t)
r""" Return the transform of the curve by `(r,s,t)` (with `u=1`). INPUT: - ``r``, ``s``, ``t`` -- three elements of the base ring. OUTPUT: The elliptic curve obtained from self by the standard Weierstrass transformation `(u,r,s,t)` with `u=1`. .. note:: This is just a special case of :meth:`change_weierstrass_model`, with `u=1`. EXAMPLES:: sage: R.<r,s,t>=QQ[] sage: E = EllipticCurve([1,2,3,4,5]) sage: E.rst_transform(r,s,t) Elliptic Curve defined by y^2 + (2*s+1)*x*y + (r+2*t+3)*y = x^3 + (-s^2+3*r-s+2)*x^2 + (3*r^2-r*s-2*s*t+4*r-3*s-t+4)*x + (r^3+2*r^2-r*t-t^2+4*r-3*t+5) over Multivariate Polynomial Ring in r, s, t over Rational Field
r""" Return the transform of the curve by `(r,s,t)` (with `u=1`).
[ "r", "Return", "the", "transform", "of", "the", "curve", "by", "(", "r", "s", "t", ")", "(", "with", "u", "=", "1", ")", "." ]
def rst_transform(self, r, s, t): r""" Return the transform of the curve by `(r,s,t)` (with `u=1`). INPUT: - ``r``, ``s``, ``t`` -- three elements of the base ring. OUTPUT: The elliptic curve obtained from self by the standard Weierstrass transformation `(u,r,s,t)` with `u=1`. .. note:: This is just a special case of :meth:`change_weierstrass_model`, with `u=1`. EXAMPLES:: sage: R.<r,s,t>=QQ[] sage: E = EllipticCurve([1,2,3,4,5]) sage: E.rst_transform(r,s,t) Elliptic Curve defined by y^2 + (2*s+1)*x*y + (r+2*t+3)*y = x^3 + (-s^2+3*r-s+2)*x^2 + (3*r^2-r*s-2*s*t+4*r-3*s-t+4)*x + (r^3+2*r^2-r*t-t^2+4*r-3*t+5) over Multivariate Polynomial Ring in r, s, t over Rational Field """ return self.change_weierstrass_model(1, r, s, t)
[ "def", "rst_transform", "(", "self", ",", "r", ",", "s", ",", "t", ")", ":", "return", "self", ".", "change_weierstrass_model", "(", "1", ",", "r", ",", "s", ",", "t", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/elliptic_curves/ell_generic.py#L1403-L1428
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/contrib/gis/gdal/srs.py
python
SpatialReference.local
(self)
return bool(capi.islocal(self.ptr))
Returns True if this SpatialReference is local (root node is LOCAL_CS).
Returns True if this SpatialReference is local (root node is LOCAL_CS).
[ "Returns", "True", "if", "this", "SpatialReference", "is", "local", "(", "root", "node", "is", "LOCAL_CS", ")", "." ]
def local(self): "Returns True if this SpatialReference is local (root node is LOCAL_CS)." return bool(capi.islocal(self.ptr))
[ "def", "local", "(", "self", ")", ":", "return", "bool", "(", "capi", ".", "islocal", "(", "self", ".", "ptr", ")", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/contrib/gis/gdal/srs.py#L267-L269
thiagopena/djangoSIGE
e32186b27bfd8acf21b0fa400e699cb5c73e5433
djangosige/apps/compras/views/compras.py
python
OrcamentoCompraVencidosListView.view_context
(self, context)
return context
[]
def view_context(self, context): context['title_complete'] = 'ORÇAMENTOS DE COMPRA VENCIDOS' context['add_url'] = reverse_lazy('compras:addorcamentocompraview') return context
[ "def", "view_context", "(", "self", ",", "context", ")", ":", "context", "[", "'title_complete'", "]", "=", "'ORÇAMENTOS DE COMPRA VENCIDOS'", "context", "[", "'add_url'", "]", "=", "reverse_lazy", "(", "'compras:addorcamentocompraview'", ")", "return", "context" ]
https://github.com/thiagopena/djangoSIGE/blob/e32186b27bfd8acf21b0fa400e699cb5c73e5433/djangosige/apps/compras/views/compras.py#L155-L158
araffin/srl-zoo
438a05ab625a2c5ada573b47f73469d92de82132
losses/losses.py
python
perceptualSimilarityLoss
(encoded_real, encoded_prediction, next_encoded_real, next_encoded_prediction, weight, loss_manager)
return weight * pretrained_dae_encoding_loss
Perceptual similarity Loss for VAE as in # "DARLA: Improving Zero-Shot Transfer in Reinforcement Learning", Higgins et al. # see https://arxiv.org/pdf/1707.08475.pdf :param loss_manager: loss criterion needed to log the loss value (LossManager) :param encoded_real: states encoding the real observation by the DAE (th.Tensor) :param encoded_prediction: states encoding the vae's predicted observation by the DAE (th.Tensor) :param next_encoded_real: states encoding the next real observation by the DAE (th.Tensor) :param next_encoded_prediction: states encoding the vae's predicted next observation by the DAE (th.Tensor) :param weight: loss for the DAE's embedding l2 distance (float) :return: (th.Tensor)
Perceptual similarity Loss for VAE as in # "DARLA: Improving Zero-Shot Transfer in Reinforcement Learning", Higgins et al. # see https://arxiv.org/pdf/1707.08475.pdf
[ "Perceptual", "similarity", "Loss", "for", "VAE", "as", "in", "#", "DARLA", ":", "Improving", "Zero", "-", "Shot", "Transfer", "in", "Reinforcement", "Learning", "Higgins", "et", "al", ".", "#", "see", "https", ":", "//", "arxiv", ".", "org", "/", "pdf",...
def perceptualSimilarityLoss(encoded_real, encoded_prediction, next_encoded_real, next_encoded_prediction, weight, loss_manager): """ Perceptual similarity Loss for VAE as in # "DARLA: Improving Zero-Shot Transfer in Reinforcement Learning", Higgins et al. # see https://arxiv.org/pdf/1707.08475.pdf :param loss_manager: loss criterion needed to log the loss value (LossManager) :param encoded_real: states encoding the real observation by the DAE (th.Tensor) :param encoded_prediction: states encoding the vae's predicted observation by the DAE (th.Tensor) :param next_encoded_real: states encoding the next real observation by the DAE (th.Tensor) :param next_encoded_prediction: states encoding the vae's predicted next observation by the DAE (th.Tensor) :param weight: loss for the DAE's embedding l2 distance (float) :return: (th.Tensor) """ pretrained_dae_encoding_loss = F.mse_loss(encoded_real, encoded_prediction, reduction='sum') pretrained_dae_encoding_loss += F.mse_loss(next_encoded_real, next_encoded_prediction, reduction='sum') loss_manager.addToLosses("denoising perceptual similarity", weight, pretrained_dae_encoding_loss) return weight * pretrained_dae_encoding_loss
[ "def", "perceptualSimilarityLoss", "(", "encoded_real", ",", "encoded_prediction", ",", "next_encoded_real", ",", "next_encoded_prediction", ",", "weight", ",", "loss_manager", ")", ":", "pretrained_dae_encoding_loss", "=", "F", ".", "mse_loss", "(", "encoded_real", ","...
https://github.com/araffin/srl-zoo/blob/438a05ab625a2c5ada573b47f73469d92de82132/losses/losses.py#L217-L236
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/ppdet/modeling/backbones/lite_hrnet.py
python
Stem.__init__
(self, in_channel, stem_channel, out_channel, expand_ratio, norm_type='bn', freeze_norm=False, norm_decay=0.)
[]
def __init__(self, in_channel, stem_channel, out_channel, expand_ratio, norm_type='bn', freeze_norm=False, norm_decay=0.): super(Stem, self).__init__() self.conv1 = ConvNormLayer( in_channel, stem_channel, filter_size=3, stride=2, norm_type=norm_type, act='relu', freeze_norm=freeze_norm, norm_decay=norm_decay) mid_channel = int(round(stem_channel * expand_ratio)) branch_channel = stem_channel // 2 if stem_channel == out_channel: inc_channel = out_channel - branch_channel else: inc_channel = out_channel - stem_channel self.branch1 = nn.Sequential( ConvNormLayer( ch_in=branch_channel, ch_out=branch_channel, filter_size=3, stride=2, groups=branch_channel, norm_type=norm_type, freeze_norm=freeze_norm, norm_decay=norm_decay), ConvNormLayer( ch_in=branch_channel, ch_out=inc_channel, filter_size=1, stride=1, norm_type=norm_type, act='relu', freeze_norm=freeze_norm, norm_decay=norm_decay), ) self.expand_conv = ConvNormLayer( ch_in=branch_channel, ch_out=mid_channel, filter_size=1, stride=1, norm_type=norm_type, act='relu', freeze_norm=freeze_norm, norm_decay=norm_decay) self.depthwise_conv = ConvNormLayer( ch_in=mid_channel, ch_out=mid_channel, filter_size=3, stride=2, groups=mid_channel, norm_type=norm_type, freeze_norm=freeze_norm, norm_decay=norm_decay) self.linear_conv = ConvNormLayer( ch_in=mid_channel, ch_out=branch_channel if stem_channel == out_channel else stem_channel, filter_size=1, stride=1, norm_type=norm_type, act='relu', freeze_norm=freeze_norm, norm_decay=norm_decay)
[ "def", "__init__", "(", "self", ",", "in_channel", ",", "stem_channel", ",", "out_channel", ",", "expand_ratio", ",", "norm_type", "=", "'bn'", ",", "freeze_norm", "=", "False", ",", "norm_decay", "=", "0.", ")", ":", "super", "(", "Stem", ",", "self", "...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppdet/modeling/backbones/lite_hrnet.py#L401-L471
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/clients/render/renderer.py
python
RichMediaRenderer.extract_card_info
(self, tag)
return data
[]
def extract_card_info(self, tag): image = None title = None subtitle = None buttons = [] for child in tag.children: if child.name is None: pass elif child.name == 'image': image = child.text elif child.name == 'title': title = child.text elif child.name == 'subtitle': subtitle = child.text elif child.name == 'button': button = self.extract_button_info(child) buttons.append(button) else: outputLog(self, "Unknown card tag [%s]" % child.name) data = {"type": "card", "image": image, "title": title, "subtitle": subtitle, "buttons": buttons} self.extract_class_attr(tag, data) self.extract_id_attr(tag, data) return data
[ "def", "extract_card_info", "(", "self", ",", "tag", ")", ":", "image", "=", "None", "title", "=", "None", "subtitle", "=", "None", "buttons", "=", "[", "]", "for", "child", "in", "tag", ".", "children", ":", "if", "child", ".", "name", "is", "None",...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/clients/render/renderer.py#L200-L230
snakeztc/NeuralDialog-ZSDG
1d1548457a16a2e07567dc8532ea8b2fba178540
zsdg/nn_lib.py
python
AttnConnector.forward
(self, queries, keys, contents)
return new_s
[]
def forward(self, queries, keys, contents): batch_size = keys.size(0) num_key = keys.size(1) query_embeded = self.query_embed(queries) key_embeded = self.key_embed(keys) tiled_query = query_embeded.unsqueeze(1).repeat(1, num_key, 1) fc1 = F.tanh(tiled_query + key_embeded) attn = self.attn_w(fc1).squeeze(-1) attn = F.sigmoid(attn.view(-1, num_key)).view(batch_size, -1, num_key) mix = torch.bmm(attn, contents).squeeze(1) out = torch.cat([mix, queries], dim=1) if self.rnn_cell == 'lstm': h = self.project_h(out).unsqueeze(0) c = self.project_c(out).unsqueeze(0) new_s = (h, c) else: new_s = self.project(out).unsqueeze(0) return new_s
[ "def", "forward", "(", "self", ",", "queries", ",", "keys", ",", "contents", ")", ":", "batch_size", "=", "keys", ".", "size", "(", "0", ")", "num_key", "=", "keys", ".", "size", "(", "1", ")", "query_embeded", "=", "self", ".", "query_embed", "(", ...
https://github.com/snakeztc/NeuralDialog-ZSDG/blob/1d1548457a16a2e07567dc8532ea8b2fba178540/zsdg/nn_lib.py#L77-L98
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/numpy/ma/extras.py
python
unique
(ar1, return_index=False, return_inverse=False)
return output
Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays.
Finds the unique elements of an array.
[ "Finds", "the", "unique", "elements", "of", "an", "array", "." ]
def unique(ar1, return_index=False, return_inverse=False): """ Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays. """ output = np.unique(ar1, return_index=return_index, return_inverse=return_inverse) if isinstance(output, tuple): output = list(output) output[0] = output[0].view(MaskedArray) output = tuple(output) else: output = output.view(MaskedArray) return output
[ "def", "unique", "(", "ar1", ",", "return_index", "=", "False", ",", "return_inverse", "=", "False", ")", ":", "output", "=", "np", ".", "unique", "(", "ar1", ",", "return_index", "=", "return_index", ",", "return_inverse", "=", "return_inverse", ")", "if"...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/numpy/ma/extras.py#L1065-L1086
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/Team.py
python
Team.get_repos
(self)
return github.PaginatedList.PaginatedList( github.Repository.Repository, self._requester, self.url + "/repos", None )
:calls: `GET /teams/:id/repos <http://developer.github.com/v3/orgs/teams>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
:calls: `GET /teams/:id/repos <http://developer.github.com/v3/orgs/teams>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
[ ":", "calls", ":", "GET", "/", "teams", "/", ":", "id", "/", "repos", "<http", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "orgs", "/", "teams", ">", "_", ":", "rtype", ":", ":", "class", ":", "github", ".", "PaginatedList"...
def get_repos(self): """ :calls: `GET /teams/:id/repos <http://developer.github.com/v3/orgs/teams>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository` """ return github.PaginatedList.PaginatedList( github.Repository.Repository, self._requester, self.url + "/repos", None )
[ "def", "get_repos", "(", "self", ")", ":", "return", "github", ".", "PaginatedList", ".", "PaginatedList", "(", "github", ".", "Repository", ".", "Repository", ",", "self", ".", "_requester", ",", "self", ".", "url", "+", "\"/repos\"", ",", "None", ")" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/Team.py#L305-L312
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/poplib.py
python
POP3.retr
(self, which)
return self._longcmd('RETR %s' % which)
Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets].
Retrieve whole message number 'which'.
[ "Retrieve", "whole", "message", "number", "which", "." ]
def retr(self, which): """Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets]. """ return self._longcmd('RETR %s' % which)
[ "def", "retr", "(", "self", ",", "which", ")", ":", "return", "self", ".", "_longcmd", "(", "'RETR %s'", "%", "which", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/poplib.py#L248-L253
EtienneCmb/visbrain
b599038e095919dc193b12d5e502d127de7d03c9
visbrain/objects/roi_obj.py
python
RoiObj.reset
(self)
Reset the RoiObject.
Reset the RoiObject.
[ "Reset", "the", "RoiObject", "." ]
def reset(self): """Reset the RoiObject.""" self.analysis = self._analysis_backup
[ "def", "reset", "(", "self", ")", ":", "self", ".", "analysis", "=", "self", ".", "_analysis_backup" ]
https://github.com/EtienneCmb/visbrain/blob/b599038e095919dc193b12d5e502d127de7d03c9/visbrain/objects/roi_obj.py#L240-L242
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/Mask RCNN/CharlesShang_FastMaskRCNN/libs/layers/anchor.py
python
decode
(boxes, scores, all_anchors, ih, iw)
return final_boxes, classes, scores
Decode outputs into boxes Parameters --------- boxes: an array of shape (1, h, w, Ax4) scores: an array of shape (1, h, w, Ax2), all_anchors: an array of shape (1, h, w, Ax4), [x1, y1, x2, y2] Returns -------- final_boxes: of shape (R x 4) classes: of shape (R) in {0,1,2,3... K-1} scores: of shape (R) in [0 ~ 1]
Decode outputs into boxes Parameters --------- boxes: an array of shape (1, h, w, Ax4) scores: an array of shape (1, h, w, Ax2), all_anchors: an array of shape (1, h, w, Ax4), [x1, y1, x2, y2] Returns -------- final_boxes: of shape (R x 4) classes: of shape (R) in {0,1,2,3... K-1} scores: of shape (R) in [0 ~ 1]
[ "Decode", "outputs", "into", "boxes", "Parameters", "---------", "boxes", ":", "an", "array", "of", "shape", "(", "1", "h", "w", "Ax4", ")", "scores", ":", "an", "array", "of", "shape", "(", "1", "h", "w", "Ax2", ")", "all_anchors", ":", "an", "array...
def decode(boxes, scores, all_anchors, ih, iw): """Decode outputs into boxes Parameters --------- boxes: an array of shape (1, h, w, Ax4) scores: an array of shape (1, h, w, Ax2), all_anchors: an array of shape (1, h, w, Ax4), [x1, y1, x2, y2] Returns -------- final_boxes: of shape (R x 4) classes: of shape (R) in {0,1,2,3... K-1} scores: of shape (R) in [0 ~ 1] """ # h, w = boxes.shape[1], boxes.shape[2] # if all_anchors is None: # stride = 2 ** int(round(np.log2((iw + 0.0) / w))) # all_anchors = anchors_plane(h, w, stride=stride) all_anchors = all_anchors.reshape((-1, 4)) boxes = boxes.reshape((-1, 4)) scores = scores.reshape((-1, 2)) assert scores.shape[0] == boxes.shape[0] == all_anchors.shape[0], \ 'Anchor layer shape error %d vs %d vs %d' % (scores.shape[0],boxes.shape[0],all_anchors.reshape[0]) boxes = bbox_transform_inv(all_anchors, boxes) classes = np.argmax(scores, axis=1) scores = scores[:, 1] final_boxes = boxes final_boxes = clip_boxes(final_boxes, (ih, iw)) classes = classes.astype(np.int32) return final_boxes, classes, scores
[ "def", "decode", "(", "boxes", ",", "scores", ",", "all_anchors", ",", "ih", ",", "iw", ")", ":", "# h, w = boxes.shape[1], boxes.shape[2]", "# if all_anchors is None:", "# stride = 2 ** int(round(np.log2((iw + 0.0) / w)))", "# all_anchors = anchors_plane(h, w, stride=stride)"...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/Mask RCNN/CharlesShang_FastMaskRCNN/libs/layers/anchor.py#L138-L167
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
python/dgl/nn/pytorch/conv/edgeconv.py
python
EdgeConv.forward
(self, g, feat)
Description ----------- Forward computation Parameters ---------- g : DGLGraph The graph. feat : Tensor or pair of tensors :math:`(N, D)` where :math:`N` is the number of nodes and :math:`D` is the number of feature dimensions. If a pair of tensors is given, the graph must be a uni-bipartite graph with only one edge type, and the two tensors must have the same dimensionality on all except the first axis. Returns ------- torch.Tensor New node features. Raises ------ DGLError If there are 0-in-degree nodes in the input graph, it will raise DGLError since no message will be passed to those nodes. This will cause invalid output. The error can be ignored by setting ``allow_zero_in_degree`` parameter to ``True``.
[]
def forward(self, g, feat): """ Description ----------- Forward computation Parameters ---------- g : DGLGraph The graph. feat : Tensor or pair of tensors :math:`(N, D)` where :math:`N` is the number of nodes and :math:`D` is the number of feature dimensions. If a pair of tensors is given, the graph must be a uni-bipartite graph with only one edge type, and the two tensors must have the same dimensionality on all except the first axis. Returns ------- torch.Tensor New node features. Raises ------ DGLError If there are 0-in-degree nodes in the input graph, it will raise DGLError since no message will be passed to those nodes. This will cause invalid output. The error can be ignored by setting ``allow_zero_in_degree`` parameter to ``True``. """ with g.local_scope(): if not self._allow_zero_in_degree: if (g.in_degrees() == 0).any(): raise DGLError('There are 0-in-degree nodes in the graph, ' 'output for those nodes will be invalid. ' 'This is harmful for some applications, ' 'causing silent performance regression. ' 'Adding self-loop on the input graph by ' 'calling `g = dgl.add_self_loop(g)` will resolve ' 'the issue. Setting ``allow_zero_in_degree`` ' 'to be `True` when constructing this module will ' 'suppress the check and let the code run.') h_src, h_dst = expand_as_pair(feat, g) g.srcdata['x'] = h_src g.dstdata['x'] = h_dst g.apply_edges(fn.v_sub_u('x', 'x', 'theta')) g.edata['theta'] = self.theta(g.edata['theta']) g.dstdata['phi'] = self.phi(g.dstdata['x']) if not self.batch_norm: g.update_all(fn.e_add_v('theta', 'phi', 'e'), fn.max('e', 'x')) else: g.apply_edges(fn.e_add_v('theta', 'phi', 'e')) # Although the official implementation includes a per-edge # batch norm within EdgeConv, I choose to replace it with a # global batch norm for a number of reasons: # # (1) When the point clouds within each batch do not have the # same number of points, batch norm would not work. # # (2) Even if the point clouds always have the same number of # points, the points may as well be shuffled even with the # same (type of) object (and the official implementation # *does* shuffle the points of the same example for each # epoch). # # For example, the first point of a point cloud of an # airplane does not always necessarily reside at its nose. # # In this case, the learned statistics of each position # by batch norm is not as meaningful as those learned from # images. g.edata['e'] = self.bn(g.edata['e']) g.update_all(fn.copy_e('e', 'e'), fn.max('e', 'x')) return g.dstdata['x']
[ "def", "forward", "(", "self", ",", "g", ",", "feat", ")", ":", "with", "g", ".", "local_scope", "(", ")", ":", "if", "not", "self", ".", "_allow_zero_in_degree", ":", "if", "(", "g", ".", "in_degrees", "(", ")", "==", "0", ")", ".", "any", "(", ...
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/nn/pytorch/conv/edgeconv.py#L128-L203
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/fabmetheus_utilities/svg_reader.py
python
SVGReader.getRotatedLoopLayer
(self)
return self.rotatedLoopLayers[-1]
Return the rotated loop layer.
Return the rotated loop layer.
[ "Return", "the", "rotated", "loop", "layer", "." ]
def getRotatedLoopLayer(self): "Return the rotated loop layer." if self.z != None: rotatedLoopLayer = euclidean.RotatedLoopLayer( self.z ) self.rotatedLoopLayers.append( rotatedLoopLayer ) rotatedLoopLayer.rotation = self.bridgeRotation self.z = None return self.rotatedLoopLayers[-1]
[ "def", "getRotatedLoopLayer", "(", "self", ")", ":", "if", "self", ".", "z", "!=", "None", ":", "rotatedLoopLayer", "=", "euclidean", ".", "RotatedLoopLayer", "(", "self", ".", "z", ")", "self", ".", "rotatedLoopLayers", ".", "append", "(", "rotatedLoopLayer...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/svg_reader.py#L862-L869
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/redis/client.py
python
BasePipeline.__exit__
(self, exc_type, exc_value, traceback)
[]
def __exit__(self, exc_type, exc_value, traceback): self.reset()
[ "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_value", ",", "traceback", ")", ":", "self", ".", "reset", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/redis/client.py#L2646-L2647
python-discord/bot
26c5587ac13e5414361bb6e7ada42983b81014d2
bot/exts/info/doc/_cog.py
python
DocCog.set_command
( self, ctx: commands.Context, package_name: PackageName, inventory: Inventory, base_url: ValidURL = "", )
Adds a new documentation metadata object to the site's database. The database will update the object, should an existing item with the specified `package_name` already exist. If the base url is not specified, a default created by removing the last segment of the inventory url is used. Example: !docs setdoc \ python \ https://docs.python.org/3/objects.inv
Adds a new documentation metadata object to the site's database.
[ "Adds", "a", "new", "documentation", "metadata", "object", "to", "the", "site", "s", "database", "." ]
async def set_command( self, ctx: commands.Context, package_name: PackageName, inventory: Inventory, base_url: ValidURL = "", ) -> None: """ Adds a new documentation metadata object to the site's database. The database will update the object, should an existing item with the specified `package_name` already exist. If the base url is not specified, a default created by removing the last segment of the inventory url is used. Example: !docs setdoc \ python \ https://docs.python.org/3/objects.inv """ if base_url and not base_url.endswith("/"): raise commands.BadArgument("The base url must end with a slash.") inventory_url, inventory_dict = inventory body = { "package": package_name, "base_url": base_url, "inventory_url": inventory_url } try: await self.bot.api_client.post("bot/documentation-links", json=body) except ResponseCodeError as err: if err.status == 400 and "already exists" in err.response_json.get("package", [""])[0]: log.info(f"Ignoring HTTP 400 as package {package_name} has already been added.") await ctx.send(f"Package {package_name} has already been added.") return raise log.info( f"User @{ctx.author} ({ctx.author.id}) added a new documentation package:\n" + "\n".join(f"{key}: {value}" for key, value in body.items()) ) if not base_url: base_url = self.base_url_from_inventory_url(inventory_url) self.update_single(package_name, base_url, inventory_dict) await ctx.send(f"Added the package `{package_name}` to the database and updated the inventories.")
[ "async", "def", "set_command", "(", "self", ",", "ctx", ":", "commands", ".", "Context", ",", "package_name", ":", "PackageName", ",", "inventory", ":", "Inventory", ",", "base_url", ":", "ValidURL", "=", "\"\"", ",", ")", "->", "None", ":", "if", "base_...
https://github.com/python-discord/bot/blob/26c5587ac13e5414361bb6e7ada42983b81014d2/bot/exts/info/doc/_cog.py#L374-L417
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/nose/tools/nontrivial.py
python
nottest
(func)
return func
Decorator to mark a function or method as *not* a test
Decorator to mark a function or method as *not* a test
[ "Decorator", "to", "mark", "a", "function", "or", "method", "as", "*", "not", "*", "a", "test" ]
def nottest(func): """Decorator to mark a function or method as *not* a test """ func.__test__ = False return func
[ "def", "nottest", "(", "func", ")", ":", "func", ".", "__test__", "=", "False", "return", "func" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/nose/tools/nontrivial.py#L147-L151
mcneel/rhinoscriptsyntax
c49bd0bf24c2513bdcb84d1bf307144489600fd9
Scripts/rhinoscript/document.py
python
RenderMeshMaxAspectRatio
(ratio=None)
return rc
Returns or sets the render mesh maximum aspect ratio property of the active document. For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file. Parameters: ratio (number, optional): the render mesh maximum aspect ratio. The suggested range, when not zero, is from 1 to 100. Returns: number: if ratio is not specified, the current render mesh maximum aspect ratio if successful. number: if ratio is specified, the previous render mesh maximum aspect ratio if successful. None: if not successful, or on error. Example: import rhinoscriptsyntax as rs print("Quality: %s" % rs.RenderMeshQuality()) print("Mesh density: %s" % rs.RenderMeshDensity()) print("Maximum angle: %s" % rs.RenderMeshMaxAngle()) print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio()) print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength()) print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength()) print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf()) print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads()) print("Other settings: %s" % rs.RenderMeshSettings()) See Also: RenderMeshDensity RenderMeshMaxAngle RenderMeshMaxAspectRatio RenderMeshMaxDistEdgeToSrf RenderMeshMaxEdgeLength RenderMeshMinEdgeLength RenderMeshMinInitialGridQuads RenderMeshQuality RenderMeshSettings
Returns or sets the render mesh maximum aspect ratio property of the active document. For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file. Parameters: ratio (number, optional): the render mesh maximum aspect ratio. The suggested range, when not zero, is from 1 to 100. Returns: number: if ratio is not specified, the current render mesh maximum aspect ratio if successful. number: if ratio is specified, the previous render mesh maximum aspect ratio if successful. None: if not successful, or on error. Example: import rhinoscriptsyntax as rs print("Quality: %s" % rs.RenderMeshQuality()) print("Mesh density: %s" % rs.RenderMeshDensity()) print("Maximum angle: %s" % rs.RenderMeshMaxAngle()) print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio()) print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength()) print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength()) print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf()) print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads()) print("Other settings: %s" % rs.RenderMeshSettings()) See Also: RenderMeshDensity RenderMeshMaxAngle RenderMeshMaxAspectRatio RenderMeshMaxDistEdgeToSrf RenderMeshMaxEdgeLength RenderMeshMinEdgeLength RenderMeshMinInitialGridQuads RenderMeshQuality RenderMeshSettings
[ "Returns", "or", "sets", "the", "render", "mesh", "maximum", "aspect", "ratio", "property", "of", "the", "active", "document", ".", "For", "more", "information", "on", "render", "meshes", "see", "the", "Document", "Properties", ":", "Mesh", "topic", "in", "t...
def RenderMeshMaxAspectRatio(ratio=None): """Returns or sets the render mesh maximum aspect ratio property of the active document. For more information on render meshes, see the Document Properties: Mesh topic in the Rhino help file. Parameters: ratio (number, optional): the render mesh maximum aspect ratio. The suggested range, when not zero, is from 1 to 100. Returns: number: if ratio is not specified, the current render mesh maximum aspect ratio if successful. number: if ratio is specified, the previous render mesh maximum aspect ratio if successful. None: if not successful, or on error. Example: import rhinoscriptsyntax as rs print("Quality: %s" % rs.RenderMeshQuality()) print("Mesh density: %s" % rs.RenderMeshDensity()) print("Maximum angle: %s" % rs.RenderMeshMaxAngle()) print("Maximum aspect ratio: %s" % rs.RenderMeshMaxAspectRatio()) print("Minimun edge length: %s" % rs.RenderMeshMinEdgeLength()) print("Maximum edge length: %s" % rs.RenderMeshMaxEdgeLength()) print("Maximum distance, edge to surface: %s" % rs.RenderMeshMaxDistEdgeToSrf()) print("Minumum initial grid quads: %s" % rs.RenderMeshMinInitialGridQuads()) print("Other settings: %s" % rs.RenderMeshSettings()) See Also: RenderMeshDensity RenderMeshMaxAngle RenderMeshMaxAspectRatio RenderMeshMaxDistEdgeToSrf RenderMeshMaxEdgeLength RenderMeshMinEdgeLength RenderMeshMinInitialGridQuads RenderMeshQuality RenderMeshSettings """ current = scriptcontext.doc.GetCurrentMeshingParameters() rc = current.GridAspectRatio if ratio is not None: current.GridAspectRatio = ratio _SetRenderMeshAndUpdateStyle(current) return rc
[ "def", "RenderMeshMaxAspectRatio", "(", "ratio", "=", "None", ")", ":", "current", "=", "scriptcontext", ".", "doc", ".", "GetCurrentMeshingParameters", "(", ")", "rc", "=", "current", ".", "GridAspectRatio", "if", "ratio", "is", "not", "None", ":", "current",...
https://github.com/mcneel/rhinoscriptsyntax/blob/c49bd0bf24c2513bdcb84d1bf307144489600fd9/Scripts/rhinoscript/document.py#L372-L408
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/pip/_vendor/requests/models.py
python
Response.json
(self, **kwargs)
return complexjson.loads(self.text, **kwargs)
Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
Returns the json-encoded content of a response, if any.
[ "Returns", "the", "json", "-", "encoded", "content", "of", "a", "response", "if", "any", "." ]
def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads( self.content.decode(encoding), **kwargs ) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return complexjson.loads(self.text, **kwargs)
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "self", ".", "content", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should ex...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/pip/_vendor/requests/models.py#L803-L826
asweigart/PythonStdioGames
8bdabf93e6b1bb6af3e26fea24da93f85e8314b6
src/gamesbyexample/chancecheckers.py
python
displayBoard
(board)
Display the board data structure on the screen.
Display the board data structure on the screen.
[ "Display", "the", "board", "data", "structure", "on", "the", "screen", "." ]
def displayBoard(board): """Display the board data structure on the screen.""" spaces = [] # Contains all the characters to display at each space. for row in range(1, 9): if row % 2 == 0: for column in EVEN_CHECKER_COLUMNS: spaces.append(board[column + str(row)]) else: for column in ODD_CHECKER_COLUMNS: spaces.append(board[column + str(row)]) print(""" A B C D E F G H +---+---+---+---+---+---+---+---+ 1 | | {} | | {} | | {} | | {} | 1 +---+---+---+---+---+---+---+---+ 2 | {} | | {} | | {} | | {} | | 2 +---+---+---+---+---+---+---+---+ 3 | | {} | | {} | | {} | | {} | 3 +---+---+---+---+---+---+---+---+ 4 | {} | | {} | | {} | | {} | | 4 +---+---+---+---+---+---+---+---+ 5 | | {} | | {} | | {} | | {} | 5 +---+---+---+---+---+---+---+---+ 6 | {} | | {} | | {} | | {} | | 6 +---+---+---+---+---+---+---+---+ 7 | | {} | | {} | | {} | | {} | 7 +---+---+---+---+---+---+---+---+ 8 | {} | | {} | | {} | | {} | | 8 +---+---+---+---+---+---+---+---+ A B C D E F G H""".format(*spaces))
[ "def", "displayBoard", "(", "board", ")", ":", "spaces", "=", "[", "]", "# Contains all the characters to display at each space.", "for", "row", "in", "range", "(", "1", ",", "9", ")", ":", "if", "row", "%", "2", "==", "0", ":", "for", "column", "in", "E...
https://github.com/asweigart/PythonStdioGames/blob/8bdabf93e6b1bb6af3e26fea24da93f85e8314b6/src/gamesbyexample/chancecheckers.py#L72-L102
flaskbb/flaskbb
de13a37fcb713b9c627632210ab9a7bb980d591f
flaskbb/plugins/spec.py
python
flaskbb_email_updated
(user, email_update)
Hook for responding to a user updating their email. This hook is called after the email change has been persisted:: @impl def flaskbb_email_updated(app): send_email( "Email changed", [email_change.old_email], text_body=..., html_body=... ) See also :class:`~flaskbb.core.changesets.ChangeSetPostProcessor`. :param user: The user whose email was updated. :param email_update: The change set applied to the user.
Hook for responding to a user updating their email. This hook is called after the email change has been persisted::
[ "Hook", "for", "responding", "to", "a", "user", "updating", "their", "email", ".", "This", "hook", "is", "called", "after", "the", "email", "change", "has", "been", "persisted", "::" ]
def flaskbb_email_updated(user, email_update): """ Hook for responding to a user updating their email. This hook is called after the email change has been persisted:: @impl def flaskbb_email_updated(app): send_email( "Email changed", [email_change.old_email], text_body=..., html_body=... ) See also :class:`~flaskbb.core.changesets.ChangeSetPostProcessor`. :param user: The user whose email was updated. :param email_update: The change set applied to the user. """
[ "def", "flaskbb_email_updated", "(", "user", ",", "email_update", ")", ":" ]
https://github.com/flaskbb/flaskbb/blob/de13a37fcb713b9c627632210ab9a7bb980d591f/flaskbb/plugins/spec.py#L672-L691
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/YOLO/YOLO_tensorflow/YOLO_face_tf.py
python
YOLO_TF.conv_layer
(self,idx,inputs,filters,size,stride)
return tf.maximum(self.alpha*conv_biased,conv_biased,name=str(idx)+'_leaky_relu')
[]
def conv_layer(self,idx,inputs,filters,size,stride): channels = inputs.get_shape()[3] weight = tf.Variable(tf.truncated_normal([size,size,int(channels),filters], stddev=0.1)) biases = tf.Variable(tf.constant(0.1, shape=[filters])) pad_size = size//2 pad_mat = np.array([[0,0],[pad_size,pad_size],[pad_size,pad_size],[0,0]]) inputs_pad = tf.pad(inputs,pad_mat) conv = tf.nn.conv2d(inputs_pad, weight, strides=[1, stride, stride, 1], padding='VALID',name=str(idx)+'_conv') conv_biased = tf.add(conv,biases,name=str(idx)+'_conv_biased') if self.disp_console : print ' Layer %d : Type = Conv, Size = %d * %d, Stride = %d, Filters = %d, Input channels = %d' % (idx,size,size,stride,filters,int(channels)) return tf.maximum(self.alpha*conv_biased,conv_biased,name=str(idx)+'_leaky_relu')
[ "def", "conv_layer", "(", "self", ",", "idx", ",", "inputs", ",", "filters", ",", "size", ",", "stride", ")", ":", "channels", "=", "inputs", ".", "get_shape", "(", ")", "[", "3", "]", "weight", "=", "tf", ".", "Variable", "(", "tf", ".", "truncate...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/YOLO/YOLO_tensorflow/YOLO_face_tf.py#L71-L83
HazyResearch/fonduer
c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd
src/fonduer/parser/visual_parser/visual_parser.py
python
VisualParser.is_parsable
(self, document_name: str)
Check if visual information can be parsed. :param document_name: the document name. :return: Whether visual information is parsable.
Check if visual information can be parsed.
[ "Check", "if", "visual", "information", "can", "be", "parsed", "." ]
def is_parsable(self, document_name: str) -> bool: """Check if visual information can be parsed. :param document_name: the document name. :return: Whether visual information is parsable. """ pass
[ "def", "is_parsable", "(", "self", ",", "document_name", ":", "str", ")", "->", "bool", ":", "pass" ]
https://github.com/HazyResearch/fonduer/blob/c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd/src/fonduer/parser/visual_parser/visual_parser.py#L26-L32
pyglet/pyglet
2833c1df902ca81aeeffa786c12e7e87d402434b
pyglet/extlibs/png.py
python
rescale_rows
(rows, rescale)
Take each row in rows (an iterator) and yield a fresh row with the pixels scaled according to the rescale parameters in the list `rescale`. Each element of `rescale` is a tuple of (source_bitdepth, target_bitdepth), with one element per channel.
Take each row in rows (an iterator) and yield a fresh row with the pixels scaled according to the rescale parameters in the list `rescale`. Each element of `rescale` is a tuple of (source_bitdepth, target_bitdepth), with one element per channel.
[ "Take", "each", "row", "in", "rows", "(", "an", "iterator", ")", "and", "yield", "a", "fresh", "row", "with", "the", "pixels", "scaled", "according", "to", "the", "rescale", "parameters", "in", "the", "list", "rescale", ".", "Each", "element", "of", "res...
def rescale_rows(rows, rescale): """ Take each row in rows (an iterator) and yield a fresh row with the pixels scaled according to the rescale parameters in the list `rescale`. Each element of `rescale` is a tuple of (source_bitdepth, target_bitdepth), with one element per channel. """ # One factor for each channel fs = [float(2 ** s[1] - 1)/float(2 ** s[0] - 1) for s in rescale] # Assume all target_bitdepths are the same target_bitdepths = set(s[1] for s in rescale) assert len(target_bitdepths) == 1 (target_bitdepth, ) = target_bitdepths typecode = 'BH'[target_bitdepth > 8] # Number of channels n_chans = len(rescale) for row in rows: rescaled_row = array(typecode, iter(row)) for i in range(n_chans): channel = array( typecode, (int(round(fs[i] * x)) for x in row[i::n_chans])) rescaled_row[i::n_chans] = channel yield rescaled_row
[ "def", "rescale_rows", "(", "rows", ",", "rescale", ")", ":", "# One factor for each channel", "fs", "=", "[", "float", "(", "2", "**", "s", "[", "1", "]", "-", "1", ")", "/", "float", "(", "2", "**", "s", "[", "0", "]", "-", "1", ")", "for", "...
https://github.com/pyglet/pyglet/blob/2833c1df902ca81aeeffa786c12e7e87d402434b/pyglet/extlibs/png.py#L928-L958