code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def join_tribehouse(self): <NEW_LINE> <INDENT> self.send(chr(0), chr(0), "Join TH packet") | Joins the bot's tribe house. | 625941d66aa9bd52df036fde |
def disassociate_all(context, specs_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> db.qos_specs_disassociate_all(context, specs_id) <NEW_LINE> <DEDENT> except db_exc.DBError as e: <NEW_LINE> <INDENT> LOG.exception(_('DB error: %s') % e) <NEW_LINE> LOG.warn(_('Failed to disassociate qos specs %s.') % specs_id) <NEW_L... | Disassociate qos_specs from all entities. | 625941d631939e2706e4d0a2 |
def is_pos_def(self, A): <NEW_LINE> <INDENT> if np.any(np.isnan(A)) or np.any(np.isinf(A)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.all(np.real(np.linalg.eigvals(A)) > 0) | Check for positive definiteness.
Parameters
---------
A : array
square symmetric matrix.
Returns
-------
bool
whether matrix is positive-definite.
Warning! Returns false for arrays containing inf or NaN. | 625941d6cad5886f8bd27213 |
def __init__(self, length=None, width=None, height=None, unit_of_measurement=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_configuration <NEW_LIN... | DimensionRulesMaxParcelDimensions - a model defined in OpenAPI | 625941d6d10714528d5fff1f |
def particle(*args, **kwargs): <NEW_LINE> <INDENT> pass | The particle command creates a new particle object from a list of world space points.
Returns: `string` The name of the particle object created | 625941d645492302aab5e500 |
def __calculate_max_temp(self): <NEW_LINE> <INDENT> temperature_roll = dice.d100high() + self.max_temp_roll_modifier <NEW_LINE> trace.detail("Modified roll %d" % temperature_roll) <NEW_LINE> temperature_mod_values = self.standard_tables.temperature_modification(True, temperature_roll) <NEW_LINE> trace.detail("Ongoing m... | Calculates the daily maximum temperature.
:return: Tuple of the daily maximum temperature in degrees Fahrenheit, and the modifier to
apply to subsequent maximum temperature rolls. | 625941d6656771135c3ebaab |
def processId(self, id): <NEW_LINE> <INDENT> id="%s==" % id <NEW_LINE> print(id) <NEW_LINE> dicto = json.loads(base64.b64decode(id)) <NEW_LINE> if isinstance(dicto, dict): <NEW_LINE> <INDENT> user = User(dicto.get('registeredUserId')) <NEW_LINE> entryId = dicto.get('entryId') <NEW_LINE> es = entryId.split('#') <NEW_LIN... | Process the id to extract relevant info
:param id:
:return: this method modifies the structure of this object | 625941d63d592f4c4ed1d2a4 |
def fetch_page(self, tablename): <NEW_LINE> <INDENT> site = pwb.Site("wikidata", "wikidata") <NEW_LINE> return pwb.Page(site, BASE_URL + tablename) | Download lookup table from given path.
:param tablename: name of the lookup table without
full path, eg. "se-fornmin (sv)/types"
:return: Pywikibot page object where the table is located | 625941d67c178a314d6ef69c |
def check_perm(resource, action, simple=True, extra_keys={}, filters={}): <NEW_LINE> <INDENT> def check_perm_closure(f, request, *args, **kwargs): <NEW_LINE> <INDENT> if not kwargs: <NEW_LINE> <INDENT> keys = f.func_code.co_varnames[1:] <NEW_LINE> kwargs = dict(zip(keys,args)) <NEW_LINE> args = [] <NEW_LINE> <DEDENT> f... | checks user permissions to determine whether to allow user access
:resource: [string] corresponds to 'resource' value in db, ex: 'site'
:action: [string] corresponds to 'action' value in db, ex 'view'
:simple: [bool] True = checks if any permission exists for the
: resource.action pair. False = apply base filters, e... | 625941d6fbf16365ca6f6400 |
def exit_(): <NEW_LINE> <INDENT> print('Goodbye!') <NEW_LINE> sys.exit() | Exit. | 625941d64f88993c3716c2a0 |
def supports_grade_system_query(self): <NEW_LINE> <INDENT> raise errors.Unimplemented() | Tests if a ``GradeSystemQuery`` is available.
return: (boolean) - ``true`` if a grade system query is
available, ``false`` otherwise
*compliance: mandatory -- This method must be implemented.* | 625941d6099cdd3c635f0e95 |
def __init__(self, anno_rpath, video_rpath, splits): <NEW_LINE> <INDENT> self.anno_rpath = anno_rpath <NEW_LINE> self.video_rpath = video_rpath <NEW_LINE> self._load_annotations(splits) | anno_rpath: the root path of annotations
video_rpath: the root path of videos
splits: a list of splits in the dataset to load | 625941d660cbc95b062c677e |
def __init__(self, username, password, extras={'remember_me':'1'}, client='dAmnViper (python 3.x) TokenGrabber/2'): <NEW_LINE> <INDENT> self.jar = None <NEW_LINE> self.cookie = None <NEW_LINE> self.token = None <NEW_LINE> self.response = None <NEW_LINE> self.status = (0, 'Nothing has happened yet.') <NEW_LINE> response... | Initialise the object. Fetch and process an authtoken. | 625941d64527f215b584c68f |
def letterCombinations(self, digits): <NEW_LINE> <INDENT> d={'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} <NEW_LINE> r=[] <NEW_LINE> if digits=='': <NEW_LINE> <INDENT> return [] <... | :type digits: str
:rtype: List[str] | 625941d6498bea3a759b9ce9 |
def workflow_update(object_id, input_params={}, always_retry=True, **kwargs): <NEW_LINE> <INDENT> return DXHTTPRequest('/%s/update' % object_id, input_params, always_retry=always_retry, **kwargs) | Invokes the /workflow-xxxx/update API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2Fupdate | 625941d63539df3088e2e585 |
def setup(self, app): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.function_type = type(app.default_error_handler) <NEW_LINE> self.function_original = app.default_error_handler <NEW_LINE> self.app.default_error_handler = self.function_type( self.custom_error_handler, app, Bottle) | Handle plugin install | 625941d65fdd1c0f98dc046e |
def backward(self, y: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: <NEW_LINE> <INDENT> raise NotImplementedError | Args:
y: Tensor
The random variable after flow
Returns: x: Tensor, logdet: Tensor
x, the random variable before flow
logdet, the log determinant of :math:`\partial x / \partial y`
Then the density :math:`\log(p(y)) = \log(p(x)) + logdet` | 625941d699fddb7c1c9de5cb |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941d644b2445a339322cf |
def match_stmt(*pattern): <NEW_LINE> <INDENT> return Matcher(pattern, False) | Version of `match_expr` that allows you to match entire statements. | 625941d6e76e3b2f99f3aa43 |
def query(self, path, use_duration=True): <NEW_LINE> <INDENT> probs = [] <NEW_LINE> for s1, s2, d in path: <NEW_LINE> <INDENT> prob = self.transition_probability(s1, s2) <NEW_LINE> if use_duration: <NEW_LINE> <INDENT> prob *= self.duration_density(s1, s2, d) <NEW_LINE> <DEDENT> probs.append(prob) <NEW_LINE> <DEDENT> re... | Return query result of path.
Parameters
----------
path: tuple
Path of state transitions (state_i, state_j, duration)
use_duration: boolean
Whether use duration or not
Returns
-------
result: tuple
Contains the join probability of all paths (multiple paths lead to
multiplied probabilities) and each in... | 625941d630dc7b7665901b9f |
def getIPAddress(): <NEW_LINE> <INDENT> return "127.0.0.1" | Get the current ip address.
:returns: The current ip address as a string.
:rtype: str
example::
ip = xbmc.getIPAddress() | 625941d6bf627c535bc13409 |
def get_problem_combinator(index, n, num_problems=None): <NEW_LINE> <INDENT> index = index.values() <NEW_LINE> pool = range(len(index)) <NEW_LINE> if num_problems is None: <NEW_LINE> <INDENT> combinations = [i for i in itertools.combinations_with_replacement(pool, n)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rando... | Returns a function that combines *n* problems from *index* to get the given
number of combined problems selected at random. | 625941d6bf627c535bc1340a |
def object_metadata(self, key): <NEW_LINE> <INDENT> return Hdf5ObjectFactory.object_metadata(self.mesh_data(key), self.metadata) | Returns a dictionary of object metadata for the object
Parameters
----------
key : :obj:`str`
key of object to check metadata for
metadata_type : :obj:`list` of :obj:`str`
Returns
-------
:obj:`dict`
dictionary mapping metadata names to numeric/numpy list values | 625941d6ab23a570cc2503be |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.twist is None: <NEW_LINE> <INDENT> self.twist = geometry_msgs.msg.Twist() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NE... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941d66fb2d068a760f2da |
def to_struct(self): <NEW_LINE> <INDENT> if self._tags: <NEW_LINE> <INDENT> the_tags = [tag.to_struct() for tag in self._tags] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> the_tags = [] <NEW_LINE> <DEDENT> return {"_class": "StyledText", "string": self._string, "tags": the_tags} | Convert the data held in this object to a structure (eg,
struct) that represents all the data elements.
This method is used to recursively convert the object into a
self-documenting form that can easily be used for various
purposes, including diffs and queries.
These structures may be primitive Python types (string,
... | 625941d6b57a9660fec33ac1 |
def get_terminal_size(): <NEW_LINE> <INDENT> import platform <NEW_LINE> current_os = platform.system() <NEW_LINE> tuple_xy=None <NEW_LINE> if current_os == 'Windows': <NEW_LINE> <INDENT> tuple_xy = _get_terminal_size_windows() <NEW_LINE> if tuple_xy is None: <NEW_LINE> <INDENT> tuple_xy = _get_terminal_size_tput() <NEW... | This function decides what method to call to get the screen size.
src: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python | 625941d60a50d4780f6670ce |
def test_basic_model_structure_with_list_values(self): <NEW_LINE> <INDENT> values = [ { 'test1': 'value1', 'test2': 'value2', 'test3': 'value3' }, { 'test1': 'value4', 'test2': 'value5', 'test3': 'value6' }, { 'test1': 'value7', 'test2': 'value8', 'test3': 'value9' } ] <NEW_LINE> expected = [ { 'test1': 'value1', 'test... | Test valid model load of basic structure with list values | 625941d667a9b606de4a80f3 |
def _update_attributes(self): <NEW_LINE> <INDENT> leaf_params = self._tr_tree.get_leaf_parameters() <NEW_LINE> self.signature = Signature(leaf_params) <NEW_LINE> self.parameter = make_parameter_container(self, leaf_params) | Updates ``signature`` and ``parameter`` attributes.
Called by the methods that change the signature. | 625941d666673b3332b922cc |
def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(parent) <NEW_LINE> self.abstractDb = abstractDb <NEW_LINE> self.setupUi(self) <NEW_LINE> self.jsonBuilder = CustomJSONBuilder() <NEW_LINE> self.populateDomainCombo() <NEW_LINE> regex = QtC... | Constructor. | 625941d691af0d3eaac9bc55 |
def test_iforest_error(): <NEW_LINE> <INDENT> X = iris.data <NEW_LINE> assert_raises(ValueError, IsolationForest(max_samples=-1).fit, X) <NEW_LINE> assert_raises(ValueError, IsolationForest(max_samples=0.0).fit, X) <NEW_LINE> assert_raises(ValueError, IsolationForest(max_samples=2.0).fit, X) <NEW_LINE> assert_warns_mes... | Test that it gives proper exception on deficient input. | 625941d63346ee7daa2b2fa7 |
def create_lun(self, volume_name, lun_name, size, metadata, qos_policy_group_name=None): <NEW_LINE> <INDENT> path = '/vol/%s/%s' % (volume_name, lun_name) <NEW_LINE> lun_create = netapp_api.NaElement.create_node_with_children( 'lun-create-by-size', **{'path': path, 'size': six.text_type(size), 'ostype': metadata['OsTyp... | Issues API request for creating LUN on volume. | 625941d6377c676e912723e3 |
def normalise(query): <NEW_LINE> <INDENT> return query.lower().rstrip(string.punctuation) | Normalise a query for consistent string analysis
Convert the query to lowercase and remove punctuation from the right-hand side of the string
:param query: A string, the user query
:return: A string, the normalised user query | 625941d64527f215b584c690 |
def find_event(self, description): <NEW_LINE> <INDENT> session = self._get_session() <NEW_LINE> for event in session.query(Event).filter_by(description=description): <NEW_LINE> <INDENT> return event | Get a event by description | 625941d6d8ef3951e3243778 |
def test_busca_cep(self): <NEW_LINE> <INDENT> cep = self.busca_cep_exemplo(self.CEP) <NEW_LINE> self.assertEqual(self.CEP, cep.dados['cep']) | testa se o cep informado é o mesmo do retornado | 625941d6e64d504609d74a7b |
def krull_dimension(self): <NEW_LINE> <INDENT> return self.base_ring().krull_dimension() + 1 | Return the Krull dimension of this polynomial ring, which is one
more than the Krull dimension of the base ring.
EXAMPLES::
sage: R.<x> = QQ[]
sage: R.krull_dimension()
1
sage: R.<z> = GF(9,'a')[]; R
Univariate Polynomial Ring in z over Finite Field in a of size 3^2
sage: R.krull_dimension()
... | 625941d69b70327d1c4e1010 |
def __get_request_for_update( self, requirement_id, **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> ... | Retrieve the Request for update. # noqa: E501
Retrieve the Request for update. If one does not exist, an Request with some re-filled information is returned. If a submission associated with the request is approved, and the requirement requires renewal, a refilled Renewal is returned. Only the owner of the request ca... | 625941d6851cf427c661a748 |
def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> util.raiseNotDefined() | The parent class calls this to observe a
state = action => nextState and reward transition.
You should do your Q-Value update here
NOTE: You should never call this function,
it will be called on your behalf | 625941d67b180e01f3dc4a35 |
def test_067_certificate__identifer_tnauth_list(self): <NEW_LINE> <INDENT> identifier_dic = {'identifiers': '[{"type": "TnAuThLiSt", "value": "bar"}]'} <NEW_LINE> tnauthlist = 'foo' <NEW_LINE> self.assertEqual([False], self.certificate._identifer_tnauth_list(identifier_dic, tnauthlist)) | correct type but wrong value | 625941d650812a4eaa59c55b |
def test_auth_password_success(): <NEW_LINE> <INDENT> register('test', 'testpassword') <NEW_LINE> content = request('POST', '/auth', {"user": "test", "password": "testpassword"}) <NEW_LINE> assert 'token' in content | с использованием логина и пароля (поле password) | 625941d6711fe17d825425a4 |
def testJsonFindWorkflowDefinitionsRequest(self): <NEW_LINE> <INDENT> pass | Test JsonFindWorkflowDefinitionsRequest | 625941d6236d856c2ad44a17 |
def _function_get_mandatory_delivery(self, cr, uid, ids, fields, param, context = None): <NEW_LINE> <INDENT> res = {} <NEW_LINE> for item in self.browse(cr, uid, ids, context = context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res[item.id] = item.order_id.accounting_state == "planned" <NEW_LINE> <DEDENT> except: <... | Test if oc header has delivery status setted
| 625941d6046cf37aa974cf81 |
def test_random_grades(): <NEW_LINE> <INDENT> for i in range(100): <NEW_LINE> <INDENT> rand1 = random.randint(0, 100) <NEW_LINE> rand2 = random.randint(0, 100) <NEW_LINE> rand3 = random.randint(0, 100) <NEW_LINE> assert get_grade(rand1, rand2, rand3) == solution(rand1, rand2, rand3) | Test random use cases for get_grade(). | 625941d6d4950a0f3b08c588 |
def test_scale_iou(self): <NEW_LINE> <INDENT> sa = EvalBox(size=(4, 4, 4)) <NEW_LINE> sr = EvalBox(size=(4, 4, 4)) <NEW_LINE> res = scale_iou(sa, sr) <NEW_LINE> self.assertEqual(res, 1) <NEW_LINE> sa = EvalBox(size=(2, 2, 2)) <NEW_LINE> sr = EvalBox(size=(1, 1, 1)) <NEW_LINE> res = scale_iou(sa, sr) <NEW_LINE> self.ass... | Test valid and invalid inputs for scale_iou(). | 625941d64c3428357757c562 |
def pythongen(self): <NEW_LINE> <INDENT> pythoncode = self.type <NEW_LINE> if (self.type == "i"): <NEW_LINE> <INDENT> pythoncode = string.join([pythoncode,repr(self.label)],"") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pythoncode = string.join([pythoncode,repr(len(self.indexes)/2)],"") <NEW_LINE> <DEDENT> pythoncod... | Returns a character expression in Python syntax | 625941d6fff4ab517eb2f678 |
def __init__(self, make, model, year): <NEW_LINE> <INDENT> super().__init__(make, model, year) <NEW_LINE> self.battery = Battery() | Initialize attributes of the parent class
Then Initialize attributes specific to an electric car | 625941d6d6c5a10208144287 |
def set_logfile(self, logfile=''): <NEW_LINE> <INDENT> self.write(f"logging {logfile}") <NEW_LINE> return self.expect("logging_ack") | Set the logfile (location to log to).
Relevant only when the daemon is sandboxed.
:param logfile: filepath to log to | 625941d63cc13d1c6d3c75b5 |
def unique_id(self): <NEW_LINE> <INDENT> return _gnuradio_core_io.gr_udp_source_sptr_unique_id(self) | unique_id(self) -> long | 625941d6293b9510aa2c34cf |
def update_columns(infilename, column_dicts, outfilename=None): <NEW_LINE> <INDENT> default_out_file = "pyexcel_%s" % infilename <NEW_LINE> if outfilename: <NEW_LINE> <INDENT> default_out_file = outfilename <NEW_LINE> <DEDENT> if os.path.exists(default_out_file): <NEW_LINE> <INDENT> raise NotImplementedError(__WARNING_... | Update one or more columns of a data file with series
The data structure of column_dicts should be:
key should be first row of the column
the rest of the value should an array | 625941d6dc8b845886cb5771 |
def _call( self, objs: Iterable[drgn.Object]) -> Optional[Iterable[drgn.Object]]: <NEW_LINE> <INDENT> assert self.input_type is not None <NEW_LINE> self.pretty_print(self.check_input_type(objs)) | This function will call pretty_print() on each input object,
verifying the types as we go. | 625941d6d7e4931a7ee9e159 |
def cmd_all(function, profile): <NEW_LINE> <INDENT> ret=True <NEW_LINE> for host in detect_hosts(profile): <NEW_LINE> <INDENT> ret = ret and function(host) <NEW_LINE> <DEDENT> return ret | Determine the host names and run a function for each host for a given profile. | 625941d6adb09d7d5db6c9ca |
def solve_homotopy_source(self, x0, sV): <NEW_LINE> <INDENT> def f(_lambda): <NEW_LINE> <INDENT> self._lambda = _lambda <NEW_LINE> <DEDENT> def get_deltax(x): <NEW_LINE> <INDENT> (iVec, Jac) = self.get_i_Jac(x) <NEW_LINE> return self._get_deltax(iVec - self._lambda * sV, Jac) <NEW_LINE> <DEDENT> def f_eval(x): <NEW_LIN... | Newton's method with source stepping | 625941d68da39b475bd651b1 |
def __init__(self, state_size, action_size, seed, priority_eps=.1): <NEW_LINE> <INDENT> self.state_size = state_size <NEW_LINE> self.action_size = action_size <NEW_LINE> self.seed = random.seed(seed) <NEW_LINE> self.priority_eps = priority_eps <NEW_LINE> self.qnetwork_local = QNetwork(state_size, action_size, seed).to(... | Initialize an Agent object.
Params
======
state_size (int): dimension of each state
action_size (int): dimension of each action
seed (int): random seed | 625941d6046cf37aa974cf82 |
def arctan(self): <NEW_LINE> <INDENT> name, latex_name = self._function_name("arctan", r"\arctan") <NEW_LINE> resu = type(self)(self.parent(), name=name, latex_name=latex_name) <NEW_LINE> for chart, func in self._express.items(): <NEW_LINE> <INDENT> resu._express[chart] = func.arctan() <NEW_LINE> <DEDENT> return resu | Arc tangent of the scalar field.
OUTPUT:
- the scalar field `\arctan f`, where `f` is the current scalar field
EXAMPLES::
sage: M = Manifold(2, 'M', structure='topological')
sage: X.<x,y> = M.chart()
sage: f = M.scalar_field({X: x*y}, name='f', latex_name=r"\Phi")
sage: g = arctan(f) ; g
Scalar ... | 625941d68c3a8732951585f7 |
def hasCycle(self, head): <NEW_LINE> <INDENT> fast = slow = head <NEW_LINE> while fast != None and fast.next != None: <NEW_LINE> <INDENT> slow = slow.next <NEW_LINE> fast = fast.next.next <NEW_LINE> if fast == slow: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | :type head: ListNode
:rtype: bool | 625941d68c3a8732951585f8 |
def setdirection(self, d): <NEW_LINE> <INDENT> self.direction = d | Args:
d: a direction unit vector tuple (row, column) that describes the
direction that the word runs in the CharArray.
Returns:
Nothing | 625941d697e22403b379d1d6 |
def do_render(self, ctx): <NEW_LINE> <INDENT> img = self.get_image() <NEW_LINE> if img is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if isinstance(img, rsvg.Handle): <NEW_LINE> <INDENT> img.render_cairo(ctx) <NEW_LINE> return <NEW_LINE> <DEDENT> if isinstance(img, PixbufAnimation): <NEW_LINE> <INDENT> img = s... | Handle `render` signal.
Parameters
----------
ctx : `cairo.Context` | 625941d6baa26c4b54cb1359 |
def index_bar(ax, vals, facecolor='b', edgecolor='l', width=4, alpha=1.0, ): <NEW_LINE> <INDENT> facecolors = (colorConverter.to_rgba(facecolor, alpha),) <NEW_LINE> edgecolors = (colorConverter.to_rgba(edgecolor, alpha),) <NEW_LINE> right = width/2.0 <NEW_LINE> left = -width/2.0 <NEW_LINE> bars = [ ( (left, 0), (left, ... | Add a bar collection graph with height vals (-1 is missing).
ax : an Axes instance to plot to
width : the bar width in points
alpha : bar transparency | 625941d6293b9510aa2c34d0 |
def generate_judge_criteria(cover_dir, save_dir): <NEW_LINE> <INDENT> files = os.listdir(cover_dir) <NEW_LINE> out = {} <NEW_LINE> for f in files: <NEW_LINE> <INDENT> out[f] = {'good': '', 'ok': '', 'bad': ''} <NEW_LINE> <DEDENT> with open(os.path.join(save_dir, 'judge_criteria.json'), 'w') as f: <NEW_LINE> <INDENT> js... | Generate the judge critieria json
{sample cover name: {
'good': what is good?
'bad': what is bad?
}
}
:param cover_dir: the sample cover directory
:param save_dir: directory to save the json
:return: | 625941d632920d7e50b2840e |
def _login_old(self, code): <NEW_LINE> <INDENT> m = hashlib.md5() <NEW_LINE> m.update(self._password.encode()) <NEW_LINE> pwd = m.hexdigest() <NEW_LINE> m = hashlib.md5() <NEW_LINE> m.update(code.encode()) <NEW_LINE> pwd += m.hexdigest() <NEW_LINE> m = hashlib.md5() <NEW_LINE> m.update(pwd.encode()) <NEW_LINE> pwd = m.... | login for old login site
: param code: validate code
:return: None | 625941d6379a373c97cfad81 |
def check_keydown_events(event, ai_settings, screen, ship, bullets): <NEW_LINE> <INDENT> if event.key == pygame.K_RIGHT: <NEW_LINE> <INDENT> ship.moving_right = True <NEW_LINE> <DEDENT> elif event.key == pygame.K_LEFT: <NEW_LINE> <INDENT> ship.moving_left = True <NEW_LINE> <DEDENT> elif event.key == pygame.K_SPACE: <NE... | 响应按下键盘的事件. | 625941d629b78933be1e58e5 |
def xyz_to_Yxy2(xyz, **kwargs): <NEW_LINE> <INDENT> xyz = np2d(xyz) <NEW_LINE> Yxy = xyz.astype(np.float) <NEW_LINE> sumxyz = xyz[...,0] + xyz[...,1] + xyz[...,2] <NEW_LINE> Yxy[...,0] = xyz[...,1] <NEW_LINE> Yxy[...,1] = xyz[...,0] / sumxyz <NEW_LINE> Yxy[...,2] = xyz[...,1] / sumxyz <NEW_LINE> return Yxy | Convert XYZ tristimulus values CIE Yxy chromaticity values.
Args:
:xyz:
| ndarray with tristimulus values
Returns:
:Yxy:
| ndarray with Yxy chromaticity values
(Y value refers to luminance or luminance factor) | 625941d6c432627299f04e83 |
def get_content(self, info): <NEW_LINE> <INDENT> reflinks = self.site['reflinks'] <NEW_LINE> refcontent = [] <NEW_LINE> key = info['order'] <NEW_LINE> reverse = info.get('reverse', False) <NEW_LINE> navcomps = info['components'] <NEW_LINE> def pred(item): <NEW_LINE> <INDENT> itemcomps = item['components'] <NEW_LINE> if... | Infer sorted content of a folder. | 625941d607d97122c4178acb |
def _generate_proxy_class(module_or_class, name, ignore_classes=False): <NEW_LINE> <INDENT> if module_or_class not in memo: <NEW_LINE> <INDENT> klass = type(name.strip("_"), (IDAProxy,), {}) <NEW_LINE> add_module(module_or_class, klass, ignore_classes=ignore_classes) <NEW_LINE> Pyro4.expose(klass) <NEW_LINE> memo[modul... | Generates a safe proxyable class from given module or class. | 625941d6e8904600ed9f216b |
def test_user_login_failed_user_none(self): <NEW_LINE> <INDENT> request, response = APP.test_client.post( '/auth/user', data=json.dumps(TestUserValues.none)) <NEW_LINE> self.assertEqual(response.status, 401) <NEW_LINE> self.assertEqual(response.json['reasons'][0], EXCEPTION_MESSAGE['none_user']) | url에서 실패한 로그인 테스트: 유저 없음 | 625941d630c21e258bdfa6da |
def generate_code(q, n): <NEW_LINE> <INDENT> code = list(itertools.product(list(range(q)), repeat=n)) <NEW_LINE> return np.array(code) | Parameters
-----------
q : prime int
a field over q, the alphabet
n : int
length of codewords
Returns
--------
list of codewords of length n over finite field q | 625941d6462c4b4f79d1d90c |
def parse_huanqiu(self, response): <NEW_LINE> <INDENT> hxs = HtmlXPathSelector(response) <NEW_LINE> hxs_a = hxs.select("//div[@class='section']//ul/li/a/@href").extract() <NEW_LINE> for a in hxs_a: <NEW_LINE> <INDENT> if not a.startswith('http'): <NEW_LINE> <INDENT> base_url = get_base_url(response) <NEW_LINE> a = urlj... | 环球 | 625941d6b5575c28eb68e23d |
def rand10(self): <NEW_LINE> <INDENT> while (True): <NEW_LINE> <INDENT> a = rand7() <NEW_LINE> b = rand7() <NEW_LINE> idx = b + 7 * (a - 1) <NEW_LINE> if (idx <= 40): <NEW_LINE> <INDENT> return 1 + (idx - 1) % 10 <NEW_LINE> <DEDENT> a = idx - 40 <NEW_LINE> b = rand7() <NEW_LINE> idx = b + (a - 1) * 7 <NEW_LINE> if (idx... | :rtype: int | 625941d68e7ae83300e4b209 |
def containsPattern(self, arr, m, k): <NEW_LINE> <INDENT> for i in xrange(len(arr)-m*k+1): <NEW_LINE> <INDENT> if arr[i:i+m]*k == arr[i:i+m*k]: return True <NEW_LINE> <DEDENT> return False | :type arr: List[int]
:type m: int
:type k: int
:rtype: bool | 625941d69c8ee82313fbb9b1 |
def _initialize_data_pipeline(self): <NEW_LINE> <INDENT> self.x = tf.placeholder( dtype=tf.float32, shape=[None, self.input_size], name='input_ph') <NEW_LINE> self.eps = tf.placeholder( dtype=tf.float32, shape=[None, self.num_lvs], name='rand_ph') | Create placeholders for input and random values | 625941d6dc8b845886cb5772 |
def get_p4_users(p4): <NEW_LINE> <INDENT> users = [] <NEW_LINE> results = p4.run('users') <NEW_LINE> if results: <NEW_LINE> <INDENT> for r in results: <NEW_LINE> <INDENT> users.append((r['User'], r['Email'], r['FullName'])) <NEW_LINE> <DEDENT> <DEDENT> return users | Retrieve the set of users registered in the Perforce server, in a
list of tuples consisting of username, email address, and full name. If
no users exist, an empty list is returned.
Returns a list of 3-tuples: (p4user, email, fullname) | 625941d626238365f5f0f0ad |
def __filter_terms(dic_combinaison, threshold): <NEW_LINE> <INDENT> return {__key2str(key): dic_combinaison[key] for key in dic_combinaison if dic_combinaison[key] >= threshold} | Take a dictionnary containing each combinations of terms and return those
which are found k or more time (default k=2).
It returns a dict, containing each complex term as a key <str>,
and value is the number of occurence <int> in dic_combinaison. | 625941d6ec188e330fd5a9d8 |
def dump_no_overwrite_test(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--a', type=int, nargs='*') <NEW_LINE> parser.add_argument('--b', type=int) <NEW_LINE> parser = argload.ArgumentLoader(parser, ['a']) <NEW_LINE> mkdir('log') <NEW_LINE> parser... | Fail if dump is used without overwrite | 625941d67b25080760e39695 |
@pytest.fixture(scope="session") <NEW_LINE> def librepcb_server(): <NEW_LINE> <INDENT> import time <NEW_LINE> import threading <NEW_LINE> import socket <NEW_LINE> import socketserver <NEW_LINE> import http.server <NEW_LINE> class Handler(http.server.SimpleHTTPRequestHandler, object): <NEW_LINE> <INDENT> def translate_p... | Fixture which provides a HTTP server at localhost:8080
All tests should use this server instead of the official LibrePCB API server
or GitHub for downloading libraries. | 625941d6baa26c4b54cb135a |
def test_unmoderated_question_is_viewable(self): <NEW_LINE> <INDENT> submission = SubmissionFactory() <NEW_LINE> rsp = self.client.get(submission.get_absolute_url()) <NEW_LINE> self.assertNotContains(rsp, "This question has been removed.") <NEW_LINE> self.assertContains(rsp, "Share This Question!") <NEW_LINE> self.asse... | Question page should be accessible if the question has been unmoderated,
but with a notice of removal instead of the typical vote flag share buttons. | 625941d660cbc95b062c677f |
def nonzero(data, shape): <NEW_LINE> <INDENT> index_1d = [i for i, e in enumerate(data) if e != 0] <NEW_LINE> pos = [] <NEW_LINE> for ind in index_1d: <NEW_LINE> <INDENT> pos.append(get_index(shape,ind)) <NEW_LINE> <DEDENT> pos2 = [] <NEW_LINE> for k in range(len(pos[0])): <NEW_LINE> <INDENT> pos2.append(tuple([i[k] fo... | Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of `data`, containing
the indices of the non-zero elements in that dimension.
Parameters
----------
data : list
Input data.
shape : tuple
The shape of the input array
Returns
-------
tuple_of_arrays : tupl... | 625941d6507cdc57c6306f1b |
def test_logout(client): <NEW_LINE> <INDENT> response = client.post("/api/auth/logout") <NEW_LINE> assert response.status_code == 200 <NEW_LINE> assert "detail" in response.json() | POST /auth/logout. - 200 | 625941d63d592f4c4ed1d2a6 |
def setup(self): <NEW_LINE> <INDENT> return {} | Return a list of wizard dictionaries with questions needed for setting up the class.
Answers to the questions will automatically be saved to self.answers. | 625941d6de87d2750b85ffd0 |
def __init__(self, name, adjacent=None): <NEW_LINE> <INDENT> adjacent = adjacent or set() <NEW_LINE> self.name = name <NEW_LINE> self.adjacent = set(adjacent) | Create a person node with friends adjacent | 625941d66aa9bd52df036fe1 |
def load_data(self, wd, content, title, query): <NEW_LINE> <INDENT> s = wd <NEW_LINE> self.datasets = {} <NEW_LINE> count = 0 <NEW_LINE> for i in ("train", "valid", "test"): <NEW_LINE> <INDENT> temp_t = s + i + "_summary" <NEW_LINE> temp_v = s + i + "_content" <NEW_LINE> temp_q = s + i + "_query" <NEW_LINE> temp_sie = ... | Load all the datasets
Arguments:
* wd: Directory where all the data files are stored
Returns:
* void | 625941d630bbd722463cc004 |
def test_parse_metadata_csv_non_ascii(self): <NEW_LINE> <INDENT> data = [["Filename", "dc.title"], ["objects/foo.jpg", six.ensure_str("元気です")]] <NEW_LINE> with open(self.metadata_file.as_posix(), "w") as f: <NEW_LINE> <INDENT> writer = csv.writer(f) <NEW_LINE> for row in data: <NEW_LINE> <INDENT> writer.writerow(row) <... | It should parse unicode. | 625941d69f2886367277aac8 |
def test_check_update_calls_callback_when_update_available(): <NEW_LINE> <INDENT> with requests_mock.mock() as mocked_server: <NEW_LINE> <INDENT> mocked_server.post(_base_url + _check_update_endpoint, text=_json_update_response, status_code=200) <NEW_LINE> request = UpdateDetailRequest('v1', 'MyDevice', '{"AnyCustomDat... | Tests that the client ''check'' callback is called with UpdateDetail when status code is available | 625941d676d4e153a657ed6e |
def on_contact_joined(self, account): <NEW_LINE> <INDENT> gui.Conversation.on_contact_joined(self,account) <NEW_LINE> contact = self.session.contacts.get(account) <NEW_LINE> if contact and len(self.members) > 1: <NEW_LINE> <INDENT> message = e3.base.Message(e3.base.Message.TYPE_MESSAGE, _('%s has joined the ... | called when a contact joins the conversation | 625941d6099cdd3c635f0e96 |
@fn.curry(1) <NEW_LINE> def peek( seq: Seq, key: Callable[[Seq], Any] = NOT_GIVEN, default=NOT_GIVEN, n=NOT_GIVEN ) -> Tuple[Any, Seq]: <NEW_LINE> <INDENT> if key is NOT_GIVEN: <NEW_LINE> <INDENT> return _peek_direct(seq, n, default) <NEW_LINE> <DEDENT> elif n is not NOT_GIVEN: <NEW_LINE> <INDENT> raise TypeError("cann... | Retrieve an element and return a tuple of (elem, seq).
The resulting sequence *includes* all elements of the original sequence.
If a callable key is given, it is used to partially consume the list and
produce the returning element.
Args:
seq:
Input sequence.
key:
A function that is used to ins... | 625941d6e5267d203edcded7 |
def testGrowCircular(self): <NEW_LINE> <INDENT> im = afwImage.MaskedImageF(11, 11) <NEW_LINE> im[5, 5, afwImage.LOCAL] = (10, 0x0, 0.0) <NEW_LINE> fs = afwDetect.FootprintSet(im, afwDetect.Threshold(10)) <NEW_LINE> self.assertEqual(len(fs.getFootprints()), 1) <NEW_LINE> radius = 3 <NEW_LINE> for fctrl in (afwDetect.Foo... | Grow footprints in all 4 directions using the FootprintSet/FootprintControl constructor | 625941d6eab8aa0e5d26dd95 |
def settings(self, nodialog=False): <NEW_LINE> <INDENT> if 'MT - EDI' in self.indata: <NEW_LINE> <INDENT> self.data = copy.deepcopy(self.indata['MT - EDI']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.showprocesslog('No EDI data') <NEW_LINE> return False <NEW_LINE> <DEDENT> self.combobox1.currentIndexChanged.dis... | Entry point into item.
Parameters
----------
nodialog : bool, optional
Run settings without a dialog. The default is False.
Returns
-------
bool
True if successful, False otherwise. | 625941d6f8510a7c17cf9939 |
def get_messages(user, location, basecamp=0): <NEW_LINE> <INDENT> if basecamp and location is None: <NEW_LINE> <INDENT> location = user.basecamp_location <NEW_LINE> <DEDENT> params = [("accuracy", user.location.accuracy), ("bc", int(basecamp)), ("lat", location.latitude), ("long", location.longitude), ("token", get_tok... | Return raw response data for all messages in location/basecamp using
user | 625941d607f4c71912b116c0 |
@register.filter(name='software_upgraded') <NEW_LINE> def software_upgraded(site): <NEW_LINE> <INDENT> if site.software_upgraded == Yes: <NEW_LINE> <INDENT> return 'YES' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'NO' | :param site:
:return: | 625941d65f7d997b87174cd6 |
def correction(self): <NEW_LINE> <INDENT> return self.serverinfo()["info"]["correction"] | Get the correction values from hyperion.
:return: json structure containing correction values | 625941d656ac1b37e6264409 |
def __init__(self): <NEW_LINE> <INDENT> SelectionView.__init__(self) <NEW_LINE> self.headers = [_('Repository'), _('Filename')] <NEW_LINE> self.store = self.setup_view() <NEW_LINE> self.state = 'normal' <NEW_LINE> self._last_selected = [] | @param widget: | 625941d68a43f66fc4b5429f |
@pytest.mark.parametrize( 'base_url,api_key', [ (None, None), (None, 'baby'), ('donthurtme', None), ] ) <NEW_LINE> def test_config_params(tmpdir_factory, mocker, base_url, api_key): <NEW_LINE> <INDENT> config_file = config(tmpdir_factory, base_url=base_url, api_key=api_key) <NEW_LINE> with pytest.raises(ValueError) as ... | Assert error is raised if a required parameter is missing from the config file | 625941d6e76e3b2f99f3aa45 |
def render_start(self): <NEW_LINE> <INDENT> return None | Render the string representation of the opening of this node. | 625941d6596a897236089cfb |
def _additional_repr_info(self): <NEW_LINE> <INDENT> return {} | Override to return additional info to go into __repr__. | 625941d6d53ae8145f87a4aa |
def delete_ax_webhook(self): <NEW_LINE> <INDENT> response = self._requests(self.webhook_url, 'get') <NEW_LINE> wh_name = AX_JIRA_WEBHOOK_PAYLOAD['name'] + self._get_cluster_name() <NEW_LINE> ax_whs = [wh for wh in response.json() if wh['name'] == wh_name] <NEW_LINE> for wh in ax_whs: <NEW_LINE> <INDENT> logger.info('De... | Delete AX Jira webhook
:return: | 625941d68a349b6b435e83b0 |
def _get_version_from_db(self, engine): <NEW_LINE> <INDENT> conn = engine.connect() <NEW_LINE> try: <NEW_LINE> <INDENT> context = migration.MigrationContext.configure(conn) <NEW_LINE> version = context.get_current_revision() or '-1' <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> conn.close() <NEW_LINE> <DEDENT> retur... | Fetches latest version of migrate repo from database
For each type of migrate repo, the latest version from db
will be returned. | 625941d6627d3e7fe0d6908e |
def getFile(path): <NEW_LINE> <INDENT> file = open(path, 'rb') <NEW_LINE> s = file.read() <NEW_LINE> file.close() <NEW_LINE> return s | little helper function
:return: | 625941d6d18da76e23532714 |
def put_mapping(self, body, index=None, params=None): <NEW_LINE> <INDENT> if self.client.__es_version__ == "6": <NEW_LINE> <INDENT> return super().put_mapping( body, doc_type=DOC_TYPE, index=index, params=params or {} ) <NEW_LINE> <DEDENT> return super().put_mapping(body, index=index, params=params or {}) | Add our dummy type in kwargs of the put_mapping call to satisfy the requirement in ES. | 625941d66fb2d068a760f2dc |
def collatz_read_3 (r) : <NEW_LINE> <INDENT> return (map(int, s.split()) for s in r) | r is a reader
returns a generator over a list of ints of length 2 | 625941d65166f23b2e1a5396 |
def initialize_changelog_file(self) -> str: <NEW_LINE> <INDENT> if os.path.isfile(self.CHANGELOG): <NEW_LINE> <INDENT> return f"{self.CHANGELOG} already exists" <NEW_LINE> <DEDENT> with open(self.CHANGELOG, 'w', encoding='utf-8') as changelog: <NEW_LINE> <INDENT> changelog.write(self.INIT) <NEW_LINE> <DEDENT> return f"... | Creates a changelog if one does not already exist | 625941d6b545ff76a8914052 |
def _deactivate(self): <NEW_LINE> <INDENT> log("GPU: Deactivating program") <NEW_LINE> gl.glUseProgram(0) <NEW_LINE> for uniform in self._uniforms.values(): <NEW_LINE> <INDENT> uniform.deactivate() <NEW_LINE> <DEDENT> for attribute in self._attributes.values(): <NEW_LINE> <INDENT> attribute.deactivate() | Deactivate the program. | 625941d638b623060ff0b02a |
def __init__(self, cred_file, bibliographic_drive="0ACMs9qA33X6eUk9PVA"): <NEW_LINE> <INDENT> self.cred_file_location = cred_file <NEW_LINE> self.drive_id = bibliographic_drive <NEW_LINE> self.service = self._connection() | Within the given drive teamfolder, search for files and retrieve the
corresponding URI for the file. Besides the `search_file` functionality,
the more general query options for G-drive are applicable as well.
Parameters
-----------
cred_file : str
local json file containing the credentials for the API access to th... | 625941d60a50d4780f6670d1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.