code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def pay_order_interfaces(order: Order): <NEW_LINE> <INDENT> return set_order_paid(order)
将订单设置为已支付状态,同时生成一些其他的数据, 带commit
625941baac7a0e7691ed3f7e
def __init__(self, available_replicas=None, collision_count=None, conditions=None, observed_generation=None, ready_replicas=None, replicas=None, unavailable_replicas=None, updated_replicas=None): <NEW_LINE> <INDENT> self._available_replicas = None <NEW_LINE> self._collision_count = None <NEW_LINE> self._conditions = No...
ExtensionsV1beta1DeploymentStatus - a model defined in Swagger
625941ba26238365f5f0ed0f
def put(self, key, data): <NEW_LINE> <INDENT> hashValue = self.hashFunction(key, self.size) <NEW_LINE> if self.keys[hashValue] == None: <NEW_LINE> <INDENT> self.keys[hashValue] = key <NEW_LINE> self.data[hashValue] = data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.keys[hashValue] == key: <NEW_LINE> <INDENT> ...
Given key/value pair, insert in hash table, or replace data.
625941ba2c8b7c6e89b35668
def test_delete_message(self): <NEW_LINE> <INDENT> pass
Test case for delete_message Delete message # noqa: E501
625941ba091ae35668666e0a
def myPow(self, x, n): <NEW_LINE> <INDENT> sign = n < 0 <NEW_LINE> n = abs(n) <NEW_LINE> temp = x <NEW_LINE> re = 1 <NEW_LINE> while n: <NEW_LINE> <INDENT> if n % 2: <NEW_LINE> <INDENT> re *= temp <NEW_LINE> <DEDENT> temp *= temp <NEW_LINE> n /= 2 <NEW_LINE> <DEDENT> return 1 / re if sign else re
:type x: float :type n: int :rtype: float
625941ba23849d37ff7b2f37
def form_key(self, *args, **kwargs): <NEW_LINE> <INDENT> normalized = self.call_sign.normalize(*args, **kwargs) <NEW_LINE> cache_key = CacheKey(*normalized.args, **normalized.kwargs) <NEW_LINE> return cache_key.tuple
Form normalized cache key from args and kwargs
625941baab23a570cc250025
def test_update_reservation_conflict_override(self): <NEW_LINE> <INDENT> student = User.query.filter_by(name='student').first() <NEW_LINE> team_type = TeamType.query.filter_by(name='other_team').first() <NEW_LINE> initial_team = Team(name="other_team_1") <NEW_LINE> initial_team.team_type = team_type <NEW_LINE> initial_...
Update a reservation, and then override it.
625941ba379a373c97cfa9f0
def set_image(self): <NEW_LINE> <INDENT> if self.is_killing: <NEW_LINE> <INDENT> image_index = int(floor(pygame.time.get_ticks() * Character.TILES_CHANGE_SPEED) % self.kill_length) <NEW_LINE> self.image = self.kill_textures[image_index] <NEW_LINE> <DEDENT> elif self.is_running: <NEW_LINE> <INDENT> image_index = int(flo...
Method that sets 'image' field using character's textures
625941ba167d2b6e31218a3c
def get_provides_port(self): <NEW_LINE> <INDENT> return copy(self._provides_port_ports)
Get all objects related with this object with relation `providesPort`. :rtype: :py:class:`OrderedDict` :return: A copy of the collection of objects related with this object.
625941ba2ae34c7f2600cfd7
def rang(self): <NEW_LINE> <INDENT> return self.matriu.rank()
Retorna el rang de la matriu
625941ba50485f2cf553cc3e
@app.route(API_V1 + "authentication", methods=['GET']) <NEW_LINE> def authentication(): <NEW_LINE> <INDENT> return jsonify(enabled=authentication_enabled())
check if basic authentication is enabled
625941ba1d351010ab8559c2
def ModFactoryImage(factory_bin, test_src, test_list_src): <NEW_LINE> <INDENT> subprocess.check_call([_MOUNT_PARTITION_SCRIPT, _MOUNT_RW, factory_bin, _MOUNT_PARTITION_INDEX, _MOUNT_POINT]) <NEW_LINE> try: <NEW_LINE> <INDENT> test_sink = os.path.join(_MOUNT_POINT, _IMAGE_TEST_DIR) <NEW_LINE> test_list_sink = os.path.jo...
Adds new tests and a test_list to the given factory image. Args: factory_bin: path to factory image file. test_src: path to directory containing tests. test_list_src: path to test list. Raises: CalledProcessError: if a script or command returns non-zero. DistutilsFileError: on file copy failure.
625941ba3cc13d1c6d3c7229
def score_obs(self, params): <NEW_LINE> <INDENT> Xb = np.dot(self.exog, params) <NEW_LINE> prob = self.cdf(Xb) <NEW_LINE> return (self.endog - prob)[:, None] * self.exog
Logit model Jacobian of the log-likelihood for each observation Parameters ---------- params: array-like The parameters of the model Returns ------- jac : array-like The derivative of the loglikelihood for each observation evaluated at `params`. Notes ----- .. math:: \frac{\partial\ln L_{i}}{\partial\bet...
625941bad486a94d0b98dff2
def addon(self, name): <NEW_LINE> <INDENT> cmd = ["heroku", "addons:create", name, "--app", self.name] <NEW_LINE> self._run(cmd)
Set up an addon
625941ba97e22403b379ce3e
def subtract_backgrounds(iss_data=[], ranges=[], btype='linear', avg=3): <NEW_LINE> <INDENT> AVG = avg + 0.5 <NEW_LINE> for iss in iss_data: <NEW_LINE> <INDENT> iss._background = dict() <NEW_LINE> for key in iss.energy.keys(): <NEW_LINE> <INDENT> iss._background[key] = subtract_single_background(iss.get_xy(key), ranges...
Subtract a linear background from defined 'ranges'. Return data above backgrounds.
625941baa17c0f6771cbdef9
def fetch_campaigns(self): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> log.error('It is neccesary to save account before saving campaigns') <NEW_LINE> <DEDENT> response = api_call('act_%s/adcampaigns' % self.account_id) <NEW_LINE> instances = [] <NEW_LINE> for resource in response.data: <NEW_LINE> <INDENT> ...
Retrieve and save all campaigns for account
625941baa8ecb033257d2f7b
def _refresh_os_mixins(self, extras): <NEW_LINE> <INDENT> template_schema = 'http://schemas.openstack.org/template/os#' <NEW_LINE> images = vm.retrieve_images(extras['nova_ctx']) <NEW_LINE> os_lst = [occify_terms(item['name']) for item in images] <NEW_LINE> occi_lst = [item.term for item in self.registry.get_categories...
Register images as OsTemplate mixins from information retrieved from glance (shared and user-specific).
625941ba9b70327d1c4e0c79
def __init__(self, parent): <NEW_LINE> <INDENT> self._isshown = True <NEW_LINE> self._parent = parent <NEW_LINE> Control.__init__(self, parent)
Default class constructor. :param `parent`: the separator parent object, an instance of :class:`ButtonPanel`.
625941bae5267d203edcdb46
def _frac_y_to_pixel_y(self, frac_y: float) -> int: <NEW_LINE> <INDENT> return self._frac_to_pixel(frac_y, self._surface.get_height())
Converts a fractional y value to its corresponding y pixel value :param frac_y: The fractional location on the y axis. (0.0 - 1.0) :return: An int that is the pixel value on the y axis
625941ba507cdc57c6306b7a
def split(self, output, motion_output=None): <NEW_LINE> <INDENT> with self.outputs_lock: <NEW_LINE> <INDENT> outputs = {} <NEW_LINE> if output is not None: <NEW_LINE> <INDENT> outputs[PiVideoFrameType.frame] = output <NEW_LINE> <DEDENT> if motion_output is not None: <NEW_LINE> <INDENT> outputs[PiVideoFrameType.motion_d...
Called to switch the encoder's output. This method is called by :meth:`~PiCamera.split_recording` and :meth:`~PiCamera.record_sequence` to switch the encoder's :attr:`output` object to the *output* parameter (which can be a filename or a file-like object, as with :meth:`start`).
625941babaa26c4b54cb0fc8
def forward(self, x, depth, alpha): <NEW_LINE> <INDENT> x = self.fc(x) <NEW_LINE> assert depth < self.depth, "Requested output depth cannot be produced" <NEW_LINE> y = self.initial_block(x) <NEW_LINE> if depth > 0: <NEW_LINE> <INDENT> for block in self.layers[:depth - 1]: <NEW_LINE> <INDENT> y = block(y) <NEW_LINE> <DE...
forward pass of the Generator :param x: input noise :param depth: current depth from where output is required :param alpha: value of alpha for fade-in effect :return: y => output
625941ba4d74a7450ccd4069
def testTCPShortWrite(self): <NEW_LINE> <INDENT> name = 'short-write.tcp-short.tests.powerdns.com.' <NEW_LINE> query = dns.message.make_query(name, 'AXFR', 'IN') <NEW_LINE> responses = [] <NEW_LINE> soa = dns.rrset.from_text(name, 60, dns.rdataclass.IN, dns.rdatatype.SOA, 'ns.' + name + ' hostmaster.' + name + ' 1 3600...
TCP: Short write to client
625941ba8e71fb1e9831d653
def find_nearby_stops(x, y): <NEW_LINE> <INDENT> radius = 500 <NEW_LINE> params = { "Circle": "{:.6f},{:.6f},{:d}".format(y, x, radius), "ReturnList": ",".join(RETURN_LIST), } <NEW_LINE> url = format_url("/instant_V2", **params) <NEW_LINE> request = pan.http.get(url, encoding="utf_8") <NEW_LINE> return parsejson_find_n...
Return a list of stops near given coordinates.
625941ba5166f23b2e1a4fff
def get_pf(pfname): <NEW_LINE> <INDENT> if hasattr(stock, 'pfread'): <NEW_LINE> <INDENT> return stock.pfread(pfname).pf2dict() <NEW_LINE> <DEDENT> elif hasattr(stock, 'pfget'): <NEW_LINE> <INDENT> return stock.pfget(pfname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("No pf function available")
Return a dict from a pf file
625941ba7c178a314d6ef2ff
def setLogThreshold(self, threshold): <NEW_LINE> <INDENT> Log.getDefaultLog().setThreshold(threshold)
set the importance threshold for the default log. This and setDebugVerbosity are different APIs that affect the same underlying limit that controls how many messages get logged. Normally one uses one of the predefined values--Log.DEBUG, Log.INFO, Log.WARN, and Log.FATAL--as input. @param threshold the minimum impo...
625941ba4a966d76dd550eb2
def test_one_of_each(self): <NEW_LINE> <INDENT> results = { MockPlugin(): (0, ['C'], ''), MockPlugin(): (0, {u'a.txt': u'F'}, ''), MockPlugin(): (0, {u'a.txt': [[1, None, u'L']]}, '')} <NEW_LINE> rc = ResultsCollater(results) <NEW_LINE> self.assertEqual({u'info': 3, u'warn': 0, u'stop': 0}, rc.counts) <NEW_LINE> cm, fm...
One of each type of message is captured.
625941ba0a366e3fb873e6bd
def __init__(self, connector, identity, redfish_version=None, registries=None, root=None): <NEW_LINE> <INDENT> super(SessionCollection, self).__init__( connector, identity, redfish_version=redfish_version, registries=registries, root=root)
A class representing a SessionCollection :param connector: A Connector instance :param identity: The identity of the Session resource :param redfish_version: The version of RedFish. Used to construct the object according to schema of given version. :param registries: Dict of Redfish Message Registry objects to be ...
625941ba67a9b606de4a7d62
def ffmpeg_resize(video,output,size): <NEW_LINE> <INDENT> cmd= [get_setting("FFMPEG_BINARY"), "-i", video, "-vf", "scale=%d:%d"%(res[0], res[1]), output] <NEW_LINE> subprocess_call(cmd)
resizes ``video`` to new size ``size`` and write the result in file ``output``.
625941ba6fece00bbac2d5e1
def test_related_field(self): <NEW_LINE> <INDENT> countries = self.env['res.country'].search([('code', '!=', False)], limit=100) <NEW_LINE> self.assertEqual(len(countries), 100, "Not enough records in comodel 'res.country'") <NEW_LINE> partners = self.env['res.partner'].create([ {'name': country.code, 'country_id': cou...
create a custom related field, and check filled values
625941bade87d2750b85fc34
def test_selection(self): <NEW_LINE> <INDENT> path = self.tmp_repos() <NEW_LINE> os.mkdir(path) <NEW_LINE> python_file = '001_initial_.py' <NEW_LINE> sqlite_upgrade_file = '001_sqlite_upgrade.sql' <NEW_LINE> default_upgrade_file = '001_default_upgrade.sql' <NEW_LINE> for file_ in [sqlite_upgrade_file, default_upgrade_f...
Verify right sql script is selected
625941bad8ef3951e32433e3
def bottom(self) -> None: <NEW_LINE> <INDENT> current_index = ALL_WINDOWS.index(self) <NEW_LINE> ALL_WINDOWS.pop(current_index) <NEW_LINE> ALL_WINDOWS.insert(0, self)
Sets this window to the bottom of the drawing buffer (In other words, it will be drawn under everything else).
625941baa8370b7717052746
def get_namespace(self, bundle): <NEW_LINE> <INDENT> return "{level}.project_data.%s" % (bundle.obj.get_space_replaced_name)
Hook to return the dotted path to this field based on the level and the name of the field The level name is formatted in the dehydrate method of the DataFormConfigResource
625941ba99cbb53fe6792a8d
def get_recipe_ids(): <NEW_LINE> <INDENT> return request_list('https://api.wynncraft.com/v2/recipe/list')
Gets a :class:`list` of :class:`str` objects containing all recipe IDs from the Wynncraft API. :returns: A list of all recipeIDs as :class:`str` :rtype: :class:`list`
625941ba656771135c3eb718
def vslice(self, value): <NEW_LINE> <INDENT> if isinstance(value, datetime.datetime): <NEW_LINE> <INDENT> value = date2num(value) <NEW_LINE> <DEDENT> ind = bisect.bisect_right(self['spectrogram']['xedges'], value) <NEW_LINE> ans = dm.SpaceData() <NEW_LINE> ans[self['spectrogram'].attrs['variables'][1]] = tb.bin_edges_t...
slice a spectrogram at a given position along the x axis, maintains variable names from spectrogram Parameters ========== value : float or datetime.datetime the value to slice the spectrogram at Returns ======= out : datamodel.SpaceData spacedata containing the slice
625941baa8370b7717052747
def to_nx_graph(item, to_undirected=False): <NEW_LINE> <INDENT> if isinstance(item, MineList): <NEW_LINE> <INDENT> g = get_nx_graph(item) <NEW_LINE> if to_undirected: <NEW_LINE> <INDENT> g = g.to_undirected(reciprocal=False) <NEW_LINE> <DEDENT> return g <NEW_LINE> <DEDENT> elif isinstance(item, list): <NEW_LINE> <INDEN...
Recursively transform an item or iterable into nx Graph.
625941bad4950a0f3b08c1f8
def get_root( self, **kwargs ): <NEW_LINE> <INDENT> kwargs['async_req'] = kwargs.get( 'async_req', False ) <NEW_LINE> kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) <NEW_LINE> kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) <NEW_LINE> kwargs['_request_timeout'] = kwa...
Root resource # noqa: E501 Issue a `GET` request to the root resource to find all of the resource categories supported by the API # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_root(async_req=True) >>> resul...
625941ba45492302aab5e166
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1EphemeralVolumeSource): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941ba4e4d5625662d4282
def DescribePublicConfigs(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribePublicConfigs", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DescribePublicCon...
查询公共配置项列表 :param request: Request instance for DescribePublicConfigs. :type request: :class:`tencentcloud.tsf.v20180326.models.DescribePublicConfigsRequest` :rtype: :class:`tencentcloud.tsf.v20180326.models.DescribePublicConfigsResponse`
625941ba94891a1f4081b94e
def __init__(self, user=None, password=None, confirm_password=None): <NEW_LINE> <INDENT> self._user = None <NEW_LINE> self._password = None <NEW_LINE> self._confirm_password = None <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> self.user = user <NEW_LINE> <DEDENT> if password is not None: <NEW_LINE> <INDENT> self....
Body1 - a model defined in Swagger
625941ba30bbd722463cbc69
def set_thumbnail(self, pixmap): <NEW_LINE> <INDENT> pixmap = pixmap.scaledToHeight(self.thumb_size, QtCore.Qt.SmoothTransformation) <NEW_LINE> if pixmap.width() > self.thumb_size: <NEW_LINE> <INDENT> extra = pixmap.width() - self.thumb_size <NEW_LINE> pixmap = pixmap.copy(extra / 2, 0, self.thumb_size, self.thumb_size...
Set a thumbnail given the current pixmap.
625941ba711fe17d82542218
def read(self, source_path): <NEW_LINE> <INDENT> from cStringIO import StringIO <NEW_LINE> with pelican_open(source_path) as source: <NEW_LINE> <INDENT> text = StringIO(source.encode('utf8')) <NEW_LINE> <DEDENT> content = StringIO() <NEW_LINE> ad = AsciiDocAPI() <NEW_LINE> options = self.settings.get('ASCIIDOC_OPTIONS'...
Parse content and metadata of asciidoc files
625941ba63f4b57ef0000fc7
def _iter_built_with_prepended(installed, infos): <NEW_LINE> <INDENT> yield installed <NEW_LINE> versions_found = {installed.version} <NEW_LINE> for version, func in infos: <NEW_LINE> <INDENT> if version in versions_found: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> candidate = func() <NEW_LINE> if candidate is No...
Iterator for ``FoundCandidates``. This iterator is used when the resolver prefers the already-installed candidate and NOT to upgrade. The installed candidate is therefore always yielded first, and candidates from index come later in their normal ordering, except skipped when the version is already installed.
625941ba2ae34c7f2600cfd8
def set(self, start_time, end_time, weekdays=None, instance_ids=None): <NEW_LINE> <INDENT> if start_time >= end_time: <NEW_LINE> <INDENT> raise ValueError( 'Start time can\'t be greater than or equal to end time' ) <NEW_LINE> <DEDENT> start_time = start_time.isoformat() <NEW_LINE> end_time = end_time.isoformat() <NEW_L...
Create or update weekday run times for all or specific EC2 instances. :type instance_ids: list :param instance_ids: A list of strings of instance IDs :type weekdays: list :param weekdays: A list of strings of weekdays (e.g. `Monday`) :type start_time: datetime.time :param start_time: The instance starting time :typ...
625941bad7e4931a7ee9ddc2
@contract(cadena='str', returns='int') <NEW_LINE> def contar_vocales(cadena: str) -> int: <NEW_LINE> <INDENT> return sum(1 for _ in filter(lambda x: x in ("a", "e", "i", "o", "u"), cadena))
9: Return number of vocales in a word. >>> contar_vocales("murcielago") 5
625941ba4c3428357757c1d1
def GetReverseOrdering(self): <NEW_LINE> <INDENT> return _itkLabelStatisticsKeepNObjectsImageFilterPython.itkLabelStatisticsKeepNObjectsImageFilterIUC2IUS2_GetReverseOrdering(self)
GetReverseOrdering(self) -> bool
625941bab5575c28eb68dea4
def Lderivs(self, E, n, prec, d): <NEW_LINE> <INDENT> if prec > 64: <NEW_LINE> <INDENT> raise ValueError("prec (=%s) must be at most 64" % prec) <NEW_LINE> <DEDENT> if prec < 1: <NEW_LINE> <INDENT> raise ValueError("prec (=%s) must be at least 1" % prec) <NEW_LINE> <DEDENT> v = self('-sp %sp%sd%s %s' % (n, prec, d, sel...
Return `0^{th}` to `d^{th}` derivatives of `L(\mathrm{Sym}^{(n)}(E,s)` to prec digits of precision, where `s` is the right edge if `n` is even and the center if `n` is odd. INPUT: - ``E`` - elliptic curve - ``n`` - integer (even or odd) - ``prec`` - integer - ``d`` - integer OUTPUT: a string, exactly as out...
625941ba0fa83653e4656e63
def __init__(self, count, minimum, mean, median, maximum, variance, stdev, stdev2, stdev3): <NEW_LINE> <INDENT> self.__count = count <NEW_LINE> self.__minimum = minimum <NEW_LINE> self.__mean = mean <NEW_LINE> self.__median = median <NEW_LINE> self.__maximum = maximum <NEW_LINE> self.__variance = variance <NEW_LINE> se...
Constructor
625941ba38b623060ff0ac95
def default_speedup(self): <NEW_LINE> <INDENT> return 100
Tracker seems to be race-free
625941bad8ef3951e32433e4
def create_master(self,name): <NEW_LINE> <INDENT> repository_master_path = os.path.join(self.base_path,name) <NEW_LINE> os.system("svnadmin create " + repository_master_path) <NEW_LINE> self.created_path.append(repository_master_path) <NEW_LINE> return repository_master_path
Create svn master repository. Return create master repository directory path.
625941bafb3f5b602dac3536
def deposit(self, amount): <NEW_LINE> <INDENT> assert isinstance(amount, money.Money) <NEW_LINE> self._balance += amount
Adds amount of money to the balance. Args: amount (float): amount to be added to balance Raises: AssertionError: If amount is not of the type "money"
625941ba4e4d5625662d4283
def texwithoutdagger(self): <NEW_LINE> <INDENT> show = string.join([self.type[0],"_{",repr(self.index),"}"], "") <NEW_LINE> return show
Returns a human-friendly string of the content
625941ba0a366e3fb873e6be
def t_OBJECT_CAST(t): <NEW_LINE> <INDENT> t.value = "".join(t.value.split()) <NEW_LINE> return t
\( [\ \t]* ([Oo][Bb][Jj][Ee][Cc][Tt]) [\ \t]* \)
625941ba30bbd722463cbc6a
def initialize_connection(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection = psycopg2.connect(user = Connection.USER, port = Connection.PORT, database = Connection.DATABASE) <NEW_LINE> self.cursor = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor) <NEW_LINE> <DEDENT> except (Exceptio...
method for initialyse the connection to the database
625941ba66656f66f7cbc051
def OnFilterLeftClick(self, event = None): <NEW_LINE> <INDENT> itm = self.list.HitTest(event.GetPosition())[0] <NEW_LINE> if event.ShiftDown() and itm>-1: <NEW_LINE> <INDENT> self.OnEnableFilter(itm) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event.Skip()
Actions triggered by left mouse button click on filter list. Parameters: event - wx.Event
625941bacad5886f8bd26e89
def QueryOpMode(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> reply_text = self.__SendCommand('OM?') <NEW_LINE> print('MFC is in ' + reply_text) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Warning: <NEW_LINE> <INDENT> print('Unsuccessful communication with MFC ' + str(self.address)) <NEW_LINE> return False
Checks to see if the MFC is in run mode or in ______ mode. Parameters: None Returns: boolean value which indicates whether communication with MFC was successful
625941ba5f7d997b87174942
def get_long_name(self): <NEW_LINE> <INDENT> return self.jsettings["settings"]["long_name"]
Returns module long name.
625941ba3539df3088e2e1f2
def time_trace_plots(metadata, data, agent_ids): <NEW_LINE> <INDENT> dim = 2 <NEW_LINE> time_vec = np.arange(start=0, stop=metadata['max_time']+2*metadata['dt'], step=metadata['dt']) <NEW_LINE> for id_ in agent_ids: <NEW_LINE> <INDENT> a = data['agents'][id_] <NEW_LINE> est_data = a.local_filter.state_history <NEW_LINE...
Creates time trace plots for provided agent ids Inputs: metadata -- sim run metadata data -- sim results data structure agent_ids -- list of agent ids to plot Outputs: plots -- matplotlib plot objects
625941bacdde0d52a9e52ed6
def do_gridsearch(self,useDropOut = False,multi=False): <NEW_LINE> <INDENT> seed = 7 <NEW_LINE> numpy.random.seed(seed) <NEW_LINE> model = KerasClassifier(build_fn=self.create_model, verbose=0) <NEW_LINE> learn_rate = [0.0001, 0.001, 0.1] <NEW_LINE> dropout_rate = [0.1,0.2, 0.3] <NEW_LINE> X = self.trainDF[var_list].va...
Implementation of the sklearn grid search for hyper parameter tuning, making use of kfolds cross validation. Pass a dictionary of lists of parameters to test on. Choose number of cores to run on with n_jobs, -1 is all of them
625941ba91f36d47f21ac396
@asyncio.coroutine <NEW_LINE> def async_trigger(hass, config, action): <NEW_LINE> <INDENT> entity_id = config.get(CONF_ENTITY_ID) <NEW_LINE> from_state = config.get(CONF_FROM, MATCH_ALL) <NEW_LINE> to_state = get_deprecated(config, CONF_TO, CONF_STATE, MATCH_ALL) <NEW_LINE> time_delta = config.get(CONF_FOR) <NEW_LINE> ...
Listen for state changes based on configuration.
625941ba1f037a2d8b9460a6
def set_control_register(ate_inst, value): <NEW_LINE> <INDENT> wb_addr = 0x00001000 + 0x403 <NEW_LINE> assert (ate_inst.write(wb_addr, value & 0x1))
:param ate_inst: :param value: :return:
625941ba99fddb7c1c9de23a
def getLocalAreaDensity(self): <NEW_LINE> <INDENT> return _algorithms.Inhibition2_getLocalAreaDensity(self)
getLocalAreaDensity(self) -> nta::algorithms::Inhibition2::value_type
625941ba7b25080760e39301
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self.laser_scan_topic <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%length, length, _x)) <NE...
serialize message into buffer :param buff: buffer, ``StringIO``
625941ba711fe17d82542219
def read_dataset(dataset, path, limit=0, concat=False, all_years_label=False): <NEW_LINE> <INDENT> _, trigram_vecs_data = make_dataset.read_trigram_vecs('./data/raw/{}_cluster/'.format(dataset)) <NEW_LINE> df = pd.read_csv(path) <NEW_LINE> if limit != 0: <NEW_LINE> <INDENT> df = df.head(limit) <NEW_LINE> <DEDENT> label...
Reads the data set from given path, expecting it to contain a 'y' column with the label and each year in its own column containing a number of trigram indexes. Limit sets the maximum number of examples to read, zero meaning no limit. If concat is true each of the trigrams in a year is concatenated, if false they are in...
625941bafff4ab517eb2f2e1
def test_export_pdf_table_with_images_and_comments(self, fail=False): <NEW_LINE> <INDENT> self.user_login('test') <NEW_LINE> self.export_pdf_with_images_and_comments(fail=False, pdf_type="table") <NEW_LINE> self.export_pdf_token(pdf_type="table")
Tests exporting a workout as a pdf as the owner user with images and comments
625941ba29b78933be1e5560
def p_statement(p): <NEW_LINE> <INDENT> p[0] = p[1]
statement : affectation
625941ba851cf427c661a3b9
def network_status(self): <NEW_LINE> <INDENT> return self._transmit("network status")
dump network status
625941ba16aa5153ce36231f
def get_table_instance(self, p_table_name, p_schema='city4age_sr'): <NEW_LINE> <INDENT> return super(SRPostORM, self).get_table_instance(p_table_name, p_schema)
By giving a name of a table, this method returns the base instance :param p_table_name The name of the table :param p_schema The name of the given schema :return: A Base instance of the table to be computed
625941babe7bc26dc91cd4ac
def ddx(self): <NEW_LINE> <INDENT> N = self.owner.grid.num_points <NEW_LINE> g = 1/(2.0 * self.dr) <NEW_LINE> col_below = np.zeros(N) - g <NEW_LINE> col_above = np.zeros(N) + g <NEW_LINE> D = sparse.dia_matrix(([col_below, col_above], [-1, 1]), shape=(N, N)) <NEW_LINE> return D
Finite difference matrix for df/dx (centered) Returns ------- :class:`scipy.sparse.dia_matrix` Matrix which implements the centered finite difference approximation to df/dx
625941ba6fb2d068a760ef41
def _find_conflict_paths(self, end_clauses, relevant_clauses): <NEW_LINE> <INDENT> lit_to_clauses = defaultdict(set) <NEW_LINE> for c in relevant_clauses: <NEW_LINE> <INDENT> for lit in c: <NEW_LINE> <INDENT> lit_to_clauses[abs(lit)].add(c) <NEW_LINE> <DEDENT> <DEDENT> lit_to_clauses = dict(lit_to_clauses) <NEW_LINE> d...
Return a tuple of paths representing conflicts between a set of clauses. See https://github.com/enthought/sat-solver/wiki/Unsatisfiability-Error-Messages for discussion about how best to implement this.
625941ba30dc7b7665901811
def random_distort(img, angle): <NEW_LINE> <INDENT> new_img = img.astype(float) <NEW_LINE> value = np.random.randint(-28, 28) <NEW_LINE> if value > 0: <NEW_LINE> <INDENT> mask = (new_img[:,:,0] + value) > 255 <NEW_LINE> <DEDENT> if value <= 0: <NEW_LINE> <INDENT> mask = (new_img[:,:,0] + value) < 0 <NEW_LINE> <DEDENT> ...
method for adding random distortion to dataset images, including random brightness adjust and shadow
625941babe8e80087fb20aef
def add_datetime(orig_datetime, units='seconds=1'): <NEW_LINE> <INDENT> k = dict() <NEW_LINE> for u in units.split(","): <NEW_LINE> <INDENT> x = u.split('=') <NEW_LINE> p = x[0].lower() <NEW_LINE> k[p if p[-1] == 's' else p+'s'] = int(x[1]) <NEW_LINE> <DEDENT> return orig_datetime + relativedelta.relativedelta(**k)
Add delta to datetime :param orig_datetime: the base datetime/ date :param units: the units to be added, e.g. month=1,day=-2,hour=3,minute=-7 :return: added result
625941ba76d4e153a657e9d7
def testTransactionTemplateItem(self): <NEW_LINE> <INDENT> pass
Test TransactionTemplateItem
625941ba5fc7496912cc382d
def _check_weights(self): <NEW_LINE> <INDENT> for one_layer in self.model.layers: <NEW_LINE> <INDENT> print ('layer = ',one_layer) <NEW_LINE> print ('weights =', one_layer.get_weights()) <NEW_LINE> print ('weights shape = ', np.shape(one_layer.get_weights()))
Print the weights of layers. For debug purpose, not using anywhere.
625941ba23e79379d52ee40e
def test_template_cli_5(self): <NEW_LINE> <INDENT> with self.assertRaises(subprocess.CalledProcessError) as error: <NEW_LINE> <INDENT> self.run_test_on_template_fixture(number=5) <NEW_LINE> <DEDENT> self.assertIn( "NoInputOptionNotHandledByTemplateError", error.exception.stderr.decode() )
Run the test on the test template 5. - The initialize.py doesn't cater for no-input, raise exception.
625941ba7b25080760e39302
def agdispQaqc(model, csv_path): <NEW_LINE> <INDENT> pd_obj_inputs = pd.read_csv(csv_path, index_col=0, header=None, skiprows=1, skipfooter=46, engine='python') <NEW_LINE> pd_obj_inputs = pd_obj_inputs.drop(labels=pd_obj_inputs.columns[range(4)], axis=1) <NEW_LINE> pd_obj_inputs.index.name = None <NEW_LINE> pd_obj_inpu...
Read in QAQC CSV as Pandas DataFrame, removing any uneeded columns, setting the index_col name to None, and renumbering the data columns.
625941baaad79263cf3908e3
def rhobca_rate(params, state, dx, Sca): <NEW_LINE> <INDENT> N = params['N'] <NEW_LINE> Np = params['Np'] <NEW_LINE> rhob_ca = state['rhob_ca'] <NEW_LINE> v = state['v'] <NEW_LINE> drhobca_dt = np.zeros(N) <NEW_LINE> drhobca_dt[0] = -1 / dx[0] * (-rhob_ca[1] * v[1] + rhob_ca[0] * v[0]) + Sca[0] <NEW_LINE> drhobca_dt[1:...
Calculate char accumulation rate.
625941bae1aae11d1e749b5c
def log_model_neptune( checkpoint_path: pathlib.Path, save_directory: pathlib.Path, name: str, neptune_logger, ): <NEW_LINE> <INDENT> checkpoint = torch.load(checkpoint_path) <NEW_LINE> model = checkpoint["hyper_parameters"]["model"] <NEW_LINE> torch.save(model.state_dict(), save_directory / name) <NEW_LINE> neptune_lo...
Saves the model to disk, uploads it to neptune and removes it again.
625941badc8b845886cb53dc
def test_stdout(test, capfd): <NEW_LINE> <INDENT> logging.disable(logging.CRITICAL) <NEW_LINE> try: <NEW_LINE> <INDENT> process = sh.sh("-c", "echo test1; echo test2 >&2; echo тест3; echo тест4 >&2;", _stdout=STDOUT) <NEW_LINE> process.execute() <NEW_LINE> assert process.stdout() == "" <NEW_LINE> assert process.stderr(...
Tests output to stdout.
625941ba50485f2cf553cc40
def test_convert_bad_remote_pnglist(self): <NEW_LINE> <INDENT> self.assertAllTargetFormatsRaise(Exception, [ 'http://localhost:62010/www/icon16x16.png', 'http://localhost:62010/www/foo.png', 'http://localhost:62010/www/icon32x32.png' ])
Test conversion from bad remote source.
625941ba1d351010ab8559c4
def alter_list_data_to_serialize(self, request, data): <NEW_LINE> <INDENT> shape_type = request.GET.get('shape_type', 'simple') <NEW_LINE> for obj in data['objects']: <NEW_LINE> <INDENT> if shape_type != 'simple': <NEW_LINE> <INDENT> del obj.data['simple_shape'] <NEW_LINE> <DEDENT> if shape_type != 'full': <NEW_LINE> <...
Allow the selection of simple, full or no shapes using a query parameter.
625941ba0c0af96317bb8090
def _check_for_peers(self) -> None: <NEW_LINE> <INDENT> for peer in list(self.peers.values()): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> their_peers = self._recoverable_get( peer, '--node', 'internal', 'peers', '--edit', default={}) <NEW_LINE> <DEDENT> except exceptions.FailedQuery: <NEW_LINE> <INDENT> continue <NEW...
none -> none check our peers' peer lists to see if they know anyone we don't, also works as a heartbeat to our connected peers
625941ba3c8af77a43ae3645
def parse_xml(self, xml_doc): <NEW_LINE> <INDENT> self.__reset_dom__() <NEW_LINE> try: <NEW_LINE> <INDENT> self.dom = xml.dom.minidom.parseString(xml_doc) <NEW_LINE> self.dom.normalize() <NEW_LINE> <DEDENT> except xml.parsers.expat.ExpatError as msg: <NEW_LINE> <INDENT> self.errors.append((2001, None, _T('Invalid XML d...
Parse XML into DOM object.
625941ba4c3428357757c1d2
def test_got_buckets_return(self): <NEW_LINE> <INDENT> self.kz_partitioner.acquired = True <NEW_LINE> self.kz_partitioner.__iter__.return_value = [2, 3] <NEW_LINE> self.buckets_got = None <NEW_LINE> d = Deferred() <NEW_LINE> def got_buckets(_buckets): <NEW_LINE> <INDENT> self.buckets_got = _buckets <NEW_LINE> return d ...
`got_buckets` return value is propogated to timerservice that ensures that the service stops after returned deferred is fired
625941ba97e22403b379ce40
def remoteCompletion(self, text): <NEW_LINE> <INDENT> self.__sendCommand("%s%s\n" % (RequestCompletion, text))
Public slot to get the a list of possible commandline completions from the remote client. @param text the text to be completed (string or QString)
625941ba07f4c71912b1132f
def rmtree(directory: str, ignore_errors=False): <NEW_LINE> <INDENT> LOG.debug("Removing directory tree %s", directory) <NEW_LINE> shutil.rmtree( directory, ignore_errors=ignore_errors, onerror=handle_remove_readonly )
Remove directory and contents.
625941ba507cdc57c6306b7c
def get_skyblock_news(self): <NEW_LINE> <INDENT> response = general.do_request(BASE_URL, 'skyblock/news', {'key': self.api_key}).json() <NEW_LINE> return response['items']
Returns a dict containing skyblock news with a title, description and thread
625941bae5267d203edcdb48
def update_file(self, name, message, content): <NEW_LINE> <INDENT> self.sha = self.get_contents(name)['sha'] <NEW_LINE> self.payload = json.dumps({'message': message, 'content': base64.b64encode(content), 'sha': self.sha}) <NEW_LINE> r = self.session.put(self.url + name, data=self.payload) <NEW_LINE> if r.status_code =...
Updates a file in Github repo Args: name: Name of the file to be updated message: Commit message content: Content of commit
625941ba3539df3088e2e1f3
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todoRest.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sur...
Run administrative tasks.
625941baa05bb46b383ec6cc
def get_disks_in_pci_address(pci_address): <NEW_LINE> <INDENT> disks_path = "/dev/disk/by-path/" <NEW_LINE> disk_list = [] <NEW_LINE> for dev in os.listdir(disks_path): <NEW_LINE> <INDENT> if pci_address in dev: <NEW_LINE> <INDENT> link = os.readlink(os.path.join(disks_path, dev)) <NEW_LINE> disk_list.append(os.path.ab...
Gets disks in a PCI address. :param pci_address: Any segment of a PCI address (1f, 0000:00:1f, ...) :return: list of disks in a PCI address.
625941ba8e71fb1e9831d655
def skip_forward(x, n_out_channels): <NEW_LINE> <INDENT> N, n_in_channels, H, W = x.shape <NEW_LINE> assert (n_in_channels == n_out_channels) or ( n_out_channels == n_in_channels*2), 'Invalid n_out_channels' <NEW_LINE> skip = np.array(x, copy=True) <NEW_LINE> pool_cache, downsampled, skip_p = None, False, 0 <NEW_LINE> ...
Computes the forward pass for a skip connection. The input x has shape (N, d_1, d_2, d_3) where x[i] is the ith input. If n_out_channels is equal to 2* d_1, downsampling and padding are applied else, the input is replicated in output Inputs: x - Input data, of shape (N, d_1, d_2, d_3) n_out_channels - Number of channel...
625941bae64d504609d746e8
def test_makeAMZDate(self): <NEW_LINE> <INDENT> instant = datetime.datetime(2016, 11, 11, 2, 45, 50) <NEW_LINE> self.assertEqual(makeAMZDate(instant), "20161111T024550Z")
A L{datetime.datetime} instance is formatted according to the convention for AMZ dates.
625941ba5e10d32532c5edd6
def _find_lineage_for_domains(config, domains): <NEW_LINE> <INDENT> if config.duplicate: <NEW_LINE> <INDENT> return "newcert", None <NEW_LINE> <DEDENT> ident_names_cert, subset_names_cert = cert_manager.find_duplicative_certs(config, domains) <NEW_LINE> if ident_names_cert is None and subset_names_cert is None: <NEW_LI...
Determine whether there are duplicated names and how to handle them (renew, reinstall, newcert, or raising an error to stop the client run if the user chooses to cancel the operation when prompted). :returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew...
625941ba4a966d76dd550eb5
def subSplats( self, res=None, req=None ): <NEW_LINE> <INDENT> if req is not None: <NEW_LINE> <INDENT> source = self.request_dict <NEW_LINE> dikt = req <NEW_LINE> <DEDENT> elif res is not None: <NEW_LINE> <INDENT> source = self.response_dict <NEW_LINE> dikt = res <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Valu...
Asterisk (the Splat) matches all values. A translation dictionary entry of the form: 'field': { '*': { 'other': 'value' || None }} or even 'field': { '*': { 'other': '*' }} is handled in this function. The second mechanism provides a way to switch original vals to a new key. E.g. the subdict: 'field1': {...
625941baa8370b7717052749
def print_board(player_board, opponent_board, hitmiss, score_dic, fleet_list): <NEW_LINE> <INDENT> alphabet = ["A","B","C","D","E","F","G","H","I","J"] <NEW_LINE> if sys.platform.startswith('linux') or sys.platform.startswith('darwin'): <NEW_LINE> <INDENT> os.system('clear') <NEW_LINE> <DEDENT> elif sys.plaform.startsw...
prints the boards to the screen including scores and sunk ships
625941babe7bc26dc91cd4ad
def _get_index_name_by_column(table, column_name): <NEW_LINE> <INDENT> for _, index_metadata in six.iteritems(table.indexes): <NEW_LINE> <INDENT> options = dict(index_metadata.index_options) <NEW_LINE> if 'target' in options and options['target'] == column_name: <NEW_LINE> <INDENT> return index_metadata.name <NEW_LINE>...
Find the index name for a given table and column.
625941bac4546d3d9de728d9
def execute(self, sql, args): <NEW_LINE> <INDENT> self.__cur.execute(sql, args) <NEW_LINE> return self.__cur
The database cursor.
625941ba498bea3a759b9959
def upload(self, filename): <NEW_LINE> <INDENT> response = None <NEW_LINE> try: <NEW_LINE> <INDENT> with open(filename, 'rb') as file: <NEW_LINE> <INDENT> body = file.read() <NEW_LINE> <DEDENT> url = urlparse(self._url) <NEW_LINE> response = post_multipart(url, fields=None, files=[('myfile', path.basename(filename), bo...
Effettua l'upload del file. Restituisce la risposta ricevuta dal repository o None se c'è stato un problema.
625941ba187af65679ca4fc6
def _enqueue(self, queue_name, next_queue, plugin, command, server, channel, nick, message): <NEW_LINE> <INDENT> user = nick.split('!')[0] <NEW_LINE> if not user in self._command_queues[queue_name]: <NEW_LINE> <INDENT> self._command_queues[queue_name][user] = [] <NEW_LINE> <DEDENT> self._command_queues[queue_name][user...
Adds a command to the appropriate queue for later processing.
625941ba96565a6dacc8f57d
def _allMetrics(self): <NEW_LINE> <INDENT> return [metric for an in self.ps.analyses for metric in an.metrics]
Returns all metrics except for ones in transient analysis
625941ba566aa707497f4421
def save_training_result(self, im_name, im, dir=False, epoch=0): <NEW_LINE> <INDENT> if dir: <NEW_LINE> <INDENT> save_path = os.path.join(self.sample, str(epoch)) <NEW_LINE> if not os.path.exists(save_path): <NEW_LINE> <INDENT> os.mkdir(save_path) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> save_path = self....
save test result during training procedure, [tensor, Variable] :param im_name: :param im: :param dir: /sample/epoch/i.png :param epoch: :return:
625941bad53ae8145f87a11e