code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def parse_color_setting(config_string): <NEW_LINE> <INDENT> if not config_string: <NEW_LINE> <INDENT> return PALETTES[DEFAULT_PALETTE] <NEW_LINE> <DEDENT> parts = config_string.lower().split(";") <NEW_LINE> palette = PALETTES[NOCOLOR_PALETTE].copy() <NEW_LINE> for part in parts: <NEW_LINE> <INDENT> if part in PALETTES:... | Parse a DJANGO_COLORS environment variable to produce the system palette
The general form of a palette definition is:
"palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option"
where:
palette is a named palette; one of 'light', 'dark', or 'nocolor'.
role is a named style used by Django
... | 625941c7c432627299f04c82 |
def get_scheme_obj(self): <NEW_LINE> <INDENT> return self.scheme_obj | Get the scheme file used during the process. | 625941c7a4f1c619b28b0079 |
@main.route('/') <NEW_LINE> def index(): <NEW_LINE> <INDENT> event = Event( title="title", description="description", date_and_time="Date and Time", guests ="guests" ) <NEW_LINE> db.session.add(event) <NEW_LINE> db.session.commit() <NEW_LINE> return render_template('index.html', event=event) | Show upcoming events to users! | 625941c7be7bc26dc91cd63f |
def test_aggregate_alert(self): <NEW_LINE> <INDENT> rv = self.app.get('/aggregate_alerts', headers=settings.header) <NEW_LINE> self.assertEqual(rv.status_code, 200) <NEW_LINE> data = json.loads(rv.data.decode("utf-8")) <NEW_LINE> self.assertEqual(data["total"], 8) <NEW_LINE> self.assertEqual(sorted(list(data.keys())), ... | test aggregate_alerts | 625941c756ac1b37e626420f |
def endGame(self): <NEW_LINE> <INDENT> pass | Update e greedy and game buffer | 625941c7dc8b845886cb5572 |
def _vm_cleanup(self, hostname=None): <NEW_LINE> <INDENT> if hostname: <NEW_LINE> <INDENT> vm = VirtualMachine( hostname=hostname, target_image=hostname, provisioning_server=self.libvirt_vm, distro=DISTRO_RHEL7, ) <NEW_LINE> vm._created = True <NEW_LINE> vm.destroy() | Cleanup the VM from provisioning server
:param str hostname: The content host hostname | 625941c7e64d504609d7487d |
def __init__(self, compute, project, backend_service_name, network, subnetwork, preserve_instance_external_ip, region): <NEW_LINE> <INDENT> super(InternalBackendService, self).__init__(compute, project, backend_service_name, network, subnetwork, preserve_instance_external_ip, region) <NEW_LINE> self.log() | Initialization
Args:
compute: google compute engine
project: project ID
backend_service_name: name of the backend service
network: target network
subnetwork: target subnet
preserve_instance_external_ip: whether to preserve the external IP
region: region of the backend service | 625941c763d6d428bbe4452d |
def index(request): <NEW_LINE> <INDENT> justlogout = False <NEW_LINE> autherror = False <NEW_LINE> seaf_root = settings.SEAFILE_ROOT <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> return HttpResponseRedirect(reverse('private')) <NEW_LINE> <DEDENT> if request.method == 'POST': <NEW_LINE> <INDENT> for... | Main login view | 625941c7462c4b4f79d1d70e |
def transit_shape(tt, smooth=0.02): <NEW_LINE> <INDENT> return logistic(abs(tt) - 0.5, smooth) - 1. | A single transit of unit width and depth, centered at zero | 625941c7d6c5a10208144087 |
def execute(self, path, args, mode=None, maximize=False): <NEW_LINE> <INDENT> dll = self.options.get("dll") <NEW_LINE> free = self.options.get("free") <NEW_LINE> source = self.options.get("from") <NEW_LINE> self.init_regkeys(self.REGKEYS) <NEW_LINE> p = Process() <NEW_LINE> if not p.execute(path=path, args=args, dll=dl... | Starts an executable for analysis.
@param path: executable path
@param args: executable arguments
@param mode: monitor mode - which functions to instrument
@param maximize: whether the GUI should start maximized
@return: process pid | 625941c794891a1f4081bae6 |
def catalog_0(self, *tokens): <NEW_LINE> <INDENT> request = cherrypy.request <NEW_LINE> try: <NEW_LINE> <INDENT> cat = self.repo.get_catalog(pub=self._get_req_pub()) <NEW_LINE> <DEDENT> except srepo.RepositoryError as e: <NEW_LINE> <INDENT> cherrypy.log("Request failed: {0}".format(str(e))) <NEW_LINE> raise cherrypy.HT... | Provide a full version of the catalog, as appropriate, to
the requesting client. Incremental catalogs are not supported
for v0 catalog clients. | 625941c77b25080760e39497 |
def cross(v1, v2): <NEW_LINE> <INDENT> return v1[0]*v2[1] - v1[1]*v2[0] | The cross product between the vector and other vector
v1.cross(v2) -> v1.x*v2.y - v2.y*v1.x
:return: The cross product | 625941c744b2445a339320d4 |
def dataFromPacket(self, packet): <NEW_LINE> <INDENT> if packet is None or not isinstance(packet, tuple): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pkgid, header = packet <NEW_LINE> data = None <NEW_LINE> try: <NEW_LINE> <INDENT> data = header[KEY_DATA] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass... | Fills data information on the scan from json packet
:param packet: tuple()
:return: | 625941c791af0d3eaac9ba55 |
def _execute(self, source, hidden): <NEW_LINE> <INDENT> if not hidden: <NEW_LINE> <INDENT> self.executing.emit(source) <NEW_LINE> <DEDENT> msg_id = self.kernel_client.execute(source, hidden) <NEW_LINE> self._request_info['execute'][ msg_id] = self._ExecutionRequest(msg_id, 'user') <NEW_LINE> self._hidden = hidden | Execute 'source'. If 'hidden', do not show any output.
See parent class :meth:`execute` docstring for full details.
Overriden copy to move 'executing' event before it is actually executed | 625941c73c8af77a43ae37dd |
def getRamdisk(self, size=0, mountpoint="", ramdiskType=""): <NEW_LINE> <INDENT> if not ramdiskType in self.validRamdiskTypes: <NEW_LINE> <INDENT> raise BadRamdiskTypeException("Not a valid ramdisk type") <NEW_LINE> <DEDENT> if size and mountpoint and ramdiskType: <NEW_LINE> <INDENT> if self.myosfamily == "darwin": <NE... | Getter for the ramdisk instance.
@var: ramdisks - a list of ramdisks this factory has created
:param size: (Default value = 0)
:param mountpoint: (Default value = "")
:param ramdiskType: (Default value = "") | 625941c73317a56b86939c98 |
def initialize(name=None,**kwargs): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = sys.argv[0] or '' <NEW_LINE> <DEDENT> kwargs['name'] = name <NEW_LINE> app_config.update(kwargs) <NEW_LINE> for key, func in dict(initialization_rack).items(): <NEW_LINE> <INDENT> if not initialization_rack[key]: <NEW_LI... | Invokes the initialization code for all the izaber.* modules
that are hanging off of the system. | 625941c763b5f9789fde7123 |
def shoot(cp, alpha, kernel_width, n_steps=10): <NEW_LINE> <INDENT> dt = 1/n_steps <NEW_LINE> traj_cp = [cp] <NEW_LINE> traj_alpha = [alpha] <NEW_LINE> for i in range(1,n_steps): <NEW_LINE> <INDENT> cp, alpha = traj_cp[-1], traj_alpha[-1] <NEW_LINE> result_cp,result_alpha = discretisation_step(cp,alpha,dt,kernel_width)... | TO DO
------------
This is the trajectory of a Hamiltonian dynamic, with system seen in lecture notes.
Compute here trajectories of control points and alpha from t=0 to t=1.
------------
cp is of shape (n_landmarks, 2)
alpha is of shape (n_landmarks, 2)
n_step : number of steps in your hamiltonian trajectory, use to d... | 625941c78c3a8732951583f7 |
def copyRandomList(self, head): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> p = head <NEW_LINE> while p: <NEW_LINE> <INDENT> pn = Node(p.val, p.next) <NEW_LINE> p.next = pn <NEW_LINE> p = pn.next <NEW_LINE> <DEDENT> p = head <NEW_LINE> while p: <NEW_LINE> <INDENT> if p.random: <... | :type head: Node
:rtype: Node | 625941c7cc40096d6159598e |
def vertices(self, exclude_sandwiched=False): <NEW_LINE> <INDENT> import itertools <NEW_LINE> from sage.matroids.all import Matroid <NEW_LINE> R = self.parent().base_ring() <NEW_LINE> parallels = self._parallel_hyperplanes() <NEW_LINE> A_list = [parallel[0][1] for parallel in parallels] <NEW_LINE> b_list_list = [[-hype... | Return the vertices.
The vertices are the zero-dimensional faces, see
:meth:`face_vector`.
INPUT:
- ``exclude_sandwiched`` -- boolean (default:
``False``). Whether to exclude hyperplanes that are
sandwiched between parallel hyperplanes. Useful if you only
need the convex hull.
OUTPUT:
The vertices in a sorte... | 625941c76fece00bbac2d77b |
@pytest.mark.rhv2 <NEW_LINE> def test_change_cpu_ram(provisioner, soft_assert, provider, prov_data, vm_name): <NEW_LINE> <INDENT> prov_data['catalog']["vm_name"] = vm_name <NEW_LINE> prov_data['hardware']["num_sockets"] = "4" <NEW_LINE> prov_data['hardware']["cores_per_socket"] = "1" if not provider.one_of(SCVMMProvide... | Tests change RAM and CPU in provisioning dialog.
Prerequisities:
* A provider set up, supporting provisioning in CFME
Steps:
* Open the provisioning dialog.
* Apart from the usual provisioning settings, set number of CPUs and amount of RAM.
* Submit the provisioning request and wait for it to finish.
... | 625941c74428ac0f6e5ba82f |
def exist_expand(self, long_url): <NEW_LINE> <INDENT> result = self.db.where(table='url', what='shorten', expand=long_url) <NEW_LINE> if result: <NEW_LINE> <INDENT> return result[0] | 检查数据库中是否已有相关记录,有则返回短 URL
| 625941c745492302aab5e300 |
@main.route('/suppliers/assessments/trigger', methods=['POST']) <NEW_LINE> @login_required <NEW_LINE> @role_required('admin') <NEW_LINE> def trigger_assessment(): <NEW_LINE> <INDENT> data_api_client.req.assessments().post(data={ 'assessment': { 'brief_id': request.form['brief_id'], 'domain_name': request.form['domain_n... | Triggers a domain assessment for a supplier. | 625941c7090684286d50ed22 |
def detectCycle(self, head): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> slow, fast = head, head <NEW_LINE> while fast is not None: <NEW_LINE> <INDENT> fast = fast.next <NEW_LINE> if fast is not None: <NEW_LINE> <INDENT> fast = fast.next <NEW_LINE> <DEDENT> slow = slow.next <NEW... | :type head: ListNode
:rtype: ListNode | 625941c7187af65679ca515c |
def start_service(): <NEW_LINE> <INDENT> dCon = DictionaryController() <NEW_LINE> dispatcher = cherrypy.dispatch.RoutesDispatcher() <NEW_LINE> dispatcher.connect('dict_get_key', '/dictionary/:key', controller=dCon, action='GET_KEY', conditions=dict(method=['GET'])) <NEW_LINE> dispatcher.connect('dict_put_key', '/dictio... | configures and runs the server | 625941c7ff9c53063f47c232 |
def _check_generation(self): <NEW_LINE> <INDENT> session = self._meta_data['bigip']._meta_data['icr_session'] <NEW_LINE> response = session.get(self._meta_data['uri']) <NEW_LINE> current_gen = response.json().get('generation', None) <NEW_LINE> if current_gen is not None and current_gen != self.generation: <NEW_LINE> <I... | Check that the generation on the BIG-IP® matches the object
This will do a get to the objects URI and check that the generation
returned in the JSON matches the one the object currently has. If it
does not it will raise the `GenerationMismatch` exception. | 625941c724f1403a92600ba5 |
def add_child(self, router): <NEW_LINE> <INDENT> assert isinstance(router, Router), 'Not a valid Router' <NEW_LINE> assert router is not self, 'cannot add self to children' <NEW_LINE> for r in self.routes: <NEW_LINE> <INDENT> if r == router: <NEW_LINE> <INDENT> return r <NEW_LINE> <DEDENT> elif r._route == router._rout... | Add a new :class:`Router` to the :attr:`routes` list.
| 625941c7566aa707497f45a8 |
def GetResources(self): <NEW_LINE> <INDENT> _menu = "Intersection" <NEW_LINE> _tip = "Set snapping to the intersection of edges." <NEW_LINE> return {'Pixmap': 'Snap_Intersection', 'MenuText': QT_TRANSLATE_NOOP("Draft_Snap_Intersection", _menu), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Snap_Intersection", _tip)} | Set icon, menu and tooltip. | 625941c726238365f5f0eeaa |
def _rectify_hashlen(hashlen): <NEW_LINE> <INDENT> if hashlen is NoParam or hashlen == 'default': <NEW_LINE> <INDENT> return DEFAULT_HASHLEN <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return hashlen | Example:
>>> assert _rectify_hashlen(NoParam) is DEFAULT_HASHLEN
>>> assert _rectify_hashlen(8) == 8 | 625941c7498bea3a759b9aed |
def _add_index_server(self): <NEW_LINE> <INDENT> index_servers = '\n\t'.join(self.servers.keys()) <NEW_LINE> self.conf.set('distutils', 'index-servers', index_servers) | Adds index-server to 'distutil's 'index-servers' param. | 625941c7d8ef3951e324357b |
def show_graph_stats(dag_nodes, node_segments): <NEW_LINE> <INDENT> csize = 20 <NEW_LINE> ecnts = [len(ns) for _, ns in dag_nodes.iteritems()] <NEW_LINE> ncnts = [len(ns) for _, ns in node_segments.iteritems()] <NEW_LINE> necnts = [len(ns) for i, ns in node_segments.iteritems() if i in dag_nodes] <NEW_LINE> len_ecnts =... | :param dag_nodes: directed edge dictionary mapping node-id to set of node-ids.
:param node_segments: dictionary mapping start node-ids to the segments which grow from them. | 625941c7baa26c4b54cb115e |
def add_organism(self, org): <NEW_LINE> <INDENT> organism = self.find_by_o_id(org) <NEW_LINE> if organism is None: <NEW_LINE> <INDENT> organism = Organism(org) <NEW_LINE> self.organisms.append(organism) | Creates and adds an Organism object whose name is designated by org
to this object's 'organisms' member, if no such object is present in the
list.
The 'organisms' member is modified.
:param org: species name | 625941c7dd821e528d63b1e8 |
def general_poly(L): <NEW_LINE> <INDENT> def Sum(base): <NEW_LINE> <INDENT> power = len(L) - 1 <NEW_LINE> result = 0 <NEW_LINE> for i in L: <NEW_LINE> <INDENT> result += i * base**power <NEW_LINE> power -= 1 <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> return Sum | L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 | 625941c729b78933be1e56eb |
def factorial(n): <NEW_LINE> <INDENT> fact = 1 <NEW_LINE> while(n > 1): <NEW_LINE> <INDENT> fact = n * fact <NEW_LINE> n = n - 1 <NEW_LINE> <DEDENT> return fact | Calculate factorial using while | 625941c78a43f66fc4b540a4 |
def __init__(self, kwargs): <NEW_LINE> <INDENT> dict.__init__(self, kwargs) | constructor | 625941c71f037a2d8b94623c |
def __init__(self, loc, map_only, team_number): <NEW_LINE> <INDENT> Agent.__init__(self, loc, map_only, team_number) <NEW_LINE> self.direction = [0, 0] <NEW_LINE> self.isDone = False | Constructor
Parameters
----------
self : object
CapEnv object | 625941c7ac7a0e7691ed410c |
def _parse(formula): <NEW_LINE> <INDENT> q = [] <NEW_LINE> mol = {} <NEW_LINE> i = 0 <NEW_LINE> while i < len(formula): <NEW_LINE> <INDENT> token = formula[i] <NEW_LINE> if token in CLOSERS: <NEW_LINE> <INDENT> m = re.match('\d+', formula[i+1:]) <NEW_LINE> if m: <NEW_LINE> <INDENT> weight = int(m.group(0)) <NEW_LINE> i... | Return the molecule dict and length of parsed part.
Recurse on opening brackets to parse the subpart and
return on closing ones because it is the end of said subpart. | 625941c7a05bb46b383ec860 |
def GetForegroundValue(self): <NEW_LINE> <INDENT> return _itkBinaryMorphologicalClosingImageFilterPython.itkBinaryMorphologicalClosingImageFilterIUL2IUL2SE2_GetForegroundValue(self) | GetForegroundValue(self) -> unsigned long | 625941c7b7558d58953c4f54 |
def p_stmt(p): <NEW_LINE> <INDENT> if p[2] == '=': <NEW_LINE> <INDENT> p[0] = ('assign' , p[1] , p[3]) <NEW_LINE> <DEDENT> elif p[1] == 'input': <NEW_LINE> <INDENT> p[0] = ('input' , p[2] , p[3]) <NEW_LINE> <DEDENT> elif p[1] == 'print': <NEW_LINE> <INDENT> p[0] = ('print' , p[2] , p[3]) <NEW_LINE> <DEDENT> elif p[1] =... | stmt : ID '=' exp
| INPUT opt_string ID
| PRINT value value_list
| IF exp THEN stmt_list opt_else ENDIF
| WHILE exp stmt_list ENDWHILE
| FOR ID '=' exp TO exp opt_step stmt_list NEXT ID | 625941c715fb5d323cde0b4c |
def rle_decode(mask_rle, shape=(1280, 1918, 1)): <NEW_LINE> <INDENT> img = np.zeros(shape[0]*shape[1], dtype=np.uint8) <NEW_LINE> s = mask_rle.split() <NEW_LINE> starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] <NEW_LINE> starts -= 1 <NEW_LINE> ends = starts + lengths <NEW_LINE> for lo, hi... | Функция расшифровывает маску изображения, особый архив масок mask_rle
mask_rle: run-length as string formated (start length)
shape: (height,width) of array to return
Returns numpy array, 1 - mask, 0 - background | 625941c77cff6e4e811179c4 |
def is_expired(snap): <NEW_LINE> <INDENT> exp_epoch = int(snap.split("_")[const.VLAB_SNAP_EXPIRES]) <NEW_LINE> current_time = int(time.time()) <NEW_LINE> return exp_epoch < current_time | Determine if the snapshot is expired
:Returns: Boolean
:param snap: The name of the snapshot
:type snap: String | 625941c731939e2706e4ceaa |
def QueryMaliciousRegistration(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("QueryMaliciousRegistration", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.QueryMa... | 商户恶意注册接口
:param request: Request instance for QueryMaliciousRegistration.
:type request: :class:`tencentcloud.cpdp.v20190820.models.QueryMaliciousRegistrationRequest`
:rtype: :class:`tencentcloud.cpdp.v20190820.models.QueryMaliciousRegistrationResponse` | 625941c74f6381625f114a7a |
def validate_args(parsed_args): <NEW_LINE> <INDENT> supported_distros = ['Android', 'Ubuntu', 'Debian', 'OSX', 'Fedora', 'Arch Linux', 'openSUSE', 'Automatic', 'mingw32', 'mingw64'] <NEW_LINE> if parsed_args.distribution not in supported_distros: <NEW_LINE> <INDENT> print('Distribution \''+parsed_args.distribution+'\' ... | Validate the args values, exit if error is found | 625941c7fb3f5b602dac36d0 |
def get_frame(self): <NEW_LINE> <INDENT> success, rawFrame = self.video.read() <NEW_LINE> ret, frame = cv2.imencode(".jpg", rawFrame) <NEW_LINE> return frame.tobytes() | Capture one frame from the web cam, encode it to .jpg format
and returns it in bytes for use by "camera_stream". | 625941c7d58c6744b4257c9e |
def move_humans(self, zombie_distance): <NEW_LINE> <INDENT> width = self.get_grid_width() <NEW_LINE> height = self.get_grid_height() <NEW_LINE> visited = poc_grid.Grid(height, width) <NEW_LINE> obstacle = len(zombie_distance) * len(zombie_distance[0]) <NEW_LINE> human_list = [] <NEW_LINE> for human in self.humans(): <N... | Function that moves humans away from zombies, diagonal moves
are allowed | 625941c7b5575c28eb68e03e |
def div(a,b): <NEW_LINE> <INDENT> c=a/b <NEW_LINE> return c | division of two numbers | 625941c74e4d5625662d4418 |
def rsa_verify(public_key, plaintext, signature): <NEW_LINE> <INDENT> hsh = sha512_hash(plaintext) <NEW_LINE> signature_tuple = (signature, ) <NEW_LINE> return public_key.verify(hsh, signature_tuple) == True | Hash and and verify a plain text using a public key. | 625941c7c4546d3d9de72a71 |
def prepare(self, direction): <NEW_LINE> <INDENT> self.fill_grub_device_entry() <NEW_LINE> self.fill_partition_list() <NEW_LINE> self.translate_ui() <NEW_LINE> self.show_all() <NEW_LINE> button = self.ui.get_object('partition_encryption_settings') <NEW_LINE> button.set_sensitive(False) <NEW_LINE> button.hide() <NEW_LIN... | Prepare our dialog to show/hide/activate/deactivate what's necessary | 625941c766673b3332b920cf |
@cli_repo.command(name='list') <NEW_LINE> @click.option('-i', '--index', required=False, help='Repository index file') <NEW_LINE> def list_repository(index): <NEW_LINE> <INDENT> loader = DictLoader(util.read_index(index)) if index is not None else UrlLoader() <NEW_LINE> datasets = RepositoryManager(doc=loader.load()).f... | List repository index content. | 625941c79f2886367277a8cc |
def get_bumpers(self): <NEW_LINE> <INDENT> reply = self.get_sensor_packet(OI_PACKET_BUMPS_AND_WHEEL_DROPS) <NEW_LINE> return byte_to_bumpers(ord(reply[0])) | Gets the current state of the bumper, as the list of pressed parts.
The returned list contains the bumper part ids (OI_BUMPER_xxx) and can be
empty if the bumper is currently not pressed. | 625941c75fdd1c0f98dc0271 |
def __eq__(self, other): <NEW_LINE> <INDENT> if self.h == other.h and self.m == other.m and self.s == other.s: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | (Horario, Horario) -> Horario
Recebe referencias `self` e `other` a objetos da classe Horario.
Retorna True se o horário `self` é igual ao horário `other` e
retorna False em caso contrário.
Este método é utilizado pelo Python quando escrevemos "Horario == Horario".
Exemplos:
>>> t1 = Horario(8,1,59)
>>> t2 = Horar... | 625941c771ff763f4b5496c8 |
def update_arrays_with_http_info(self, array_settings, **kwargs): <NEW_LINE> <INDENT> all_params = ['array_settings'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LIN... | Update arrays
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_arrays_with_http_info(array_settings, call... | 625941c70a50d4780f666ed0 |
def execute_drop(item_id): <NEW_LINE> <INDENT> verif=False <NEW_LINE> for item in inventory: <NEW_LINE> <INDENT> if item_id in item["id"]: <NEW_LINE> <INDENT> verif=True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if verif: <NEW_LINE> <INDENT> current_room["items"].append(item) <NEW_LINE> inventory.remove(item) <NEW_... | This function takes an item_id as an argument and moves this item from the
player's inventory to list of items in the current room. However, if there is
no such item in the inventory, this function prints "You cannot drop that." | 625941c71d351010ab855b5b |
def setup(self, bottom, top): <NEW_LINE> <INDENT> params = eval(self.param_str) <NEW_LINE> self.dir = params['dir'] <NEW_LINE> self.train = params['train'] <NEW_LINE> self.split = params['split'] <NEW_LINE> self.mean = np.array(params['mean']) <NEW_LINE> self.random = params.get('randomize', True) <NEW_LINE> self.seed ... | Setup data layer according to parameters:
- sbdd_dir: path to SBDD `dataset` dir
- split: train / seg11valid
- mean: tuple of mean values to subtract
- randomize: load in random order (default: True)
- seed: seed for randomization (default: None / current time)
for SBDD semantic segmentation.
N.B.segv11alid is the s... | 625941c7d268445f265b4ead |
def list(self): <NEW_LINE> <INDENT> return self._invoke('list', None) | Get monitored items list
:rtype: :class:`list` of :class:`Monitoring.MonitoredItem`
:return: list of names
:raise: :class:`com.vmware.vapi.std.errors_client.Error`
Generic error | 625941c7046cf37aa974cd87 |
def get_random(min, max): <NEW_LINE> <INDENT> return random.randrange(min, max + 1) | returns a random number within the given range | 625941c730bbd722463cbe04 |
def delete_request(self, resource): <NEW_LINE> <INDENT> path = os.path.join('.', resource) <NEW_LINE> if resource == 'csumn': <NEW_LINE> <INDENT> ret = MOVED_PERMANENTLY <NEW_LINE> <DEDENT> elif not os.path.exists(resource): <NEW_LINE> <INDENT> ret = NOT_FOUND + get_contents('404.html') <NEW_LINE> <DEDENT> elif not che... | Handles DELETE requests. | 625941c756b00c62f0f14697 |
def __repr__(self): <NEW_LINE> <INDENT> return '{}({!r}, {!r})'.format(self.__class__.__name__, self.domain, self.prior) | Return ``repr(self)``. | 625941c7287bf620b61d3aa3 |
def store(self): <NEW_LINE> <INDENT> if Configuration._guarded is not True and self._conf is not None: util.writefile(path=self._path, s=json.dumps(self._conf)) <NEW_LINE> return self | Stores configration file and
writes any changes made. | 625941c7fff4ab517eb2f47a |
def mayViewEvent(self, event): <NEW_LINE> <INDENT> if self.request.get('hide_wf_history_event', False) and event['action'] == 'publish': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | See docstring in interfaces.py. | 625941c750485f2cf553cdd8 |
def test_using_api(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print(JVMAPI.default()) <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> traceback.print_exc(file=sys.stdout) <NEW_LINE> self.fail("failed to load certain classes") <NEW_LINE> <DEDENT> kls_name = str(JVMAPI.forClass(javaClassName=JVMAPI... | Must be able to load the API | 625941c74527f215b584c497 |
@_contextlib.contextmanager <NEW_LINE> def root_dir(): <NEW_LINE> <INDENT> root = _settings.env.root <NEW_LINE> old = _os.getcwd() <NEW_LINE> try: <NEW_LINE> <INDENT> _os.chdir(root) <NEW_LINE> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> _os.chdir(old) | chdir() into the root directory | 625941c7596a897236089b00 |
def newTool(self, datamodel, path): <NEW_LINE> <INDENT> PathLog.track() <NEW_LINE> try: <NEW_LINE> <INDENT> nr = 0 <NEW_LINE> for row in range(datamodel.rowCount()): <NEW_LINE> <INDENT> itemNr = int(datamodel.item(row, 0).data(PySide.QtCore.Qt.EditRole)) <NEW_LINE> nr = max(nr, itemNr) <NEW_LINE> <DEDENT> nr += 1 <NEW_... | Adds a toolbit item to a model | 625941c7d486a94d0b98e184 |
def test_HTTP11_pipelining(test_client): <NEW_LINE> <INDENT> conn = test_client.get_connection() <NEW_LINE> conn.putrequest('GET', '/hello', skip_host=True) <NEW_LINE> conn.putheader('Host', conn.host) <NEW_LINE> conn.endheaders() <NEW_LINE> for trial in range(5): <NEW_LINE> <INDENT> conn._output( ('GET /hello?%s HTTP/... | Test HTTP/1.1 pipelining.
:py:mod:`http.client` doesn't support this directly. | 625941c7a79ad161976cc184 |
def wait_for_mav_type(self, timeout): <NEW_LINE> <INDENT> rospy.loginfo("waiting for MAV_TYPE") <NEW_LINE> loop_freq = 1 <NEW_LINE> rate = rospy.Rate(loop_freq) <NEW_LINE> res = False <NEW_LINE> for i in xrange(timeout * loop_freq): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = self.get_param_srv('MAV_TYPE') <NEW_... | Wait for MAV_TYPE parameter, timeout(int): seconds | 625941c7462c4b4f79d1d70f |
def get_difference(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if self.pc != pc: <NEW_LINE> <INDENT> result.append(('pc', get_hex(pc))) <NEW_LINE> <DEDENT> if self.upc != upc: <NEW_LINE> <INDENT> result.append(('upc', get_hex(upc))) <NEW_LINE> <DEDENT> if self.A != A: <NEW_LINE> <INDENT> result.append(('A', get_h... | 作为上一次状态,与当前状态对比,返回不一致的值 | 625941c7925a0f43d2549eb5 |
def test_category_new(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('manage:category_new')) <NEW_LINE> eq_(response.status_code, 200) <NEW_LINE> response_ok = self.client.post( reverse('manage:category_new'), { 'name': 'Web Dev Talks ' } ) <NEW_LINE> self.assertRedirects(response_ok, reverse('manage:cat... | Category form adds new categories. | 625941c710dbd63aa1bd2be3 |
def cli_parser() -> argparse.ArgumentParser: <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( prog="CLI-HELLO", description="A simple hello-world command line app", epilog=" --- ", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) <NEW_LINE> return parser | Factory function to create parser object for arguments from the command line
Returns
-------
parser : argparse.ArgumentParser | 625941c75fcc89381b1e16fd |
def generator_next_fn(iterator_id_t): <NEW_LINE> <INDENT> def generator_py_func(iterator_id): <NEW_LINE> <INDENT> values = next(generator_state.get_iterator(iterator_id)) <NEW_LINE> try: <NEW_LINE> <INDENT> flattened_values = nest.flatten_up_to(output_types, values) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <... | Generates the next element from iterator with ID `iterator_id_t`.
We map this function across an infinite repetition of the
`iterator_id_t`, and raise `StopIteration` to terminate the iteration.
Args:
iterator_id_t: A `tf.int64` tensor whose value uniquely identifies
the iterator in `generator_state` from which... | 625941c7956e5f7376d70ead |
def init(): <NEW_LINE> <INDENT> if platform.system() == "Linux": <NEW_LINE> <INDENT> os.system("clear") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> os.system("cls") <NEW_LINE> <DEDENT> jobs.baseOption() | 主方法 | 625941c73cc13d1c6d3c73ba |
def __init__(self, stream): <NEW_LINE> <INDENT> super(CMakeTest, self).__init__() <NEW_LINE> stmt = "" <NEW_LINE> while stream.hasNextLine(): <NEW_LINE> <INDENT> line = stream.pop() <NEW_LINE> stmt += line <NEW_LINE> if ")" in line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> self.format = CMakeFormat() <NEW... | Parameters
----------
stream : LineStream | 625941c7cc0a2c11143dcecf |
def load(fstr, resample=None): <NEW_LINE> <INDENT> xl_file = pd.ExcelFile(fstr) <NEW_LINE> df = xl_file.parse(xl_file.sheet_names[0]) <NEW_LINE> icp_data = df["p"].values <NEW_LINE> icp_timestmp = df["timestmp"].values <NEW_LINE> ts = pd.Series(icp_data, index=icp_timestmp) <NEW_LINE> if resample is not None: <NEW_LINE... | load .xlsx file for ICP using pandas
average all time stamp (resampling) in 'seconds' (default)
return a new time series by pandas | 625941c723e79379d52ee5a4 |
def domain_points(rank, ndims=3): <NEW_LINE> <INDENT> if rank == 0: <NEW_LINE> <INDENT> return [[1./3., 1./3., 1./3.]] <NEW_LINE> <DEDENT> return [[i / rank for i in n] for n in indices(rank, ndims)] | Generate coordinates for control points in n-dimensional barycentric coordinates | 625941c7d8ef3951e324357c |
def maxPoints(self, points): <NEW_LINE> <INDENT> def gcd(x,y): <NEW_LINE> <INDENT> if x==0 or y==0: <NEW_LINE> <INDENT> return x+y <NEW_LINE> <DEDENT> if x>y: <NEW_LINE> <INDENT> x,y = y,x <NEW_LINE> <DEDENT> return gcd(x, y%x) <NEW_LINE> <DEDENT> ans = 0 <NEW_LINE> for index, point in enumerate(points): <NEW_LINE> <IN... | :type points: List[Point]
:rtype: int | 625941c7e76e3b2f99f3a84c |
def __init__(self, driver=None, fs_type=None, options=None, read_only=None, secret_ref=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuratio... | V1FlexVolumeSource - a model defined in OpenAPI | 625941c776e4537e8c3516b1 |
def initialize_threads(self): <NEW_LINE> <INDENT> self.socket_layer.socket_create() <NEW_LINE> self.socket_layer.socket_bind() <NEW_LINE> """ Accept connections from multiple clients and save to list """ <NEW_LINE> for c in self.all_connections: <NEW_LINE> <INDENT> c.close() <NEW_LINE> <DEDENT> self.all_connections = [... | This method initializes the threads that the core runs on, it also checks whether the threads are dead, if
they are dead, it revives them, if it can't it reports back.
:return: | 625941c7e76e3b2f99f3a84d |
@functools.lru_cache(maxsize=1000) <NEW_LINE> def get_supported_content_language_variant(lang_code, strict=False): <NEW_LINE> <INDENT> if lang_code: <NEW_LINE> <INDENT> possible_lang_codes = [lang_code] <NEW_LINE> try: <NEW_LINE> <INDENT> possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"]) <NEW_LINE> <DEDENT> ... | Return the language code that's listed in supported languages, possibly
selecting a more generic variant. Raise LookupError if nothing is found.
If `strict` is False (the default), look for a country-specific variant
when neither the language code nor its generic variant is found.
lru_cache should have a maxsize to pre... | 625941c74d74a7450ccd4203 |
def acquire_node(self, node): <NEW_LINE> <INDENT> return node.set(self.resource, self.lock_key, nx=True, px=self.ttl) | accquire a single redis ndoe | 625941c7a4f1c619b28b007b |
def last_day(self): <NEW_LINE> <INDENT> return self.week.end_date | Returns the last day of the view being displayed | 625941c721a7993f00bc7d2d |
def emit(self, record): <NEW_LINE> <INDENT> pass | Do nothing | 625941c70383005118ecf622 |
def test_get_keep_missing(self, keep_manager): <NEW_LINE> <INDENT> assert keep_manager.get_keep_target(test_backup_id) is None | Verify when there is no keep annotation get_keep_target returns None | 625941c71f037a2d8b94623d |
def generate_header(self): <NEW_LINE> <INDENT> if self.run_header == True: <NEW_LINE> <INDENT> user_header = b"modified" <NEW_LINE> header_len = 132 <NEW_LINE> self.header = b'' <NEW_LINE> self.header += struct.pack(">I",0) <NEW_LINE> self.header += struct.pack(">I",4) <NEW_LINE> self.header += struct.pack(">I",header_... | Generates header for writing bin file of processed data.
*HACK: right now hardcoded for standard 512 litke array*
Refer to the documentation 'readme_binfile_writing.txt' for more details. | 625941c73c8af77a43ae37de |
def example(): <NEW_LINE> <INDENT> true_means, raw_means, fitted_means, fitted_means_em, y = trial() <NEW_LINE> focal_point_size = 72 <NEW_LINE> fig = plt.figure() <NEW_LINE> t = [i+1 for i in range(N_TIMES)] <NEW_LINE> plt.plot(t, true_means, linewidth=1.5, c="black", label="true mean") <NEW_LINE> plt.scatter(t, fitt... | Run and plot a trial | 625941c7dc8b845886cb5573 |
def score(alice, bob) -> tuple: <NEW_LINE> <INDENT> a = b = 0 <NEW_LINE> for i, j in zip(alice, bob): <NEW_LINE> <INDENT> if i > j: <NEW_LINE> <INDENT> a += 1 <NEW_LINE> <DEDENT> elif i < j: <NEW_LINE> <INDENT> b += 1 <NEW_LINE> <DEDENT> <DEDENT> return a, b | Score
Accepts two lists and awards one point for the higher score
:param alice: list
:param bob: list
:return: tuple | 625941c776d4e153a657eb70 |
def sparse_segment_mean_with_num_segments_eager_fallback(data, indices, segment_ids, num_segments, name=None): <NEW_LINE> <INDENT> _ctx = _context.context() <NEW_LINE> _attr_T, (data,) = _execute.args_to_matching_eager([data], _ctx) <NEW_LINE> _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _d... | This is the slowpath function for Eager mode.
This is for function sparse_segment_mean_with_num_segments | 625941c7de87d2750b85fdd1 |
def __init__(self, controlCmd, data, notification="") : <NEW_LINE> <INDENT> self._data = dict() <NEW_LINE> self._notification = notification <NEW_LINE> self._controlCmd = controlCmd <NEW_LINE> self._status = True <NEW_LINE> if common_isValidType(data,'dict') is True : <NEW_LINE> <INDENT> self._data = da... | Initilisation de l'objet dont les attributs seront echanges entre le client
et le serveur.
Les champs du protocole sont ranges dans un dictionnaire. | 625941c794891a1f4081bae8 |
def data_process(self,max_seq_length): <NEW_LINE> <INDENT> all_rel_tag = [] <NEW_LINE> all_ner_tag = [] <NEW_LINE> for one_data in self.raw_train_data: <NEW_LINE> <INDENT> triple_list = one_data["triple_list"] <NEW_LINE> for s, r, o in triple_list: <NEW_LINE> <INDENT> if r not in all_rel_tag: <NEW_LINE> <INDENT> all_re... | 获得word2id,tag2id,将原始数据进行处理,返回可训练数据
:return: | 625941c7cb5e8a47e48b7aeb |
def analog_in_acquisition_mode_get(self): <NEW_LINE> <INDENT> mode = c_int() <NEW_LINE> dwf.FDwfAnalogInAcquisitionModeGet(self.hdwf, byref(mode)) <NEW_LINE> return AcquisitionMode(mode) | Returns
-------
AcquisitionMode :
Current mode | 625941c77b25080760e39499 |
def get_elastigroup_active_instances(self, group_id): <NEW_LINE> <INDENT> content = self.send_get( url=self.__base_elastigroup_url + "/" + str(group_id) + "/status", entity_name='active instances') <NEW_LINE> formatted_response = self.convert_json( content, self.camel_to_underscore) <NEW_LINE> return formatted_response... | Get active instances of an elastigroup
# Arguments
group_id (String): Elastigroup ID
# Returns
(Object): Elastigroup API response | 625941c7ff9c53063f47c233 |
@user_passes_test_or_403(lambda user: user.is_staff or user.is_registrar_user()) <NEW_LINE> def coordinates_from_address(request): <NEW_LINE> <INDENT> address = request.GET.get('address', '') <NEW_LINE> if address: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (lat, lng) = get_lat_long(address) <NEW_LINE> return JsonRes... | Return {lat:#, lng:#, success: True} of any address or {success: False} if lookup fails. | 625941c73c8af77a43ae37df |
def do_count(self, name): <NEW_LINE> <INDENT> print(len([str(val) for key, val in storage.all().items() if type(val).__name__ == name])) | This counts instances of a class
| 625941c7cc40096d61595990 |
def get_content_length(environ): <NEW_LINE> <INDENT> content_length = environ.get('CONTENT_LENGTH') <NEW_LINE> if content_length is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return max(0, int(content_length)) <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> pass | Returns the content length from the WSGI environment as
integer. If it's not available ``None`` is returned.
.. versionadded:: 0.9
:param environ: the WSGI environ to fetch the content length from. | 625941c75fc7496912cc39bd |
def write(self, datagram, addr=None): <NEW_LINE> <INDENT> if not self._send(datagram, addr): <NEW_LINE> <INDENT> self._buffer.append((datagram, addr)) <NEW_LINE> self.startWriting() | Write a datagram.
@type datagram: C{str}
@param datagram: The datagram to be sent.
@type addr: C{tuple} containing C{str} as first element and C{int} as
second element, or C{None}
@param addr: A tuple of (I{stringified dotted-quad IP address},
I{integer port number}); can be C{None} in connected mode. | 625941c79b70327d1c4e0e14 |
def test_small(self): <NEW_LINE> <INDENT> ts = settings.THUMBNAIL_SIZE / 2 <NEW_LINE> (width, height) = _scale_dimensions(ts, ts) <NEW_LINE> eq_(ts, width) <NEW_LINE> eq_(ts, height) | A small image is not scaled. | 625941c7b830903b967e994b |
def _connect(self): <NEW_LINE> <INDENT> self._play_context.remote_user = self.default_user <NEW_LINE> if not self._connected: <NEW_LINE> <INDENT> display.vvv(u"ESTABLISH LOCAL CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self._play_context.remote_addr) <NEW_LINE> self._connected = True <NEW_LI... | connect to the local host; nothing to do here | 625941c7d53ae8145f87a2b1 |
def private_encrypt(key, message): <NEW_LINE> <INDENT> if HAS_M2: <NEW_LINE> <INDENT> return key.private_encrypt(message, salt.utils.rsax931.RSA_X931_PADDING) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> signer = salt.utils.rsax931.RSAX931Signer(key.exportKey('PEM')) <NEW_LINE> return signer.sign(message) | Generate an M2Crypto-compatible signature
:param Crypto.PublicKey.RSA._RSAobj key: The RSA key object
:param str message: The message to sign
:rtype: str
:return: The signature, or an empty string if the signature operation failed | 625941c7187af65679ca515e |
def load_from_parser(self, parser): <NEW_LINE> <INDENT> super().load_from_parser(parser) <NEW_LINE> for body in xpath(parser.xhtml, "//xhtml:body"): <NEW_LINE> <INDENT> self.load_from_pgheader(lxml.etree.tostring(body, encoding = six.text_type, method = 'text')) | Load DublinCore from Project Gutenberg ebook.
| 625941c74e696a04525c948b |
def harvest(self, source, resourcetype, resourceformat=None, harvestinterval=None, responsehandler=None): <NEW_LINE> <INDENT> node0 = self._setrootelement('csw30:Harvest') <NEW_LINE> node0.set('version', self.version) <NEW_LINE> node0.set('service', self.service) <NEW_LINE> node0.set(util.nspath_eval('xsi:schemaLocatio... | Construct and process a Harvest request
Parameters
----------
- source: a URI to harvest
- resourcetype: namespace identifying the type of resource
- resourceformat: MIME type of the resource
- harvestinterval: frequency of harvesting, in ISO8601
- responsehandler: endpoint that CSW should responsd to with response | 625941c771ff763f4b5496c9 |
def minimum_sum(values, num): <NEW_LINE> <INDENT> return sum_few(values, num, reverse=False) | Sum the num smallest integers in the array values
Args:
values (list): List of ints to sum
num (int): Number of items to sum
Returns:
int: Summary
Examples:
>>> minimum_sum([9, 1, 8, 2], 2)
3 | 625941c7f8510a7c17cf973b |
def get_decoded_data(self): <NEW_LINE> <INDENT> return self.psd_file.decoded_data | get psd decoded data
returns:
decoded_data (psd_tools.reader.reader.ParseResult) | 625941c78e05c05ec3eea3b3 |
def _get(tab, i,k,m,n,ret=0): <NEW_LINE> <INDENT> if 0 <= i < m and 0 <= k < n: <NEW_LINE> <INDENT> return tab[k][i] <NEW_LINE> <DEDENT> return ret | Get an element of matrix tab, or val(0) if out of bounds indices | 625941c7ff9c53063f47c234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.