_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q54300 | SearchInFiles.__replace_within_document | train | def __replace_within_document(self, document, occurrences, replacement_pattern):
"""
Replaces given pattern occurrences in given document using given settings.
:param document: Document.
:type document: QTextDocument
:param replacement_pattern: Replacement pattern.
:type... | python | {
"resource": ""
} |
q54301 | SearchInFiles.__interrupt_search | train | def __interrupt_search(self):
"""
Interrupt the current search.
"""
if self.__search_worker_thread:
self.__search_worker_thread.quit()
self.__search_worker_thread.wait()
self.__container.engine.stop_processing(warning=False) | python | {
"resource": ""
} |
q54302 | SearchInFiles.__cache | train | def __cache(self, file, content, document):
"""
Caches given file.
:param file: File to cache.
:type file: unicode
:param content: File content.
:type content: list
:param document: File document.
:type document: QTextDocument
"""
self.__... | python | {
"resource": ""
} |
q54303 | SearchInFiles.__uncache | train | def __uncache(self, file):
"""
Uncaches given file.
:param file: File to uncache.
:type file: unicode
"""
if file in self.__files_cache:
self.__files_cache.remove_content(file) | python | {
"resource": ""
} |
q54304 | SearchInFiles.set_search_results | train | def set_search_results(self, search_results):
"""
Sets the Model Nodes using given search results.
:param search_results: Search results.
:type search_results: list
:return: Method success.
:rtype: bool
"""
root_node = umbra.ui.nodes.DefaultNode(name="In... | python | {
"resource": ""
} |
q54305 | SearchInFiles.set_replace_results | train | def set_replace_results(self, replace_results):
"""
Sets the Model Nodes using given replace results.
:param replace_results: Replace results.
:type replace_results: list
:return: Method success.
:rtype: bool
"""
root_node = umbra.ui.nodes.DefaultNode(na... | python | {
"resource": ""
} |
q54306 | SearchInFiles.search | train | def search(self):
"""
Searchs user defined locations for search pattern.
:return: Method success.
:rtype: bool
"""
self.__interrupt_search()
search_pattern = self.Search_comboBox.currentText()
replacement_pattern = self.Replace_With_comboBox.currentText... | python | {
"resource": ""
} |
q54307 | SearchInFiles.replace | train | def replace(self, nodes):
"""
Replaces user defined files search pattern occurrences with replacement pattern using given nodes.
:param nodes: Nodes.
:type nodes: list
:return: Method success.
:rtype: bool
"""
files = {}
for node in nodes:
... | python | {
"resource": ""
} |
q54308 | SearchInFiles.save_files | train | def save_files(self, nodes):
"""
Saves user defined files using give nodes.
:param nodes: Nodes.
:type nodes: list
:return: Method success.
:rtype: bool
"""
metrics = {"Opened": 0, "Cached": 0}
for node in nodes:
file = node.file
... | python | {
"resource": ""
} |
q54309 | get_service | train | def get_service():
"""Load the configured service."""
global _SERVICE_MANAGER
if _SERVICE_MANAGER is None:
_SERVICE_MANAGER = driver.DriverManager(
namespace='tvrenamer.data.services',
name=cfg.CONF.lookup_service,
invoke_on_load=True)
return _SERVICE_MANAGER... | python | {
"resource": ""
} |
q54310 | UserService.get_user_id | train | def get_user_id(self, mxit_id, scope='profile/public'):
"""
Retrieve the Mxit user's internal "user ID"
No user authentication required
"""
user_id = _get(
token=self.oauth.get_app_token(scope),
uri='/user/lookup/' + urllib.quote(mxit_id)
)
... | python | {
"resource": ""
} |
q54311 | UserService.get_status | train | def get_status(self, mxit_id, scope='profile/public'):
"""
Retrieve the Mxit user's current status
No user authentication required
"""
status = _get(
token=self.oauth.get_app_token(scope),
uri='/user/public/statusmessage/' + urllib.quote(mxit_id)
)... | python | {
"resource": ""
} |
q54312 | UserService.get_display_name | train | def get_display_name(self, mxit_id, scope='profile/public'):
"""
Retrieve the Mxit user's display name
No user authentication required
"""
display_name = _get(
token=self.oauth.get_app_token(scope),
uri='/user/public/displayname/' + urllib.quote(mxit_id)
... | python | {
"resource": ""
} |
q54313 | UserService.get_avatar | train | def get_avatar(self, mxit_id, output_file_path=None, scope='profile/public'):
"""
Retrieve the Mxit user's avatar
No user authentication required
"""
data = _get(
token=self.oauth.get_app_token(scope),
uri='/user/public/avatar/' + urllib.quote(mxit_id)
... | python | {
"resource": ""
} |
q54314 | UserService.get_basic_profile | train | def get_basic_profile(self, user_id, scope='profile/public'):
"""
Retrieve the Mxit user's basic profile
No user authentication required
"""
profile = _get(
token=self.oauth.get_app_token(scope),
uri='/user/profile/' + urllib.quote(user_id)
)
... | python | {
"resource": ""
} |
q54315 | UserService.upload_file_and_send_file_offer | train | def upload_file_and_send_file_offer(self, file_name, user_id, data=None, input_file_path=None,
content_type='application/octet-stream', auto_open=False,
prevent_share=False, scope='content/send'):
"""
Upload a file of any ty... | python | {
"resource": ""
} |
q54316 | UserService.get_cover_image | train | def get_cover_image(self, output_file_path=None, scope='profile/public'):
"""
Retrieve the Mxit user's cover image
No user authentication required
"""
data = _get(
token=self.oauth.get_user_token(scope),
uri='/user/cover'
)
if output_file_... | python | {
"resource": ""
} |
q54317 | run | train | def run(quiet, args):
"""Run a local command.
Examples:
$ django run manage.py runserver
...
"""
if not args:
raise ClickException('pass a command to run')
cmd = ' '.join(args)
application = get_current_application()
name = application.name
settings = os.environ.get('... | python | {
"resource": ""
} |
q54318 | auto | train | def auto():
"""set colouring on if STDOUT is a terminal device, off otherwise"""
try:
Style.enabled = False
Style.enabled = sys.stdout.isatty()
except (AttributeError, TypeError):
pass | python | {
"resource": ""
} |
q54319 | create_anchor_from_header | train | def create_anchor_from_header(header, existing_anchors=None):
"""
Creates GitHub style auto-generated anchor tags from header line strings
:param header: The portion of the line that should be converted
:param existing_anchors: A dictionary of AnchorHub tags to auto-generated
anchors
:retur... | python | {
"resource": ""
} |
q54320 | _provider_state_fixtures_with_params | train | def _provider_state_fixtures_with_params(
provider_state_fixture_by_descriptor: Dict[str, ProviderStateFixture],
provider_states: Tuple[ProviderState, ...]
) -> List[Tuple[ProviderStateFixture, Dict]]:
"""Get a list of provider states fixtures for an interaction with their parameters.
Raises an ... | python | {
"resource": ""
} |
q54321 | _pluck_parameter_names | train | def _pluck_parameter_names(provider_state_fixture: Callable) -> FrozenSet[str]:
"""Pluck the parameter names of a function.
>>> def hello(name: str, yell: bool = False) -> str:
... greeting = f'Hello {name}!'; return greeting.upper() if yell else greeting
>>> _pluck_parameter_names(hello) == frozen... | python | {
"resource": ""
} |
q54322 | _use_provider_states | train | def _use_provider_states(
provider_state_fixtures_with_params: List[Tuple[ProviderStateFixture, Dict]]
) -> Generator:
"""Run all given provider states as a contextmanager."""
with contextlib.ExitStack() as stack:
for provider_state_fixture, params in provider_state_fixtures_with_params:
... | python | {
"resource": ""
} |
q54323 | current_offset | train | def current_offset(local_tz=None):
"""
Returns current utcoffset for a timezone. Uses
DEFAULT_LOCAL_TZ by default. That value can be
changed at runtime using the func below.
"""
if local_tz is None:
local_tz = DEFAULT_LOCAL_TZ
dt = local_tz.localize(datetime.now())
return dt.utco... | python | {
"resource": ""
} |
q54324 | Episode.status | train | def status(self):
"""Provides current status of processing episode.
Structure of status:
original_filename => formatted_filename, state, messages
:returns: mapping of current processing state
:rtype: dict
"""
return {
self.original: {
... | python | {
"resource": ""
} |
q54325 | Episode.parse | train | def parse(self):
"""Extracts component keys from filename.
:raises tvrenamer.exceptions.InvalidFilename:
when filename was not parseable
:raises tvrenamer.exceptions.ConfigValueError:
when regex used for parsing was incorrectly configured
"""
self.clean_... | python | {
"resource": ""
} |
q54326 | Episode.enhance | train | def enhance(self):
"""Load metadata from a data service to improve naming.
:raises tvrenamer.exceptions.ShowNotFound:
when unable to find show/series name based on parsed name
:raises tvrenamer.exceptions.EpisodeNotFound:
when unable to find episode name(s) based on pars... | python | {
"resource": ""
} |
q54327 | Episode.format_name | train | def format_name(self):
"""Formats the media file based on enhanced metadata.
The actual name of the file and even the name of the directory
structure where the file is to be stored.
"""
self.formatted_filename = formatter.format_filename(
self.series_name, self.seaso... | python | {
"resource": ""
} |
q54328 | Episode.rename | train | def rename(self):
"""Renames media file to formatted name.
After parsing data from initial media filename and searching
for additional data to using a data service, a formatted
filename will be generated and the media file will be renamed
to the generated name and optionally rel... | python | {
"resource": ""
} |
q54329 | Client.create_bundle | train | def create_bundle(self, name=None, media_url=None,
audio_channel=None, metadata=None, notify_url=None,
external_id=None):
"""Create a new bundle.
'metadata' may be None, or an object that can be converted to a JSON
string. See API documentation for r... | python | {
"resource": ""
} |
q54330 | Client.delete_bundle | train | def delete_bundle(self, href=None):
"""
Delete a bundle.
:param href: the relative href to the bundle.
:type href: string, may not be None
:return: nothing
:raises APIException: If the response code is not 204.
"""
# Argument error checking.
asse... | python | {
"resource": ""
} |
q54331 | Client.get_bundle | train | def get_bundle(self, href=None, embed_tracks=False,
embed_metadata=False, embed_insights=False):
"""Get a bundle.
'href' the relative href to the bundle. May not be None.
'embed_tracks' determines whether or not to include track
information in the response.
'e... | python | {
"resource": ""
} |
q54332 | Client.update_bundle | train | def update_bundle(self, href=None, name=None,
notify_url=None, version=None,
external_id=None):
"""Update a bundle. Note that only the 'name' and 'notify_url' can
be update.
'href' the relative href to the bundle. May not be None.
'name' the ... | python | {
"resource": ""
} |
q54333 | Client.update_metadata | train | def update_metadata(self, href=None, metadata=None, version=None):
"""Update the metadata in a bundle.
'href' the relative href to the metadata. May not be None.
'metadata' may be None, or an object that can be converted to a
JSON string. See API documentation for restrictions. The
... | python | {
"resource": ""
} |
q54334 | Client.delete_metadata | train | def delete_metadata(self, href=None):
"""Delete metadata.
'href' the relative href to the bundle. May not be None.
Returns nothing.
If the response status is not 204, throws an APIException."""
# Argument error checking.
assert href is not None
raw_result = s... | python | {
"resource": ""
} |
q54335 | Client.create_track | train | def create_track(self, href=None, media_url=None, label=None,
audio_channel=None):
"""Add a new track to a bundle. Note that the total number of
allowable tracks is limited. See the API documentation for
details.
'href' the relative href to the tracks list. May not... | python | {
"resource": ""
} |
q54336 | Client.delete_track_at_index | train | def delete_track_at_index(self, href=None, index=None):
"""Delete a track, or all the tracks.
'href' the relative href to the track list. May not be None.
'index' the index of the track to delete. If none is given,
all tracks are deleted.
Returns nothing.
If the respon... | python | {
"resource": ""
} |
q54337 | Client.delete_track | train | def delete_track(self, href=None):
"""Delete a track.
'href' the relative index of the track. May not be none.
Returns nothing.
If the response status is not 204, throws and APIException."""
# Argument error checking.
assert href is not None
raw_result = self... | python | {
"resource": ""
} |
q54338 | Client.request_insight | train | def request_insight(self, href, insight):
"""Requests an insight to be run.
Normally insights are set to automatically run so you will NOT need
to call this method -- use get_insight() instead.
However, non-autorun insights can be requested using this method (for
example high-ac... | python | {
"resource": ""
} |
q54339 | Client.get_data | train | def get_data(self, href=None):
"""Gets data from an insight with data links such as captions.
'href' the relative href to the data. May not be None.
Returns the content of the data as a string.
If the response status is not 2xx, throws an APIException.
"""
# Argument ... | python | {
"resource": ""
} |
q54340 | Client._get_simple_model | train | def _get_simple_model(self, href=None):
"""Get a model
'href' the relative href to the model. May not be None.
Returns a data structure equivalent to the JSON returned by the
API.
If the response status is not 2xx, throws an APIException.
If the JSON to python data str... | python | {
"resource": ""
} |
q54341 | Client.search | train | def search(self, href=None,
query=None, query_fields=None, query_filter=None,
limit=None, embed_items=None, embed_tracks=None,
embed_metadata=None, embed_insights=None, language=None):
"""Search a media collection.
'href' the relative href to the bundle lis... | python | {
"resource": ""
} |
q54342 | Client._search_p1 | train | def _search_p1(self, query=None, query_fields=None, query_filter=None,
limit=None, embed_items=None, embed_tracks=None,
embed_metadata=None, embed_insights=None, language=None):
"""Function called to retrieve the first page."""
# Prepare the data we're going to inc... | python | {
"resource": ""
} |
q54343 | Client._search_pn | train | def _search_pn(self, href=None, limit=None,
embed_items=None, embed_tracks=None, embed_metadata=None,
embed_insights=None):
"""Function called to retrieve pages 2-n."""
url_components = urlparse(href)
path = url_components.path
data = parse_qs(url_c... | python | {
"resource": ""
} |
q54344 | Client.get | train | def get(self, path, data=None):
"""Executes a GET.
'path' may not be None. Should include the full path to the
resource.
'data' may be None or a dictionary. These values will be
appended to the path as key/value pairs.
Returns a named tuple that includes:
statu... | python | {
"resource": ""
} |
q54345 | Client.delete | train | def delete(self, path, data=None):
"""Executes a DELETE.
'path' may not be None. Should include the full path to the
resoure.
'data' may be None or a dictionary.
Returns a named tuple that includes:
status: the HTTP status code
json: the returned JSON-HAL
... | python | {
"resource": ""
} |
q54346 | Client.put | train | def put(self, path, data):
"""Executes a PUT.
'path' may not be None. Should include the full path to the
resoure.
'data' may be None or a dictionary.
Returns a named tuple that includes:
status: the HTTP status code
json: the returned JSON-HAL
If the ... | python | {
"resource": ""
} |
q54347 | Client._parse_json | train | def _parse_json(self, jstring=None):
"""Parse jstring and return a Python data structure.
'jstring' a string of JSON. May not be None.
Returns a Python data structure.
If jstring couldn't be parsed, raises an APIDataException."""
# Argument error checking.
assert jstr... | python | {
"resource": ""
} |
q54348 | APIException.get_status | train | def get_status(self):
"""Return the status embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed."""
result = ''
if self._data_struct is not None:
result = self._data_struct[KEY_STATUS]
return result | python | {
"resource": ""
} |
q54349 | APIException.get_message | train | def get_message(self):
"""Return the message embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed."""
result = ''
if self._data_struct is not None:
result = self._data_struct[KEY_MESSAGE]
return result | python | {
"resource": ""
} |
q54350 | APIException.get_code | train | def get_code(self):
"""Return the code embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed. This
should always match the 'http_response'."""
result = ''
if self._data_struct is not None:
result = self._data_struct[KEY_CODE]
... | python | {
"resource": ""
} |
q54351 | RFFeatures.rank_features | train | def rank_features(self, inputs: pd.DataFrame, targets: pd.DataFrame, problem_type='classification') -> pd.DataFrame:
""" Rank features using Random Forest classifier and the recursive feature elimination
"""
try:
X = normalize( \
inputs.apply(pd.to_n... | python | {
"resource": ""
} |
q54352 | get_story | train | def get_story(new):
"""Return a story of the given ID."""
url = URLS['item'].format(new)
try:
data = req.get(url)
except req.ConnectionError:
raise
except req.Timeout:
raise req.Timeout('A timeout problem occurred.')
except req.TooManyRedirects:
raise req.TooManyR... | python | {
"resource": ""
} |
q54353 | create_list_stories | train | def create_list_stories(
list_id_stories, number_of_stories, shuffle, max_threads
):
"""Show in a formatted way the stories for each item of the list."""
list_stories = []
with ThreadPoolExecutor(max_workers=max_threads) as executor:
futures = {
executor.submit(get_story, new)
... | python | {
"resource": ""
} |
q54354 | MagBlock.rot | train | def rot(inputArray, theta=0, pc=(0, 0)):
""" rotate input array with angle of theta
:param inputArray: input array or list,
e.g. np.array([[0,0],[0,1],[0,2]]) or [[0,0],[0,1],[0,2]]
:param theta: rotation angle in degree
:param pc: central point coords (x,y) r... | python | {
"resource": ""
} |
q54355 | MagBlock.str2dict | train | def str2dict(istr):
""" translate string into dict
:param istr: string with format like: "k1=v1, k2=v2" ...
:return: dict
"""
if 'lattice' not in istr.lower():
tmpstr = istr.replace(',', '=').split('=')
else:
tmpstr = istr.split('=')
k = [... | python | {
"resource": ""
} |
q54356 | MagBlock.setConf | train | def setConf(self, conf, type='simu'):
""" set information for different type dict,
:param conf: configuration information, str or dict
:param type: simu, ctrl, misc
"""
if conf is None:
return
else:
if isinstance(conf, str):
conf =... | python | {
"resource": ""
} |
q54357 | MagBlock.printConfig | train | def printConfig(self, type='simu'):
""" print information about element
:param type: comm, simu, ctrl, misc, all
"""
print("{s1}{s2:^22s}{s1}".format(s1="-" * 10, s2="Configuration START"))
print("Element name: {en} ({cn})".format(en=self.name, cn=self.__class__.__name__))
... | python | {
"resource": ""
} |
q54358 | MagBlock.getConfig | train | def getConfig(self, type='online', format='elegant'):
""" only dump configuration part, dict
:param type: comm, simu, ctrl, misc, all, online (default)
:param format: elegant/mad, elegant by default
"""
return list(list(self.dumpConfigDict[type](format).values())[0].values())[0] | python | {
"resource": ""
} |
q54359 | MagBlock._printCtrlConf | train | def _printCtrlConf(self):
""" get PV value and print out
"""
if self.ctrlinfo:
print("Control configs:")
for k, v in sorted(self.ctrlinfo.items(), reverse=True):
pv = v['pv']
rval = epics.caget(pv)
if rval is None:
... | python | {
"resource": ""
} |
q54360 | MagBlock.showDraw | train | def showDraw(self, fignum=1):
""" show the element drawing
:param fignum: define figure number to show element drawing
"""
if self._patches == []:
print("Please setDraw() before showDraw(), then try again.")
return
else:
fig = plt.figure(fignu... | python | {
"resource": ""
} |
q54361 | ElementQuad.getK1 | train | def getK1(self, type='simu'):
""" get quad k1 value
:param type: 'simu' or 'online'
:return: quad strength,i.e. k1
"""
if type == 'ctrl':
pv = self.ctrlinfo.get('k1')['pv']
rval = epics.caget(pv)
if rval is None:
val = self.get... | python | {
"resource": ""
} |
q54362 | FD.get_fixture | train | def get_fixture(self, fixture_id, head2head=None):
"""
Loads a single fixture.
Args:
* fixture_id (str): the id of the fixture
* head2head (int, optional): load the previous n fixture of the two teams
Returns:
* :obj: json: the fixture-json
"... | python | {
"resource": ""
} |
q54363 | FD.get_players | train | def get_players(self, team):
"""
Loads the players of a team.
Args:
* team (:obj: json): a team in json format obtained from the service.
Returns:
* :obj: json: the players of the team
"""
team_id = self.__get_team_id(team)
self.logger.de... | python | {
"resource": ""
} |
q54364 | Configuration.append_rows | train | def append_rows(self, rows, between, refresh_presision):
"""Transform the rows of data to Measurements.
Keyword arguments:
rows -- an array of arrays [datetime, integral_measurement]
between -- time between integral_measurements in seconds
refresh_presision -- time between sensor values that compose the ... | python | {
"resource": ""
} |
q54365 | Configuration.go_inactive | train | def go_inactive(self, dt=datetime.utcnow().replace(tzinfo=pytz.UTC)):
"""Make the configuration object inactive.
Keyword arguments:
dt -- datetime of the moment when the configuration go inactive
"""
self.end = dt
self.save() | python | {
"resource": ""
} |
q54366 | Configuration.register_measurements | train | def register_measurements(self, end, rows, between, refresh_presision):
"""Register the measurements if it has measurements and close the configuration, if it hasen't got measurements clean the temporal file on disk.
Keyword arguments:
f -- open memory file
end -- datetime of the moment when the configurati... | python | {
"resource": ""
} |
q54367 | Configuration.get_backup_filename | train | def get_backup_filename(self, path):
"""Proposes a name for the backup file.
Keyword arguments:
path -- temporal filename
"""
head = datetime.utcnow().replace(tzinfo=pytz.UTC).strftime("%Y%m%d%H%M%S")
self.backup = "stations/backup/%s.%s" % (head, path)
return self.backup | python | {
"resource": ""
} |
q54368 | Configuration.save | train | def save(self, *args, **kwargs):
""" On save, update timestamps """
now = datetime.utcnow().replace(tzinfo=pytz.UTC)
if not self.pk:
self.created = now
self.modified = now
return super(Configuration, self).save(*args, **kwargs) | python | {
"resource": ""
} |
q54369 | Measurement.register_or_check | train | def register_or_check(klass, finish, mean, between, refresh_presision, configuration):
"""Return the active configurations."""
m, created = klass.objects.get_or_create(finish=finish, configuration=configuration)
if created:
m.mean=mean
m.between=between
m.refresh_presision=refresh_presision
m.save()
... | python | {
"resource": ""
} |
q54370 | main | train | def main():
# config file
conf = Config()
actions = []
debuglevel = logging.ERROR
for it in sys.argv[1:]:
if it == ("-v"):
debuglevel = logging.WARNING
elif it == ("-vv"):
debuglevel = logging.INFO
elif it == ("-vvv"):
debuglevel = logging... | python | {
"resource": ""
} |
q54371 | get_allowed | train | def get_allowed(allow, disallow):
""" Normalize the given string attributes as a list of all allowed vClasses."""
if allow is None and disallow is None:
return SUMO_VEHICLE_CLASSES
elif disallow is None:
return allow.split()
else:
disallow = disallow.split()
return tuple(... | python | {
"resource": ""
} |
q54372 | addJunctionPos | train | def addJunctionPos(shape, fromPos, toPos):
"""Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality"""
result = list(shape)
if fromPos != shape[0]:
result = [fromPos] + result
if toPos != shape[-1... | python | {
"resource": ""
} |
q54373 | Lane.getShape | train | def getShape(self, includeJunctions=False):
"""Returns the shape of the lane in 2d.
This function returns the shape of the lane, as defined in the net.xml
file. The returned shape is a list containing numerical
2-tuples representing the x,y coordinates of the shape points.
For ... | python | {
"resource": ""
} |
q54374 | Lane.getShape3D | train | def getShape3D(self, includeJunctions=False):
"""Returns the shape of the lane in 3d.
This function returns the shape of the lane, as defined in the net.xml
file. The returned shape is a list containing numerical
3-tuples representing the x,y,z coordinates of the shape points
wh... | python | {
"resource": ""
} |
q54375 | get_expressions | train | def get_expressions():
"""Retrieve compiled pattern expressions.
:returns: compiled regular expressions for supported filename formats
:rtype: list
"""
if len(_EXPRESSIONS) == len(FILENAME_PATTERNS):
return _EXPRESSIONS
for cpattern in FILENAME_PATTERNS:
_EXPRESSIONS.append(re... | python | {
"resource": ""
} |
q54376 | BaseJSONRPCSerializer.json_dumps | train | def json_dumps(cls, obj, **kwargs):
"""
A rewrap of json.dumps done for one reason - to inject a custom `cls` kwarg
:param obj:
:param kwargs:
:return:
:rtype: str
"""
if 'cls' not in kwargs:
kwargs['cls'] = cls.json_encoder
return jso... | python | {
"resource": ""
} |
q54377 | BaseJSONRPCSerializer.json_loads | train | def json_loads(cls, s, **kwargs):
"""
A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg
:param s:
:param kwargs:
:return:
:rtype: dict
"""
if 'cls' not in kwargs:
kwargs['cls'] = cls.json_decoder
return json.l... | python | {
"resource": ""
} |
q54378 | JSONRPC10Serializer.assemble_notification_request | train | def assemble_notification_request(method, params=tuple()):
"""serialize a JSON-RPC-Notification
:Parameters: see dumps_request
:Returns: | {"method": "...", "params": ..., "id": null}
| "method", "params" and "id" are always in this order.
:Raises: see dumps_req... | python | {
"resource": ""
} |
q54379 | JSONRPC10Serializer.parse_request | train | def parse_request(cls, jsonrpc_message):
"""We take apart JSON-RPC-formatted message as a string and decompose it
into a dictionary object, emitting errors if parsing detects issues with
the format of the message.
:Returns: | [method_name, params, id] or [method_name, params]
... | python | {
"resource": ""
} |
q54380 | TokenFactory.create | train | def create(self):
"""Creates a token
It uses the app_name as the notes and the scopes are
the permissions required by the application. See those
in github when configuring an app token
Raises a TFARequired if a two factor is required after
the atempt to create it withou... | python | {
"resource": ""
} |
q54381 | make_github_markdown_writer | train | def make_github_markdown_writer(opts):
"""
Creates a Writer object used for parsing and writing Markdown files with
a GitHub style anchor transformation
opts is a namespace object containing runtime options. It should
generally include the following attributes:
* 'open': a string correspondi... | python | {
"resource": ""
} |
q54382 | Protocol.make_connection | train | def make_connection(self, transport, address):
"""Called externally when the transport is ready."""
self.connected = True
self.transport = transport
self.connection_made(address) | python | {
"resource": ""
} |
q54383 | make_command_table | train | def make_command_table(entry_points):
"""
Return a nicely formatted table of all the PIP commands installed on this
system to incorporate into the help text. The table will have two columns.
The first will list the commands that comprise the main pipeline and the
second will list all the other ... | python | {
"resource": ""
} |
q54384 | did_you_mean | train | def did_you_mean(unknown_command, entry_points):
"""
Return the command with the name most similar to what the user typed. This
is used to suggest a correct command when the user types an illegal
command.
"""
from difflib import SequenceMatcher
similarity = lambda x: SequenceMatcher(None,... | python | {
"resource": ""
} |
q54385 | notify_exception_handler | train | def notify_exception_handler(*args):
"""
Provides a notifier exception handler.
:param \*args: Arguments.
:type \*args: \*
:return: Definition success.
:rtype: bool
"""
callback = RuntimeGlobals.components_manager["factory.script_editor"].restore_development_layout
foundations.exce... | python | {
"resource": ""
} |
q54386 | Blockchain.blocks | train | def blocks(self, start=None, stop=None):
""" Yields blocks starting from ``start``.
:param int start: Starting block
:param int stop: Stop at this block
:param str mode: We here have the choice between
* "head": the last block
* "irreversibl... | python | {
"resource": ""
} |
q54387 | Blockchain.stream | train | def stream(self, filter_by=list(), *args, **kwargs):
""" Yield a stream of blocks
:param array filter_by: List of operations to filter for, e.g.
vote, comment, transfer, transfer_to_vesting,
withdraw_vesting, limit_order_create, limit_order_cancel,
fe... | python | {
"resource": ""
} |
q54388 | Blockchain.replay | train | def replay(self, start_block=1, end_block=None, filter_by=list(), **kwargs):
""" Same as ``stream`` with different prototyp
"""
return self.stream(
filter_by=filter_by,
start=start_block,
stop=end_block,
mode=self.mode,
**kwargs
... | python | {
"resource": ""
} |
q54389 | Blockchain.get_block_from_time | train | def get_block_from_time(self, timestring, error_margin=10):
""" Estimate block number from given time
:param str timestring: String representing time
:param int error_margin: Estimate block number within this interval (in seconds)
"""
known_block = self.get_current_bloc... | python | {
"resource": ""
} |
q54390 | toCSV | train | def toCSV(pdl,out=None,write_field_names=True):
"""Conversion from the PyDbLite Base instance pdl to the file object out
open for writing in binary mode
If out is not specified, the field name is the same as the PyDbLite
file with extension .csv
If write_field_names is True, field names are wri... | python | {
"resource": ""
} |
q54391 | in_period | train | def in_period(period, dt=None):
"""
Determines if a datetime is within a certain time period. If the time
is omitted the current time will be used.
in_period return True is the datetime is within the time period, False if not.
If the expression is malformed a TimePeriod.InvalidFormat exception
... | python | {
"resource": ""
} |
q54392 | _parse_scale | train | def _parse_scale(scale_exp):
"""Parses a scale expression and returns the scale, and a list of ranges."""
m = re.search("(\w+?)\{(.*?)\}", scale_exp)
if m is None:
raise InvalidFormat('Unable to parse the given time period.')
scale = m.group(1)
range = m.group(2)
if scale not in SCALES... | python | {
"resource": ""
} |
q54393 | VCSCommandsBuilder.tag | train | def tag(version, params):
"""Build and return full command to use with subprocess.Popen for 'git tag' command
:param version:
:param params:
:return: list
"""
cmd = ['git', 'tag', '-a', '-m', 'v%s' % version, str(version)]
if params:
cmd.extend(params... | python | {
"resource": ""
} |
q54394 | VCSEngine.create_tag | train | def create_tag(self, version, params):
"""Create VCS tag
:param version:
:param params:
:return:
"""
cmd = self._command.tag(version, params)
(code, stdout, stderr) = self._exec(cmd)
if code:
raise errors.VCSError('Can\'t create VCS tag %s. ... | python | {
"resource": ""
} |
q54395 | VCSEngine.raise_if_cant_commit | train | def raise_if_cant_commit(self):
"""Verify VCS status and raise an error if commit is disallowed
:return:
"""
cmd = self._command.status()
(code, stdout, stderr) = self._exec(cmd)
if code:
raise errors.VCSError('Can\'t verify VCS status. Process exited with ... | python | {
"resource": ""
} |
q54396 | VCSEngine.add_to_stage | train | def add_to_stage(self, paths):
"""Stage given files
:param paths:
:return:
"""
cmd = self._command.add(paths)
(code, stdout, stderr) = self._exec(cmd)
if code:
raise errors.VCSError('Can\'t add paths to VCS. Process exited with code %d and message: ... | python | {
"resource": ""
} |
q54397 | EchoClientProtocol.connection_made | train | def connection_made(self, address):
"""When the connection is made, send something."""
logger.info("connection made to {}".format(address))
self.count = 0
self.connected = True
self.transport.write(b'Echo Me') | python | {
"resource": ""
} |
q54398 | serialize | train | def serialize(template, options=SerializerOptions()):
"""Serialize the provided template according to the language
specifications."""
context = SerializerContext(options)
context.serialize(flatten(template))
return context.output | python | {
"resource": ""
} |
q54399 | SerializerContext.write | train | def write(self, string):
"""Print provided string to the output."""
self._output += self._options.indentation_character * \
self._indentation + string + '\n' | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.