_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q37200
Partition.update_id
train
def update_id(self, sequence_id=None): """Alter the sequence id, and all of the names and ids derived from it. This often needs to be done after an IntegrityError in a multiprocessing run""" if sequence_id: self.sequence_id = sequence_id self._set_ids(force=True) i...
python
{ "resource": "" }
q37201
Partition._update_names
train
def _update_names(self): """Update the derived names""" d = dict( table=self.table_name, time=self.time, space=self.space, grain=self.grain, variant=self.variant, segment=self.segment ) assert self.dataset ...
python
{ "resource": "" }
q37202
AnalysisPartition.dataframe
train
def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None): """Return the partition as a Pandas dataframe :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param filtered_column...
python
{ "resource": "" }
q37203
AnalysisPartition.patches
train
def patches(self, basemap, simplify=None, predicate=None, args_f=None, **kwargs): """ Return geodata as a list of Matplotlib patches :param basemap: A mpl_toolkits.basemap.Basemap :param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry. ...
python
{ "resource": "" }
q37204
MeasureDimensionPartition.measures
train
def measures(self): """Iterate over all measures""" from ambry.valuetype.core import ROLE return [c for c in self.columns if c.role == ROLE.MEASURE]
python
{ "resource": "" }
q37205
MeasureDimensionPartition.measure
train
def measure(self, vid): """Return a measure, given its vid or another reference""" from ambry.orm import Column if isinstance(vid, PartitionColumn): return vid elif isinstance(vid, Column): return PartitionColumn(vid) else: return PartitionCo...
python
{ "resource": "" }
q37206
MeasureDimensionPartition.dimension_set
train
def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set()): """ Return a dict that describes the combination of one or two dimensions, for a plot :param p_dim: :param s_dim: :param dimensions: :param extant: :return: """ if not dim...
python
{ "resource": "" }
q37207
PartitionColumn.label
train
def label(self): """"Return first child that of the column that is marked as a label""" for c in self.table.columns: if c.parent == self.name and 'label' in c.valuetype: return PartitionColumn(c, self._partition)
python
{ "resource": "" }
q37208
PartitionColumn.value_labels
train
def value_labels(self): """Return a map of column code values mapped to labels, for columns that have a label column If the column is not assocaited with a label column, it returns an identity map. WARNING! This reads the whole partition, so it is really slow """ from operato...
python
{ "resource": "" }
q37209
list_build_configuration_sets
train
def list_build_configuration_sets(page_size=200, page_index=0, sort="", q=""): """ List all build configuration sets """ data = list_build_configuration_sets_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
{ "resource": "" }
q37210
create_build_configuration_set_raw
train
def create_build_configuration_set_raw(**kwargs): """ Create a new BuildConfigurationSet. """ config_set = _create_build_config_set_object(**kwargs) response = utils.checked_api_call(pnc_api.build_group_configs, 'create_new', body=config_set) if response: return response.content
python
{ "resource": "" }
q37211
update_build_configuration_set
train
def update_build_configuration_set(id, **kwargs): """ Update a BuildConfigurationSet """ data = update_build_configuration_set_raw(id, **kwargs) if data: return utils.format_json(data)
python
{ "resource": "" }
q37212
list_build_configurations_for_set
train
def list_build_configurations_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all build configurations in a given BuildConfigurationSet. """ content = list_build_configurations_for_set_raw(id, name, page_size, page_index, sort, q) if content: return utils.fo...
python
{ "resource": "" }
q37213
add_build_configuration_to_set
train
def add_build_configuration_to_set( set_id=None, set_name=None, config_id=None, config_name=None): """ Add a build configuration to an existing BuildConfigurationSet """ content = add_build_configuration_to_set_raw(set_id, set_name, config_id, config_name) if content: return utils.fo...
python
{ "resource": "" }
q37214
list_build_records_for_set
train
def list_build_records_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all build records for a BuildConfigurationSet """ content = list_build_records_for_set_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content)
python
{ "resource": "" }
q37215
list_build_set_records
train
def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all build set records for a BuildConfigurationSet """ content = list_build_set_records_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content)
python
{ "resource": "" }
q37216
AnyUrlField.register_model
train
def register_model(cls, ModelClass, form_field=None, widget=None, title=None, prefix=None): """ Register a model to use in the URL field. This function needs to be called once for every model that should be selectable in the URL field. :param ModelClass: The model to register. ...
python
{ "resource": "" }
q37217
AnyUrlField.resolve_objects
train
def resolve_objects(cls, objects, skip_cached_urls=False): """ Make sure all AnyUrlValue objects from a set of objects is resolved in bulk. This avoids making a query per item. :param objects: A list or queryset of models. :param skip_cached_urls: Whether to avoid prefetching da...
python
{ "resource": "" }
q37218
config
train
def config(path=None, root=None, db=None): """Return the default run_config object for this installation.""" import ambry.run return ambry.run.load(path=path, root=root, db=db)
python
{ "resource": "" }
q37219
get_library
train
def get_library(path=None, root=None, db=None): import ambry.library as _l """Return the default library for this installation.""" rc = config(path=path, root=root, db=db ) return _l.new_library(rc)
python
{ "resource": "" }
q37220
doc_parser
train
def doc_parser(): """Utility function to allow getting the arguments for a single command, for Sphinx documentation""" parser = argparse.ArgumentParser( prog='ambry', description='Ambry {}. Management interface for ambry, libraries ' 'and repositories. '.format(ambry._meta._...
python
{ "resource": "" }
q37221
get_extra_commands
train
def get_extra_commands(): """Use the configuration to discover additional CLI packages to load""" from ambry.run import find_config_file from ambry.dbexceptions import ConfigurationError from ambry.util import yaml try: plugins_dir = find_config_file('cli.yaml') except ConfigurationErro...
python
{ "resource": "" }
q37222
NSongModel.url
train
def url(self): """ We will always check if this song file exists in local library, if true, we return the url of the local file. .. note:: As netease song url will be expired after a period of time, we can not use static url here. Currently, we assume that the ...
python
{ "resource": "" }
q37223
get_handler
train
def get_handler(progname, fmt=None, datefmt=None, project_id=None, credentials=None, debug_thread_worker=False, **_): """Helper function to create a Stackdriver handler. See `ulogger.stackdriver.CloudLoggingHandlerBuilder` for arguments and supported keyword arguments. Returns: ...
python
{ "resource": "" }
q37224
CloudLoggingHandlerBuilder._create_gcl_resource
train
def _create_gcl_resource(self): """Create a configured Resource object. The logging.resource.Resource object enables GCL to filter and bucket incoming logs according to which resource (host) they're coming from. Returns: (obj): Instance of `google.cloud.logging.reso...
python
{ "resource": "" }
q37225
CloudLoggingHandlerBuilder.get_formatter
train
def get_formatter(self): """Create a fully configured `logging.Formatter` Example of formatted log message: 2017-08-27T20:19:24.424 cpm-example-gew1 progname (23123): hello Returns: (obj): Instance of `logging.Formatter` """ if not self.fmt: self...
python
{ "resource": "" }
q37226
CloudLoggingHandlerBuilder._set_worker_thread_level
train
def _set_worker_thread_level(self): """Sets logging level of the background logging thread to DEBUG or INFO """ bthread_logger = logging.getLogger( 'google.cloud.logging.handlers.transports.background_thread') if self.debug_thread_worker: bthread_logger.setLevel(l...
python
{ "resource": "" }
q37227
CloudLoggingHandlerBuilder.get_handler
train
def get_handler(self): """Create a fully configured CloudLoggingHandler. Returns: (obj): Instance of `google.cloud.logging.handlers. CloudLoggingHandler` """ gcl_client = gcl_logging.Client( project=self.project_id, credentials=se...
python
{ "resource": "" }
q37228
Search.index_dataset
train
def index_dataset(self, dataset, force=False): """ Adds given dataset to the index. """ self.backend.dataset_index.index_one(dataset, force=force)
python
{ "resource": "" }
q37229
Search.index_partition
train
def index_partition(self, partition, force=False): """ Adds given partition to the index. """ self.backend.partition_index.index_one(partition, force=force)
python
{ "resource": "" }
q37230
Search.index_library_datasets
train
def index_library_datasets(self, tick_f=None): """ Indexes all datasets of the library. Args: tick_f (callable, optional): callable of one argument. Gets string with index state. """ dataset_n = 0 partition_n = 0 def tick(d, p): if tick_f: ...
python
{ "resource": "" }
q37231
Search.search_datasets
train
def search_datasets(self, search_phrase, limit=None): """ Search for datasets. """ return self.backend.dataset_index.search(search_phrase, limit=limit)
python
{ "resource": "" }
q37232
Search.search
train
def search(self, search_phrase, limit=None): """Search for datasets, and expand to database records""" from ambry.identity import ObjectNumber from ambry.orm.exc import NotFoundError from ambry.library.search_backends.base import SearchTermParser results = [] stp = Sear...
python
{ "resource": "" }
q37233
Search.get_parsed_query
train
def get_parsed_query(self): """ Returns string with last query parsed. Assuming called after search_datasets.""" return '{} OR {}'.format( self.backend.dataset_index.get_parsed_query()[0], self.backend.partition_index.get_parsed_query()[0])
python
{ "resource": "" }
q37234
list_build_configuration_set_records
train
def list_build_configuration_set_records(page_size=200, page_index=0, sort="", q=""): """ List all build configuration set records. """ data = list_build_configuration_set_records_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
{ "resource": "" }
q37235
list_records_for_build_config_set
train
def list_records_for_build_config_set(id, page_size=200, page_index=0, sort="", q=""): """ Get a list of BuildRecords for the given BuildConfigSetRecord """ data = list_records_for_build_config_set_raw(id, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
{ "resource": "" }
q37236
AbstractProvider.auth_as
train
def auth_as(self, user): """auth as a user temporarily""" old_user = self._user self.auth(user) try: yield finally: self.auth(old_user)
python
{ "resource": "" }
q37237
LibraryConfigSyncProxy.sync_accounts
train
def sync_accounts(self, accounts_data, clear = False, password=None, cb = None): """ Load all of the accounts from the account section of the config into the database. :param accounts_data: :param password: :return: """ # Map common values into the accou...
python
{ "resource": "" }
q37238
robust_int
train
def robust_int(v): """Parse an int robustly, ignoring commas and other cruft. """ if isinstance(v, int): return v if isinstance(v, float): return int(v) v = str(v).replace(',', '') if not v: return None return int(v)
python
{ "resource": "" }
q37239
Template.render
train
def render(self, template_name, **kw): ''' Given a template name and template vars. Searches a template file based on engine set, and renders it with corresponding engine. Returns a string. ''' logger.debug('Rendering template "%s"', template_name) vars =...
python
{ "resource": "" }
q37240
BoundTemplate.render
train
def render(self, template_name, __data=None, **kw): '''Given a template name and template data. Renders a template and returns as string''' return self.template.render(template_name, **self._vars(__data, **kw))
python
{ "resource": "" }
q37241
BoundTemplate.render_to_response
train
def render_to_response(self, template_name, __data, content_type="text/html"): '''Given a template name and template data. Renders a template and returns `webob.Response` object''' resp = self.render(template_name, __data) return Response(resp, ...
python
{ "resource": "" }
q37242
Paginator.page
train
def page(self): '''Current page.''' page = self.request.GET.get(self.page_param) if not page: return 1 try: page = int(page) except ValueError: self.invalid_page() return 1 if page<1: self.invalid_page() ...
python
{ "resource": "" }
q37243
Paginator.url
train
def url(self): '''Current or base URL. Can be redefined via keyword argument on initialization. Returns `iktomi.web.URL object. `''' return URL.from_url(self.request.url, show_host=self.show_host)
python
{ "resource": "" }
q37244
Paginator.page_url
train
def page_url(self, page): ''' Returns URL for page, page is included as query parameter. Can be redefined by keyword argument ''' if page is not None and page != 1: return self.url.qs_set(**{self.page_param: page}) elif page is not None: return se...
python
{ "resource": "" }
q37245
Paginator.pages_count
train
def pages_count(self): '''Number of pages.''' if not self.limit or self.count<self.limit: return 1 if self.count % self.limit <= self.orphans: return self.count // self.limit return int(math.ceil(float(self.count)/self.limit))
python
{ "resource": "" }
q37246
Paginator.slice
train
def slice(self, items): '''Slice the sequence of all items to obtain them for current page.''' if self.limit: if self.page>self.pages_count: return [] if self.page == self.pages_count: return items[self.limit*(self.page-1):] return item...
python
{ "resource": "" }
q37247
list_build_records
train
def list_build_records(page_size=200, page_index=0, sort="", q=""): """ List all BuildRecords """ data = list_build_records_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
{ "resource": "" }
q37248
list_records_for_build_configuration
train
def list_records_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all BuildRecords for a given BuildConfiguration """ data = list_records_for_build_configuration_raw(id, name, page_size, page_index, sort, q) if data: return utils.format_json_l...
python
{ "resource": "" }
q37249
list_records_for_project
train
def list_records_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all BuildRecords for a given Project """ data = list_records_for_project_raw(id, name, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
{ "resource": "" }
q37250
list_built_artifacts
train
def list_built_artifacts(id, page_size=200, page_index=0, sort="", q=""): """ List Artifacts associated with a BuildRecord """ data = list_built_artifacts_raw(id, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
{ "resource": "" }
q37251
list_dependency_artifacts
train
def list_dependency_artifacts(id, page_size=200, page_index=0, sort="", q=""): """ List dependency artifacts associated with a BuildRecord """ data = list_dependency_artifacts_raw(id, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
python
{ "resource": "" }
q37252
StatusReporter.on_start
train
def on_start(self): """Runs when the actor is started and schedules a status update """ logger.info('StatusReporter started.') # if configured not to report status then return immediately if self.config['status_update_interval'] == 0: logger.info('StatusReporter disab...
python
{ "resource": "" }
q37253
StatusReporter.report_again
train
def report_again(self, current_status): """Computes a sleep interval, sleeps for the specified amount of time then kicks off another status report. """ # calculate sleep interval based on current status and configured interval _m = {'playing': 1, 'paused': 2, 'stopped': 5}[curren...
python
{ "resource": "" }
q37254
StatusReporter.report_status
train
def report_status(self): """Get status of player from mopidy core and send webhook. """ current_status = { 'current_track': self.core.playback.current_track.get(), 'state': self.core.playback.state.get(), 'time_position': self.core.playback.time_position.get()...
python
{ "resource": "" }
q37255
get_urlfield_cache_key
train
def get_urlfield_cache_key(model, pk, language_code=None): """ The low-level function to get the cache key for a model. """ return 'anyurlfield.{0}.{1}.{2}.{3}'.format(model._meta.app_label, model.__name__, pk, language_code or get_language())
python
{ "resource": "" }
q37256
MovingAverage.flush
train
def flush(self): """ Add accumulator to the moving average queue and reset it. For example, called by the StatsCollector once per second to calculate per-second average. """ n = self.accumulator self.accumulator = 0 stream = self.stream stream.append(n) ...
python
{ "resource": "" }
q37257
send_webhook
train
def send_webhook(config, payload): """Sends a HTTP request to the configured server. All exceptions are suppressed but emit a warning message in the log. """ try: response = requests.post( config['webhook_url'], data=json.dumps(payload, cls=ModelJSONEncoder), ...
python
{ "resource": "" }
q37258
Warehouse.clean
train
def clean(self): """Remove all of the tables and data from the warehouse""" connection = self._backend._get_connection() self._backend.clean(connection)
python
{ "resource": "" }
q37259
Warehouse.list
train
def list(self): """List the tables in the database""" connection = self._backend._get_connection() return list(self._backend.list(connection))
python
{ "resource": "" }
q37260
Warehouse.install
train
def install(self, ref, table_name=None, index_columns=None,logger=None): """ Finds partition by reference and installs it to warehouse db. Args: ref (str): id, vid (versioned id), name or vname (versioned name) of the partition. """ try: obj_number = ObjectNum...
python
{ "resource": "" }
q37261
Warehouse.materialize
train
def materialize(self, ref, table_name=None, index_columns=None, logger=None): """ Creates materialized table for given partition reference. Args: ref (str): id, vid, name or vname of the partition. Returns: str: name of the partition table in the database. """ ...
python
{ "resource": "" }
q37262
Warehouse.parse_sql
train
def parse_sql(self, asql): """ Executes all sql statements from asql. Args: library (library.Library): asql (str): ambry sql query - see https://github.com/CivicKnowledge/ambry/issues/140 for details. """ import sqlparse statements = sqlparse.parse(sqlpa...
python
{ "resource": "" }
q37263
Warehouse.query
train
def query(self, asql, logger=None): """ Execute an ASQL file and return the result of the first SELECT statement. :param asql: :param logger: :return: """ import sqlparse from ambry.mprlib.exceptions import BadSQLError from ambry.bundle.asql_parse...
python
{ "resource": "" }
q37264
Warehouse.geoframe
train
def geoframe(self, sql, simplify=None, crs=None, epsg=4326): """ Return geopandas dataframe :param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry. :param crs: Coordinate reference system information :param epsg: Specifiy the CRS as ...
python
{ "resource": "" }
q37265
Request.get_url_param
train
def get_url_param(self, index, default=None): """ Return url parameter with given index. Args: - index: starts from zero, and come after controller and action names in url. """ params = self.get_url_params() return params[index] if index < len(params) e...
python
{ "resource": "" }
q37266
UrlType.get_widget
train
def get_widget(self): """ Create the widget for the URL type. """ form_field = self.get_form_field() widget = form_field.widget if isinstance(widget, type): widget = widget() # Widget instantiation needs to happen manually. # Auto skip if choi...
python
{ "resource": "" }
q37267
UrlTypeRegistry.register
train
def register(self, ModelClass, form_field=None, widget=None, title=None, prefix=None, has_id_value=True): """ Register a custom model with the ``AnyUrlField``. """ if any(urltype.model == ModelClass for urltype in self._url_types): raise ValueError("Model is already registere...
python
{ "resource": "" }
q37268
UrlTypeRegistry.get_for_model
train
def get_for_model(self, ModelClass): """ Return the URL type for a given model class """ for urltype in self._url_types: if urltype.model is ModelClass: return urltype return None
python
{ "resource": "" }
q37269
UrlTypeRegistry.index
train
def index(self, prefix): """ Return the model index for a prefix. """ # Any web domain will be handled by the standard URLField. if self.is_external_url_prefix(prefix): prefix = 'http' for i, urltype in enumerate(self._url_types): if urltype.prefi...
python
{ "resource": "" }
q37270
message_received
train
def message_received(request, backend_name): """Handle HTTP requests from Tropo. """ logger.debug("@@ request from Tropo - raw data: %s" % request.body) try: post = json.loads(request.body) except ValueError: logger.exception("EXCEPTION decoding post data in incoming request") ...
python
{ "resource": "" }
q37271
list_running_builds
train
def list_running_builds(page_size=200, page_index=0, sort=""): """ List all RunningBuilds """ content = list_running_builds_raw(page_size, page_index, sort) if content: return utils.format_json_list(content)
python
{ "resource": "" }
q37272
between
train
def between(min_value, max_value): 'Numerical values limit' message = N_('value should be between %(min)d and %(max)d') % \ dict(min=min_value, max=max_value) @validator(message) def wrapper(conv, value): if value is None: # it meens that this value is not requir...
python
{ "resource": "" }
q37273
_tzinfome
train
def _tzinfome(tzinfo): """Gets a tzinfo object from a string. Args: tzinfo: A string (or string like) object, or a datetime.tzinfo object. Returns: An datetime.tzinfo object. Raises: UnknownTimeZoneError: If the timezone given can't be decoded. """ if not isinstance(tzinfo, datetime.tzinfo): ...
python
{ "resource": "" }
q37274
localize
train
def localize(dt, force_to_local=True): """Localize a datetime to the local timezone. If dt is naive, returns the same datetime with the local timezone, otherwise uses astimezone to convert. Args: dt: datetime object. force_to_local: Force all results to be in local time. Returns: A datetime_tz ...
python
{ "resource": "" }
q37275
get_naive
train
def get_naive(dt): """Gets a naive datetime from a datetime. datetime_tz objects can't just have tzinfo replaced with None, you need to call asdatetime. Args: dt: datetime object. Returns: datetime object without any timezone information. """ if not dt.tzinfo: return dt if hasattr(dt, "as...
python
{ "resource": "" }
q37276
detect_timezone
train
def detect_timezone(): """Try and detect the timezone that Python is currently running in. We have a bunch of different methods for trying to figure this out (listed in order they are attempted). * In windows, use win32timezone.TimeZoneInfo.local() * Try TZ environment variable. * Try and find /etc/t...
python
{ "resource": "" }
q37277
_load_local_tzinfo
train
def _load_local_tzinfo(): """Load zoneinfo from local disk.""" tzdir = os.environ.get("TZDIR", "/usr/share/zoneinfo/posix") localtzdata = {} for dirpath, _, filenames in os.walk(tzdir): for filename in filenames: filepath = os.path.join(dirpath, filename) name = os.path.relpath(filepath, tzdir)...
python
{ "resource": "" }
q37278
_wrap_method
train
def _wrap_method(name): """Wrap a method. Patch a method which might return a datetime.datetime to return a datetime_tz.datetime_tz instead. Args: name: The name of the method to patch """ method = getattr(datetime.datetime, name) # Have to give the second argument as method has no __module__ optio...
python
{ "resource": "" }
q37279
datetime_tz.asdatetime
train
def asdatetime(self, naive=True): """Return this datetime_tz as a datetime object. Args: naive: Return *without* any tz info. Returns: This datetime_tz as a datetime object. """ args = list(self.timetuple()[0:6])+[self.microsecond] if not naive: args.append(self.tzinfo) r...
python
{ "resource": "" }
q37280
datetime_tz.asdate
train
def asdate(self): """Return this datetime_tz as a date object. Returns: This datetime_tz as a date object. """ return datetime.date(self.year, self.month, self.day)
python
{ "resource": "" }
q37281
datetime_tz.astimezone
train
def astimezone(self, tzinfo): """Returns a version of this timestamp converted to the given timezone. Args: tzinfo: Either a datetime.tzinfo object or a string (which will be looked up in pytz. Returns: A datetime_tz object in the given timezone. """ # Assert we are not a...
python
{ "resource": "" }
q37282
datetime_tz.replace
train
def replace(self, **kw): """Return datetime with new specified fields given as arguments. For example, dt.replace(days=4) would return a new datetime_tz object with exactly the same as dt but with the days attribute equal to 4. Any attribute can be replaced, but tzinfo can not be set to None. Arg...
python
{ "resource": "" }
q37283
datetime_tz.utcnow
train
def utcnow(cls): """Return a new datetime representing UTC day and time.""" obj = datetime.datetime.utcnow() obj = cls(obj, tzinfo=pytz.utc) return obj
python
{ "resource": "" }
q37284
iterate.between
train
def between(start, delta, end=None): """Return an iterator between this date till given end point. Example usage: >>> d = datetime_tz.smartparse("5 days ago") 2008/05/12 11:45 >>> for i in d.between(timedelta(days=1), datetime_tz.now()): >>> print i 2008/05/12 11:45 2008/...
python
{ "resource": "" }
q37285
iterate.days
train
def days(start, end=None): """Iterate over the days between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a day apart. ...
python
{ "resource": "" }
q37286
iterate.hours
train
def hours(start, end=None): """Iterate over the hours between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a hour apart. ...
python
{ "resource": "" }
q37287
iterate.minutes
train
def minutes(start, end=None): """Iterate over the minutes between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a minute a...
python
{ "resource": "" }
q37288
publish_page
train
def publish_page(page, languages): """ Publish a CMS page in all given languages. """ for language_code, lang_name in iter_languages(languages): url = page.get_absolute_url() if page.publisher_is_draft: page.publish(language_code) log.info('page "%s" published in...
python
{ "resource": "" }
q37289
create_cms_plugin_page
train
def create_cms_plugin_page(apphook, apphook_namespace, placeholder_slot=None): """ Create cms plugin page in all existing languages. Add a link to the index page. :param apphook: e.g...........: 'FooBarApp' :param apphook_namespace: e.g.: 'foobar' :return: """ creator = CmsPluginPageCre...
python
{ "resource": "" }
q37290
CmsPageCreator.publish
train
def publish(self, page): """ Publish the page in all languages. """ assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page publish_page(page, languages=self.languages)
python
{ "resource": "" }
q37291
CmsPageCreator.add_plugins
train
def add_plugins(self, page, placeholder): """ Add a "TextPlugin" in all languages. """ for language_code, lang_name in iter_languages(self.languages): for no in range(1, self.dummy_text_count + 1): add_plugin_kwargs = self.get_add_plugin_kwargs( ...
python
{ "resource": "" }
q37292
CmsPageCreator.get_or_create_placeholder
train
def get_or_create_placeholder(self, page, placeholder_slot): """ Add a placeholder if not exists. """ placeholder, created = get_or_create_placeholder( page, placeholder_slot, delete_existing=self.delete_first) return placeholder, created
python
{ "resource": "" }
q37293
CmsPageCreator.fill_content
train
def fill_content(self, page, placeholder_slot): """ Add a placeholder to the page. Here we add a "TextPlugin" in all languages. """ if len(placeholder_slot) == 1: raise RuntimeError(placeholder_slot) placeholder, created = self.get_or_create_placeholder( ...
python
{ "resource": "" }
q37294
CmsPluginPageCreator.create
train
def create(self): """ Create the plugin page in all languages and fill dummy content. """ plugin = CMSPlugin.objects.filter(plugin_type=self.apphook) if plugin.exists(): log.debug('Plugin page for "%s" plugin already exist, ok.', self.apphook) ...
python
{ "resource": "" }
q37295
SourceTable.column
train
def column(self, source_header_or_pos): """ Return a column by name or position :param source_header_or_pos: If a string, a source header name. If an integer, column position :return: """ for c in self.columns: if c.source_header == source_header_or_pos: ...
python
{ "resource": "" }
q37296
table_convert_geometry
train
def table_convert_geometry(metadata, table_name): """Get table metadata from the database.""" from sqlalchemy import Table from ..orm import Geometry table = Table(table_name, metadata, autoload=True) for c in table.columns: # HACK! Sqlalchemy sees spatialte GEOMETRY types # as NU...
python
{ "resource": "" }
q37297
incver
train
def incver(o, prop_names): """Increment the version numbers of a set of properties and return a new object""" from ambry.identity import ObjectNumber d = {} for p in o.__mapper__.attrs: v = getattr(o, p.key) if v is None: d[p.key] = None elif p.key in prop_names: ...
python
{ "resource": "" }
q37298
MutationList.coerce
train
def coerce(cls, key, value): """Convert plain list to MutationList.""" if isinstance(value, string_types): value = value.strip() if value[0] == '[': # It's json encoded, probably try: value = json.loads(value) except ValueErro...
python
{ "resource": "" }
q37299
parse_view
train
def parse_view(query): """ Parses asql query to view object. Args: query (str): asql query Returns: View instance: parsed view. """ try: idx = query.lower().index('where') query = query[:idx] except ValueError: pass if not query.endswith(';'): ...
python
{ "resource": "" }