code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def check_preference_name(name): <NEW_LINE> <INDENT> if not re.match("[A-Za-z][_a-zA-Z0-9]*$", name): <NEW_LINE> <INDENT> raise PreferenceError(f"Illegal preference name '{name}': A preference " f"name can only start with a letter and only " f"contain letters, digits or underscore.") <NEW_LINE> <DEDENT> if name in dir(...
Make sure that a preference name is valid. This currently checks that the name does not contain illegal characters and does not clash with method names such as "keys" or "items". Parameters ---------- name : str The name to check. Raises ------ PreferenceError In case the name is invalid.
625941cc8a43f66fc4b5415b
def get_same_nat_try_internal(self): <NEW_LINE> <INDENT> return self.dlconfig['same_nat_try_internal']
Returns whether same NAT detection is enabled. @return Boolean
625941cc8e7ae83300e4b0c2
def scale_stream(s, k): <NEW_LINE> <INDENT> def rest(): <NEW_LINE> <INDENT> return scale_stream(s.rest, k) <NEW_LINE> <DEDENT> return Stream(s.first * k, lambda: scale_stream(s.rest, k))
Return a stream of the elements of S scaled by a number K. >>> s = scale_stream(ints, 5) >>> s.first 5 >>> s.rest Stream(10, <...>) >>> scale_stream(s.rest, 10)[2] 200
625941ccd7e4931a7ee9e013
def reset_path_selected(self): <NEW_LINE> <INDENT> for scan_grp in self.main_ui.grp_allScans: <NEW_LINE> <INDENT> if scan_grp.isChecked(): <NEW_LINE> <INDENT> grp_layout=scan_grp.layout() <NEW_LINE> txt_layout=grp_layout.itemAt(1).layout() <NEW_LINE> txt_layout.itemAt(0).widget().setText("") <NEW_LINE> txt_layout.itemA...
Resets the text boxes that is selected in the 'Destination' tab # GETS EVERYTHING FROM THE DYNAMIC GroupBoxes
625941cc167d2b6e31218c8b
def pig_latin(self): <NEW_LINE> <INDENT> before_pig_latin = self._get_random_word() <NEW_LINE> if before_pig_latin[0] in self.vowels: <NEW_LINE> <INDENT> pig_latin = before_pig_latin + 'way' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pig_latin = before_pig_latin[1:] + before_pig_latin[0] + 'ay' <NEW_LINE> <DEDENT> r...
Create a little pig latin for fun! What is pig latin? if the word begins with a consonant, - take the first letter, add it to the end of the word, and append 'ay' else: - add 'way' to the end
625941cc377c676e9127229e
def calculate_symmetric_dist_row(nbrs, nn_lookup, row_no): <NEW_LINE> <INDENT> dist_row = np.zeros([1, nbrs.shape[1]]) <NEW_LINE> f1 = nn_lookup[row_no] <NEW_LINE> for idx, neighbor in enumerate(f1[1:]): <NEW_LINE> <INDENT> Oi = idx + 1 <NEW_LINE> co_neighbor = True <NEW_LINE> try: <NEW_LINE> <INDENT> row = nn_lookup[n...
This function calculates the symmetric distances for one row in the matrix.
625941cc1b99ca400220aba7
def __init__(self, symbol, row, col): <NEW_LINE> <INDENT> self.symbol = symbol <NEW_LINE> self.row = row <NEW_LINE> self.col = col <NEW_LINE> self.num_sprouts_eaten = 0
(Rat, str, int, int) -> NoneType
625941cc31939e2706e4cf60
def show(target, *args, **kwargs): <NEW_LINE> <INDENT> if isinstance(target, (ecell4_base.core.FixedIntervalNumberObserver, ecell4_base.core.NumberObserver, ecell4_base.core.TimingNumberObserver, )): <NEW_LINE> <INDENT> plot_number_observer(target, *args, **kwargs) <NEW_LINE> <DEDENT> elif isinstance(target, (ecell4_ba...
An utility function to display the given target object in the proper way. Paramters --------- target : NumberObserver, TrajectoryObserver, World, str When a NumberObserver object is given, show it with viz.plot_number_observer. When a TrajectoryObserver object is given, show it with viz.plot_trajectory_observe...
625941cc4e696a04525c9541
def enqueueEnd(self, e): <NEW_LINE> <INDENT> if self._size == len(self._data): <NEW_LINE> <INDENT> self._resize(2 * len(self.data)) <NEW_LINE> <DEDENT> avail = (self._front + self._size) % len(self._data) <NEW_LINE> self._data[avail] = e <NEW_LINE> self._size += 1 <NEW_LINE> self._back = (self._front + self._size - 1) ...
Add an element to the back of queue.
625941ccbf627c535bc132c4
def increasingTriplet(self, nums): <NEW_LINE> <INDENT> size = len(nums) <NEW_LINE> if size < 3: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i, j = 0, -1 <NEW_LINE> imin = 0 <NEW_LINE> for k in range(1, size): <NEW_LINE> <INDENT> if j == -1: <NEW_LINE> <INDENT> if nums[k] > nums[i]: <NEW_LINE> <INDENT> j = k <N...
:type nums: List[int] :rtype: bool
625941cca05bb46b383ec917
def receive(self, size=4096, timeout=10): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_inet_receiving_data', size), self._mh.fromhere()) <NEW_LINE> if (not self._is_connected): <NEW_LINE> <INDENT> self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_inet_n...
Method receives data from server Args: size (int): buffer size timeout (float): receive timeout Returns: str: data Raises: event: inet_before_receive event: inet_after_receive
625941cc004d5f362079a429
def update_msg(web_client: slack.WebClient, channel: str, msg: str, ts: str, user=None, blocks=None): <NEW_LINE> <INDENT> if blocks is None: <NEW_LINE> <INDENT> if user is not None: <NEW_LINE> <INDENT> msg = f"<@{user}> " + msg <NEW_LINE> <DEDENT> web_client.chat_update(channel=channel, ts=ts, text=msg) <NEW_LINE> <DED...
Update a message Args: web_client (slack.WebClient): web client object channel (str): The channel id. e.g. 'C1234567890' msg (str): The new message you'd like to update to ts (str): The timestamp of the old message user (str) optional: If provided, '@user-name ' will be added before msg blocks ...
625941cc8c3a8732951584b0
def write_greppable_lists(self): <NEW_LINE> <INDENT> os.makedirs(wordlist_path('greppable'), exist_ok=True) <NEW_LINE> length_files = { length: open( wordlist_path_from_name( 'greppable/%s.%d' % (self.name, length) ), 'w', encoding='ascii' ) for length in range(1, self.max_indexed_length + 1) } <NEW_LINE> i = 0 <NEW_LI...
Separate the words by length and write them into separate files.
625941ccbf627c535bc132c5
def merge1(self, nums1, m, nums2, n): <NEW_LINE> <INDENT> for i in range(n): <NEW_LINE> <INDENT> nums1[i+m] = nums2[i] <NEW_LINE> <DEDENT> nums1.sort()
:type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.
625941cc099cdd3c635f0d50
def step_D(self): <NEW_LINE> <INDENT> print_step("Step D:", self.log) <NEW_LINE> es = self.eigen_system_default_handler(m=self.V_L, suffix="V_L") <NEW_LINE> self.v_x, self.v_y, self.v_z = es.x, es.y, es.z <NEW_LINE> self.tx, self.ty, self.tz = es.vals[0]**0.5,es.vals[1]**0.5,es.vals[2]**0.5 <NEW_LINE> show_vector(x=sel...
Determination of vibration components (Step D).
625941cca8370b7717052995
def elapseTime(self, gameState): <NEW_LINE> <INDENT> newparticles = [] <NEW_LINE> for currentpart in self.particles: <NEW_LINE> <INDENT> newpart = list(currentpart) <NEW_LINE> for index in xrange(len(newpart)): <NEW_LINE> <INDENT> newpart[index] = util.sample( getPositionDistributionForGhost( setGhostPositions(gameStat...
Samples each particle's next state based on its current state and the gameState. To loop over the ghosts, use: for i in range(self.numGhosts): ... Then, assuming that `i` refers to the index of the ghost, to obtain the distributions over new positions for that single ghost, given the list (prevGhostPositions) ...
625941ccb545ff76a8913f0c
def list_callables(self): <NEW_LINE> <INDENT> self.logger.debug("List of callable API objects requested") <NEW_LINE> callables = {} <NEW_LINE> for name, obj in self.systems.items(): <NEW_LINE> <INDENT> methods = [] <NEW_LINE> for member in getmembers(obj): <NEW_LINE> <INDENT> if is_api_method(obj, member[0]): <NEW_LINE...
Build list of callable methods on each exported subsystem object. Uses introspection to create a list of callable methods for each registered subsystem object. Only methods which are flagged using the @lib.api_call decorator will be included. :returns: list_reply message with callable objects and their methods.
625941cc73bcbd0ca4b2c16c
@pytest.mark.parametrize("args, chunked_args", [ (("motor1", 1, 5, 10), [("motor1", 1, 5, 10, False)]), (("motor1", 1, 5, 10, "motor2", 2, 10, 20, True), [("motor1", 1, 5, 10, False), ("motor2", 2, 10, 20, True)]), (("motor1", 1, 5, 10, "motor2", 2, 10, 20, True, "motor3", 3, 5, 15, False), [("motor1", 1, 5, 10, False)...
Check if the pattern (Pattern 2) works
625941cc94891a1f4081bb9f
def evaluate(self): <NEW_LINE> <INDENT> self.ap = self.wrapper_compute_average_precision() <NEW_LINE> self.mAP = self.ap.mean(axis=1) <NEW_LINE> self.average_mAP = self.mAP.mean() <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> print('[RESULTS] Performance on ActivityNet detection task.') <NEW_LINE> print('mAP: {}'.for...
Evaluates a prediction file. For the detection task we measure the interpolated mean average precision to measure the performance of a method.
625941cc956e5f7376d70f64
def edm_to_weighted_cross_product(D, m): <NEW_LINE> <INDENT> n = len(m) <NEW_LINE> if D.shape != (n, n): <NEW_LINE> <INDENT> raise ValueError('D should be a square matrix conformant to m') <NEW_LINE> <DEDENT> if any(x < 0 for x in m): <NEW_LINE> <INDENT> raise ValueError('each element in m should be nonnegative') <NEW_...
Get the cross product matrix. This uses the terminology of Herve Abdi 2007. @param D: a matrix of squared Euclidean distances @param m: a vector defining the mass distribution @return: a cross product matrix
625941cc3eb6a72ae02ec5d3
def persistence(self): <NEW_LINE> <INDENT> return Plasma.AuthorizationRule.Persistence()
Plasma.AuthorizationRule.Persistence Plasma.AuthorizationRule.persistence()
625941cc1d351010ab855c11
def one_kfunc(x1,y1,t,astro_obj,yso_map): <NEW_LINE> <INDENT> coords = astro_obj.circle(x1,y1,t) <NEW_LINE> n_coords = np.shape(coords)[1] <NEW_LINE> yso_sum = -1 <NEW_LINE> area = 0 <NEW_LINE> for j in range(n_coords): <NEW_LINE> <INDENT> yso_sum+=yso_map[coords[0,j],coords[1,j]] <NEW_LINE> area += astro_obj.area_arra...
Returns the number of ysos and area in circle around a given yso at position x1,y1.
625941cc796e427e537b06bc
def renamedDecorator(self): <NEW_LINE> <INDENT> pass
This is secretly a test method and will be decorated and then renamed so test discovery can find it.
625941cc283ffb24f3c559f7
@ajax_request <NEW_LINE> @login_required <NEW_LINE> def get_default_building_detail_columns(request): <NEW_LINE> <INDENT> columns = request.user.default_building_detail_custom_columns <NEW_LINE> if columns == '{}' or isinstance(columns, dict): <NEW_LINE> <INDENT> columns = [] <NEW_LINE> <DEDENT> if isinstance(columns, ...
Get default columns for building detail view. front end is expecting a JSON object with an array of field names Returns:: { "columns": ["project_id", "name", "gross_floor_area"] }
625941ccdd821e528d63b29f
def adjustSector(self, ratio): <NEW_LINE> <INDENT> self.gridsize = map(operator.mul, [ratio]*len(self.gridsize), self.gridsize) <NEW_LINE> if (self.gridsize[0]>self.combatModeStartSize[0] and self.gridsize[1]>self.combatModeStartSize[1]): <NEW_LINE> <INDENT> self.combatmode=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
Scale the size of the map by RATIO.
625941ccd4950a0f3b08c445
def setlinecolor(self, red=0, green=0, blue=0): <NEW_LINE> <INDENT> self.linecolor = "RGB({0},{1},{2})".format(red, green, blue)
Set line color to RGB value Note: Surprisingly both "RGB(R,G,B)" and "=RGB(R,G,B)" works, even thou in theory only '=' version should.
625941ccf8510a7c17cf97f3
def describe_scenarios(self): <NEW_LINE> <INDENT> print("Available scenarios for DAO testing.") <NEW_LINE> for name in available_scenarios(): <NEW_LINE> <INDENT> scenario = importlib.import_module( "scenarios.{}.run".format(name) ) <NEW_LINE> print("== {} ==\n{}.\n".format( name, textwrap.fill(scenario.scenario_descrip...
Get all scenario descriptions and print them in the screen
625941cc99fddb7c1c9de487
def read(self, buf, prompt, termitor): <NEW_LINE> <INDENT> if prompt: <NEW_LINE> <INDENT> self.frame.push(prompt) <NEW_LINE> <DEDENT> buf = buf or [] <NEW_LINE> self.set_buf(buf) <NEW_LINE> self.termitor = termitor <NEW_LINE> while True: <NEW_LINE> <INDENT> char = self.real_read() <NEW_LINE> try: <NEW_LINE> <INDENT> se...
Read a string from screen. Return the result when find a string in termitor. Return `False` when recv a Ctrl+c.
625941ccbe8e80087fb20d39
def week_containing_day(self, day): <NEW_LINE> <INDENT> self.start_date = day <NEW_LINE> self.adjust(-day.weekday())
Shows the week that contains a given date. The corresponding week will always start on Monday. @param day: datetime object, the date we want the week to show.
625941cc21a7993f00bc7de5
def update_url_if_protected(url, user): <NEW_LINE> <INDENT> from seo.models import SeoSite <NEW_LINE> search_domain = urlparse(url).netloc <NEW_LINE> protected_domains = [] <NEW_LINE> for key in settings.PROTECTED_SITES.keys(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> protected_domains.append(SeoSite.objects.get(pk...
Adds a key that bypasses authorization on protected sites if the site is protected and the user has access to the site.
625941cc0a50d4780f666f88
def set_gain(self, gains): <NEW_LINE> <INDENT> gains = [min(gain_ref.keys(), key=lambda x:abs(x-g)) for g in gains] <NEW_LINE> for i,g in enumerate(gains): <NEW_LINE> <INDENT> self.write(':AD:GAIN {0:d}, (@{1:d})'.format(g, i+1)) <NEW_LINE> <DEDENT> self.gain = gains <NEW_LINE> self.limits = [gain_ref[g] for g in self....
set gains for all channels. assumes gains is a list of valid gain values
625941cc56b00c62f0f1474f
def call_invite(self, cid, account, a_v_both, surface_other, surface_self): <NEW_LINE> <INDENT> self.add_action(e3.Action.ACTION_CALL_INVITE, (cid, account, a_v_both, surface_other, surface_self))
try to start a call with the first user of the conversation
625941cc8e05c05ec3eea46b
def transformImagesToFacesTable(source_folder, destination_folder, destination_data_file, index_list): <NEW_LINE> <INDENT> if not os.path.isdir(destination_folder): <NEW_LINE> <INDENT> os.mkdir(destination_folder) <NEW_LINE> <DEDENT> data_file = open(destination_data_file, 'w') <NEW_LINE> file_list = os.listdir(source_...
Exercise 8
625941ccd18da76e235325cc
def __init__(self, polyvizWidget, parent = None, name = None): <NEW_LINE> <INDENT> OWPlot.__init__(self, parent, name, axes = [], widget=polyvizWidget) <NEW_LINE> orngScalePolyvizData.__init__(self) <NEW_LINE> self.enableGridXB(0) <NEW_LINE> self.enableGridYL(0) <NEW_LINE> self.lineLength = 2 <NEW_LINE> self.totalPossi...
Constructs the graph
625941ccaad79263cf390b37
def min_max_normalize(self, data, data_min=pd.DataFrame(), data_max=pd.DataFrame()): <NEW_LINE> <INDENT> if (data_min.empty): data_min = data.min() <NEW_LINE> if (data_max.empty): data_max = data.max() <NEW_LINE> data_normalized = (data - data_min) / (data_max - data_min) <NEW_LINE> return (data_min, data_max, data_nor...
Normalize a Pandas dataframe using column-wise min-max normalization (can use custom min, max if desired)
625941cc4428ac0f6e5ba8e8
def skip(x): <NEW_LINE> <INDENT> return
Always returns None.
625941cc66673b3332b92187
def load_train_data(): <NEW_LINE> <INDENT> de_sents = [regex.sub("[^\s\p{Han}']", "", line) for line in codecs.open(hp.source_train, 'r', 'utf-8').read().split("\n") if line and line[0] != "<"] <NEW_LINE> en_sents = [regex.sub("[^\s\p{Latin}']", "", line) for line in codecs.open(hp.target_train, 'r', 'utf-8').read().sp...
加载训练数据
625941cc7cff6e4e81117a7c
def clone(prefix, source, stdout_callback=None, stderr_callback=None): <NEW_LINE> <INDENT> if not os.path.exists(source): <NEW_LINE> <INDENT> raise CondaEnvMissingError('Conda environment [%s] does not exist to clone.' % source) <NEW_LINE> <DEDENT> cmd_list = ['create', '-p', prefix, '--clone', source] <NEW_LINE> _call...
Clone a pre-existing env.
625941cc091ae35668667054
def top_files(query, files, idfs, n): <NEW_LINE> <INDENT> tf_idfs = {} <NEW_LINE> for file in files: <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> for word in query: <NEW_LINE> <INDENT> sum += files[file].count(word) * idfs[word] <NEW_LINE> <DEDENT> tf_idfs[file] = sum <NEW_LINE> <DEDENT> sorted_tf_idfs = list(sorted(tf_idfs....
Given a `query` (a set of words), `files` (a dictionary mapping names of files to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the filenames of the the `n` top files that match the query, ranked according to tf-idf.
625941cc7b25080760e39550
def __init__(self, resi1, resi2, stack_type): <NEW_LINE> <INDENT> self.resi1 = resi1 <NEW_LINE> self.resi2 = resi2 <NEW_LINE> self.type = stack_type
Creates a stacking object.
625941cc4d74a7450ccd42ba
@node.commandWrap <NEW_LINE> def ProcessEvents(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.ProcessEvents(*args, **kwargs)
:rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941cc24f1403a92600c5d
def getResource(url): <NEW_LINE> <INDENT> if url.startswith("/"): <NEW_LINE> <INDENT> localUrl = url[1:] <NEW_LINE> queryStart = localUrl.find("?") <NEW_LINE> if queryStart == -1: <NEW_LINE> <INDENT> path = localUrl <NEW_LINE> query = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = localUrl[:queryStart] <NEW_...
Given a URL, find or create the corresponding resource that the URL represents. (The intention is to support remote resources from other Aptrow servers, but currently only URL's relative to the local server are supported.) Even though WSGI functions parse URL's and query parameters for you, this method (which duplicat...
625941ccd486a94d0b98e23c
def jaccard_score(labels_true, labels_pred): <NEW_LINE> <INDENT> labels_true, labels_pred = check_clusterings(labels_true, labels_pred) <NEW_LINE> n_samples = labels_true.shape[0] <NEW_LINE> contingency = contingency_matrix(labels_true, labels_pred) <NEW_LINE> cc = np.sum(contingency * contingency) <NEW_LINE> N11 = (cc...
Jaccard coeficient computed according to: Ceccarelli, M. & Maratea, A. A "Fuzzy Extension of Some Classical Concordance Measures and an Efficient Algorithm for Their Computation" Knowledge-Based Intelligent Information and Engineering Systems, Springer Berlin Heidelberg, 2008, 5179, 755-763 :param labels_true: :param...
625941ccc4546d3d9de72b2a
def create_section_properties_view(self, parent): <NEW_LINE> <INDENT> return SectionPropertiesView(self.controller, parent)
Creates provider section properties view
625941cc10dbd63aa1bd2c9a
def get_modelid(self, data): <NEW_LINE> <INDENT> modelid = data[0x0C:0x0E] <NEW_LINE> return modelid
Extract a model ID from config file header
625941ccd7e4931a7ee9e014
def handle_server(kwargs, root=None, new_svr=False): <NEW_LINE> <INDENT> msg = check_session(kwargs) <NEW_LINE> if msg: return msg <NEW_LINE> ajax = kwargs.get('ajax') <NEW_LINE> host = kwargs.get('host', '').strip() <NEW_LINE> if not host: <NEW_LINE> <INDENT> return badParameterResponse(T('Server address required'), a...
Internal server handler
625941cc8c0ade5d55d3eab1
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return IndexingState( indexing = { 'key' : [ '0' ] }, queue = [ '0' ], current_entity_set = '0', queue_size = 56, count = 56 ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return IndexingState( )
Test IndexingState include_option is a boolean, when False only required params are included, when True both required and optional params are included
625941cc435de62698dfdd43
def lambda_handler(event, context): <NEW_LINE> <INDENT> login = os.environ['LOGIN'] <NEW_LINE> password = os.environ['PASSWORD'] <NEW_LINE> sns_client = boto3.client('sns') <NEW_LINE> found = find_appointment(login, password) <NEW_LINE> if found: <NEW_LINE> <INDENT> message = "" <NEW_LINE> for appt in found: <NEW_LINE>...
Do some shit
625941cc3c8af77a43ae3897
def get_engine(self): <NEW_LINE> <INDENT> return self.engine
Stub.
625941cc30dc7b7665901a5d
def urlify(str, length=None): <NEW_LINE> <INDENT> return str.strip().replace(' ', '%20')
Write a method to replace all spaces with '%20'. Args: str - String whose spaces should be replaced by '%20' length - length of str minus any spaces padded at the beginning or end Returns: A string similar to str except whose spaces have been replaced.
625941ccf548e778e58cd674
def begin(): <NEW_LINE> <INDENT> sc = turtle.Screen() <NEW_LINE> sc.title("Am I not turtley enough for you. Turtle, turtle, turtle.") <NEW_LINE> sc._root.attributes("-topmost", 1) <NEW_LINE> if __name__ == "__main__": <NEW_LINE> <INDENT> sc.setup(1.0, 1.0) <NEW_LINE> sc.onkey(go_up, "Up") <NEW_LINE> sc.onkey(go_down, ...
Starts up the turtle screen and sets up the turtle object
625941cc4d74a7450ccd42bb
def test_handle_block_height_incoming_request(self, m_logger): <NEW_LINE> <INDENT> self.channel.factory = Mock( last_block=Mock(autospec=Block, block_number=5, headerhash=b''), get_cumulative_difficulty=Mock(return_value=(0,))) <NEW_LINE> incoming_request = make_message(func_name=xrdlegacy_pb2.LegacyMessage.BH, bhData=...
handle_block_height(), unlike other handlers in this class, deals with requests and sends out responses to requests, all in the same function! If the incoming message.bhData.block_number is 0, this means that the peer wants to know our block height. If the incoming message.bhData.block_number is not 0, this means that ...
625941cc2eb69b55b151c9a5
def set_value(self, name, value): <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if '-' in name: <NEW_LINE> <INDENT> self.set_single_multivalue(name, value) <NEW_LINE> return <NEW_LINE> <DEDENT> if (name == 'show_error') or (('show_error' in self.fields) and (name == self.fields['show_e...
If this widget contains fields, then this should set a field content, given its name
625941cc57b8e32f52483591
def neighbors(self, node): <NEW_LINE> <INDENT> x, y = node <NEW_LINE> return[(nx, ny) for nx, ny in [(x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y), (x + 1, y - 1), (x + 1, y + 1), (x - 1, y - 1), (x - 1, y + 1)] if 0 <= nx < self.width and 0 <= ny < self.height and self.lines[ny][nx] == False]
for a given coordinate in the maze, returns up to 4 adjacent(north,east,south,west) nodes that can be reached (=any adjacent coordinate that is not a wall)
625941cc55399d3f055887ab
def test_identifier(self): <NEW_LINE> <INDENT> self.assertEqual(self.pos.get_identifier(), 'oai:pos.sissa.it:LATTICE 2013/001')
Test the field identifier.
625941cc5fc7496912cc3a74
def _inc_invalid_counter(self, client_id): <NEW_LINE> <INDENT> for client in self._client_list: <NEW_LINE> <INDENT> if client['id'] == client_id: <NEW_LINE> <INDENT> client['nb_invalid_messages'] += 1 <NEW_LINE> self.log.info(u"Increase number of invalid messages for %s to %s" % (client_id, client['nb_invalid_messages'...
Increase the invalid counter for a client (if it exists) @param client_id : client id
625941cc6fece00bbac2d835
def _prepare_meta_to_netcdf(self): <NEW_LINE> <INDENT> meta = self.data.attrs <NEW_LINE> meta_out = {} <NEW_LINE> for key, val in meta.items(): <NEW_LINE> <INDENT> if val is None: <NEW_LINE> <INDENT> meta_out[key] = "None" <NEW_LINE> <DEDENT> elif isinstance(val, bool): <NEW_LINE> <INDENT> meta_out[key] = int(val) <NEW...
Prepare metada for NetCDF format Returns ------- meta_out : dict metadata ready for serialisation to NetCDF.
625941cc3346ee7daa2b2e62
def lengthOfLongestSubstring(self, s): <NEW_LINE> <INDENT> chList = [-1] * 256 <NEW_LINE> maxLen = 0 <NEW_LINE> start = 0 <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> asc = ord(s[i]) <NEW_LINE> if chList[asc] !=-1 and chList[asc] >= start: <NEW_LINE> <INDENT> if (i - start) > maxLen: <NEW_LINE> <INDENT> maxLe...
:type s: str :rtype: int
625941cce5267d203edcdd94
def calc_free_cash_flow(operating_cash_flow, capital_expenditures, depreciation): <NEW_LINE> <INDENT> return operating_cash_flow - min(capital_expenditures, depreciation)
Free cash flow (FCF) represents the cash that a company is able to generate after laying out the money required to maintain or expand its asset base. Free cash flow is important because it allows a company to pursue opportunities that enhance shareholder value. Without cash, it's tough to develop new products, make acq...
625941cc0c0af96317bb82df
def reply(msg, bubble_id=-1): <NEW_LINE> <INDENT> global info <NEW_LINE> if info is not None: <NEW_LINE> <INDENT> if info['type'] == 1: <NEW_LINE> <INDENT> sendmsg(info['qq_id'], info['type'], "", info['source'], msg, bubble_id) <NEW_LINE> <DEDENT> elif info['type'] == 2: <NEW_LINE> <INDENT> sendmsg(info['qq_id'], info...
直接回复 :param msg: :param bubble_id: :return:
625941cc76e4537e8c35176a
def test_add_geo(self): <NEW_LINE> <INDENT> self.testmap.geo_data(projection='albersUsa', scale=1000, states=r'data/us-states.json') <NEW_LINE> assert self.testmap.data[0]['url'] == 'us-states.json' <NEW_LINE> assert self.testmap.data[0]['name'] == 'states'
Test adding geoJSON data to map
625941cc8c0ade5d55d3eab2
def _compute_image_from_gens(self, B): <NEW_LINE> <INDENT> L = self._manin.relations(B) <NEW_LINE> if len(L) == 0: <NEW_LINE> <INDENT> t = self._codomain.zero_element() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c, A, g = L[0] <NEW_LINE> g1 = self._dict[self._manin.reps(g)] * A <NEW_LINE> t = g1 * c <NEW_LINE> for c...
Compute image of ``B`` under ``self``. INPUT: - ``B`` -- generator of Manin relations. OUTPUT: - an element in the codomain of self (e.g. a distribution), the image of ``B`` under ``self``.
625941cc507cdc57c6306dd1
def test_unicode__basic__input_unicode_subclass(self): <NEW_LINE> <INDENT> class UnicodeSubclass(unicode): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> s = UnicodeSubclass(u"foo") <NEW_LINE> reader = Loader() <NEW_LINE> actual = reader.unicode(s) <NEW_LINE> self.assertString(actual, u"foo")
Test unicode(): default arguments with unicode-subclass input.
625941cc507cdc57c6306dd2
def clickArea(self,pnt,w,h): <NEW_LINE> <INDENT> x = pnt[0] + int(triangular(1,w)) <NEW_LINE> y = pnt[1] + int(triangular(1,h)) <NEW_LINE> return x,y
Returns random coords from area of pnt based on its width and height'
625941cc01c39578d7e74f32
def path(self, *parts): <NEW_LINE> <INDENT> parts2 = [str(self.cwd)] <NEW_LINE> for p in parts: <NEW_LINE> <INDENT> if isinstance(p, RemotePath): <NEW_LINE> <INDENT> raise TypeError("Cannot construct LocalPath from {!r}".format(p)) <NEW_LINE> <DEDENT> parts2.append(self.env.expanduser(str(p))) <NEW_LINE> <DEDENT> retur...
A factory for :class:`LocalPaths <plumbum.path.local.LocalPath>`. Usage: ``p = local.path("/usr", "lib", "python2.7")``
625941ccb5575c28eb68e0f7
def getPatchName(self): <NEW_LINE> <INDENT> return "{0}.PiP".format(self.__patch)
Get the Patch file name suitable for saving to disc. @returns {String}
625941cc9c8ee82313fbb86c
def extract_int(request, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(get_request_params(request).get(key, '')) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return None
Нормальный извлекатель числа >>> from django.test.client import RequestFactory >>> rf = RequestFactory() >>> request = rf.post('', {}) >>> extract_int(request, 'NaN') >>> request = rf.post('', {'int':1}) >>> extract_int(request, 'int') 1
625941ccbe7bc26dc91cd6f7
def test_char_field_read(self): <NEW_LINE> <INDENT> with keys(keyinfo.DECRYPT_AND_ENCRYPT): <NEW_LINE> <INDENT> with secret_model() as model: <NEW_LINE> <INDENT> test_val = "Test Secret" <NEW_LINE> secret = model.objects.create(name=test_val) <NEW_LINE> retrieved_secret = model.objects.get(id=secret.id) <NEW_LINE> self...
Uses a private key to encrypt data on model creation. Verifies the data is decrypted when reading the value back from the model.
625941cc30bbd722463cbebd
def guessFormat( self ): <NEW_LINE> <INDENT> c = [ord(x) for x in self.quals ] <NEW_LINE> mi, ma = min(c), max(c) <NEW_LINE> r = [] <NEW_LINE> for format, v in RANGES.iteritems(): <NEW_LINE> <INDENT> m1, m2 = v <NEW_LINE> if mi >= m1 and ma < m2: r.append( format ) <NEW_LINE> <DEDENT> return r
return quality score format - might return several if ambiguous.
625941cc15fb5d323cde0c07
def escape(self, line): <NEW_LINE> <INDENT> return line.replace("\\", "\\\\").replace("\"", "\\\"").replace("'", "\\'")
Escape single and double quotes and backslashes until I find something better (re.escape() escapes way too much).
625941cc4a966d76dd551107
def __iter__(self): <NEW_LINE> <INDENT> queue = collections.deque([self.root]) <NEW_LINE> while queue: <NEW_LINE> <INDENT> node = queue.popleft() <NEW_LINE> action = (yield node) <NEW_LINE> if action == "purge": <NEW_LINE> <INDENT> node["parent"]["children"].remove(node) <NEW_LINE> continue <NEW_LINE> <DEDENT> elif act...
Breadth-first iterator for navtree nodes which allows modifications of the tree during iteration. Modifications are given by passing a command to the next() method of the generator. For example: >>> tree = CatalogNavTree(context, request) >>> g = tree.iter() >>> value = g.next() >>> try: ... while True: ... ...
625941ccfbf16365ca6f62bc
def _conv_gid2guid(s): <NEW_LINE> <INDENT> return IBA.GID(s).guid();
Return the GUID portion of a GID string. :raises ValueError: If the string is invalid.
625941cc462c4b4f79d1d7c8
def mean_price(self): <NEW_LINE> <INDENT> cmp = self.__request(self.price_url)["current_price"] <NEW_LINE> return float(cmp)
c0ban mean price at c0bantrade.jp :return: float
625941cc7b180e01f3dc48f4
def _get_raw_data(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> p = Popen(self.command, stdout=PIPE, stderr=PIPE) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.error("Executing command", self.command, "resulted in error:", str(e)) <NEW_LINE> return None <NEW_LINE> <DEDENT> data = [] <NEW_LIN...
Get raw data from executed command :return: str
625941cc7d847024c06be3b3
def file_availability(self, k, n, server_dBA): <NEW_LINE> <INDENT> assert server_dBA > 9 <NEW_LINE> factor = binomial(n, k-1) <NEW_LINE> factor_dBA = 10 * math.log10(factor) <NEW_LINE> exponent = n - k + 1 <NEW_LINE> file_dBA = server_dBA * exponent - factor_dBA <NEW_LINE> return file_dBA
The full formula for the availability of a specific file is:: 1 - sum([choose(N,i) * p**i * (1-p)**(N-i)] for i in range(k)]) Where choose(N,i) = N! / ( i! * (N-i)! ) . Note that each term of this summation is the probability that there are exactly 'i' servers available, and what we're doing is adding up the cases w...
625941cc2c8b7c6e89b358b8
def get_secret(settings, secrets=secrets): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return secrets[settings] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> error_msg = 'Set the {0} environment variable'.format(settings) <NEW_LINE> <DEDENT> raise ImproperlyConfigured(error_msg)
Get the secret variable or return explicit exception.
625941cca4f1c619b28b0131
def playHand(hand, wordList, n): <NEW_LINE> <INDENT> totalScore = 0 <NEW_LINE> while calculateHandlen(hand): <NEW_LINE> <INDENT> print("Current Hand:",end = " ") <NEW_LINE> displayHand(hand) <NEW_LINE> word = input("Enter word, or a \".\" to indicate that you are finished: ") <NEW_LINE> if word == '.': <NEW_LINE> <INDE...
Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When ...
625941ccf8510a7c17cf97f4
def close_file_object(self, file_object): <NEW_LINE> <INDENT> pass
does nothing, since we are using StringIO as our file objects, and we cannot access their contents after they are closed.
625941cce1aae11d1e749daf
def test_set_owner(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ticket_id = self._tester.create_ticket(self.__class__.__name__, info={'owner': 'lammy'}) <NEW_LINE> self.env.config.set('ticket-workflow', 'reassign.set_owner', "alice,bill") <NEW_LINE> self.env.config.save() <NEW_LINE> self._tester.go_to_ticket(tic...
When using the workflow operation `set_owner` with a specific list of available owners, the assign-to field will only contain that list of owners. The requesting user will not be added to the list, and the current ticket owner will not be added to the list.
625941cca05bb46b383ec919
@ros.command() <NEW_LINE> @click.option("--name", help="Stack name", required=True) <NEW_LINE> @click.option( "--template", help="JSON template (path or - to supply through stdin)", required=True, type=click.File("r"), ) <NEW_LINE> @click.option( "--parameter", default=[], type=RosParameterType(), multiple=True, help="...
Creates a ROS stack
625941ccbf627c535bc132c7
def update_global_desktop_entitlement(self, global_desktop_entitlement_data: dict, global_desktop_entitlement_id: str): <NEW_LINE> <INDENT> headers = self.access_token <NEW_LINE> headers["Content-Type"] = 'application/json' <NEW_LINE> json_data = json.dumps(global_desktop_entitlement_data) <NEW_LINE> response = request...
Updates a Global Desktop Entitlement. Requires global_desktop_entitlement_data as a dict and global_desktop_entitlement_id as string Available for Horizon 8 2111 and later.
625941cca8370b7717052997
def normalize_codec_name(name): <NEW_LINE> <INDENT> name = UnicodeDammit.CHARSET_ALIASES.get(name.lower(), name) <NEW_LINE> try: <NEW_LINE> <INDENT> return codecs.lookup(name).name <NEW_LINE> <DEDENT> except (LookupError, TypeError, ValueError): <NEW_LINE> <INDENT> pass
Return the Python name of the encoder/decoder Returns: str, None
625941cc91f36d47f21ac5eb
def get_scan_path(self): <NEW_LINE> <INDENT> paths = self.locate("armadito-scan", "/usr/local/bin/") <NEW_LINE> return paths[0] if paths else None
return the full path of the scan tool
625941cc6e29344779a6270a
def removeNthFromEnd(self, head, n): <NEW_LINE> <INDENT> if head == None or head.next == None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> target = ListNode(0) <NEW_LINE> target.next = head <NEW_LINE> end = target <NEW_LINE> mid = target <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> end = end.next <NEW_LINE...
:type head: ListNode :type n: int :rtype: ListNode
625941cc956e5f7376d70f66
def sendNewMessage(self, request_dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sub = escape(request_dict['subject']) <NEW_LINE> message = escape(request_dict['message']) <NEW_LINE> recipients = request_dict['recipients'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return { 'success' : 0, 'error' : 'N...
Creates a new thread with specified users, subject, and initial message
625941cc711fe17d82542464
def add_bad_any_type_use_error(self, location, bson_type, ast_type, ast_parent): <NEW_LINE> <INDENT> self._add_error( location, ERROR_ID_BAD_ANY_TYPE_USE, ("The BSON Type '%s' is not allowed in a list of bson serialization types for" + "%s '%s'. It must be only a single bson type.") % (bson_type, ast_type, ast_parent))
Add an error about any being used in a list of bson types.
625941cc45492302aab5e3bb
def _write_seqx(self, name, sequence_param): <NEW_LINE> <INDENT> pass
Write a sequence to a seqx-file. @param str name: name of the sequence to be created @param list sequence_param: a list of dict, which contains all the information, which parameters are to be taken to create a sequence. The dict will have at least the entry ...
625941cc460517430c39427d
def test_copy_email(self): <NEW_LINE> <INDENT> self.new_contact.saveContact() <NEW_LINE> Contact.copy_email("0712345678") <NEW_LINE> self.assertEqual(self.new_contact.email,pyperclip.paste())
Test to confirm that we are copying the email address from a found contact
625941cc63f4b57ef0001212
def plot_tracks(track_generator, get_figure=False): <NEW_LINE> <INDENT> cv.check_type('track_generator', track_generator, openmoc.TrackGenerator) <NEW_LINE> if not track_generator.containsTracks(): <NEW_LINE> <INDENT> py_printf('ERROR', 'Unable to plot Tracks since the track ' + 'generator has not yet generated tracks'...
Plot the characteristic tracks from an OpenMOC simulation. This method requires that tracks have been generated by a TrackGenerator. Parameters ---------- track_generator : openmoc.TrackGenerator A TrackGenerator with the tracks to plot get_figure : bool Whether or not to return the Matplotlib figure Returns...
625941cc99fddb7c1c9de489
def do_after(ms, callable, *args, **kw): <NEW_LINE> <INDENT> app = QtWidgets.QApplication.instance() or QtWidgets.QApplication(sys.argv) <NEW_LINE> QtCore.QTimer.singleShot(ms, lambda : callable(*args, **kw))
Invoke the callable after the given number of milliseconds.
625941ccbd1bec0571d90727
@given(u'I am driving the car') <NEW_LINE> def step_impl(context): <NEW_LINE> <INDENT> parking40 = Parking40() <NEW_LINE> mockup = Mockup() <NEW_LINE> context.mockup = mockup <NEW_LINE> context.parking40 = parking40 <NEW_LINE> freeParkingPlaces = context.parking40.getFreeParkingPlaces() <NEW_LINE> context.freeParkingPl...
@fn step_impl @brief @given
625941cce8904600ed9f2024
def Config(**options): <NEW_LINE> <INDENT> names = ['title', 'xlabel', 'ylabel', 'xscale', 'yscale', 'xticks', 'yticks', 'axis', 'xlim', 'ylim'] <NEW_LINE> for name in names: <NEW_LINE> <INDENT> if name in options: <NEW_LINE> <INDENT> getattr(pyplot, name)(options[name]) <NEW_LINE> <DEDENT> <DEDENT> loc_dict = {'upper ...
Configures the plot. Pulls options out of the option dictionary and passes them to the corresponding pyplot functions.
625941ccf7d966606f6aa0fc
def checkForImageFileOar(self): <NEW_LINE> <INDENT> if os.path.exists(self.nextimageFile) & (self.nextLine == 1): <NEW_LINE> <INDENT> print('%s exists' % self.nextimageFile) <NEW_LINE> self.periodEventraw.stop() <NEW_LINE> self.integrateLineDataOar() <NEW_LINE> self.setnextimageFileOar() <NEW_LINE> <DEDENT> elif os.pat...
Look if data have been generated (CPU and GPU method)
625941cc1d351010ab855c14
def set_log_dir(self, model_path=None): <NEW_LINE> <INDENT> self.epoch = 0 <NEW_LINE> now = datetime.datetime.now() <NEW_LINE> if model_path: <NEW_LINE> <INDENT> regex = r".*/[\w-]+(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/mask\_rcnn\_[\w-]+(\d{4})\.h5" <NEW_LINE> m = re.match(regex, model_path) <NEW_LINE> if m: <NEW_LINE> ...
Sets the model log directory and epoch counter. model_path: If None, or a format different from what this code uses then set a new log directory and start epochs from 0. Otherwise, extract the log directory and the epoch counter from the file name.
625941cccad5886f8bd270d1
def regression(myDataSet): <NEW_LINE> <INDENT> from sklearn import linear_model <NEW_LINE> x = myDataSet[['x1','x2']] <NEW_LINE> xarr = x.as_matrix() <NEW_LINE> X = np.array([np.concatenate((v,[1])) for v in xarr]) <NEW_LINE> model = linear_model.LinearRegression(fit_intercept = True) <NEW_LINE> y = myDataSet[['y']] <N...
Input = numpy array with three columns Column 1 is the dependent variable Columns 2 and 3 are the independent variables Returns = a column vector with the b coefficients
625941cc8e71fb1e9831d8a1
def _format_subheader(headtxt): <NEW_LINE> <INDENT> subheader = "#==========================================================" "===================\n# %s\n#===============================" "==============================================" % headtxt <NEW_LINE> return subheader
Return a formatted sub-header title for text files as follows #======================================================================== # headtxt #========================================================================
625941ccb830903b967e9a03
def loglikelihood(self, X): <NEW_LINE> <INDENT> marg = self.marginal_likelihood(X) <NEW_LINE> return np.log(marg).sum()
Calculates the joint log-likelihood of the given set of observations under this model. Parameters ---------- X : np.ndarray Observations. Returns ------- float Log-likelihood.
625941cc5fcc89381b1e17b7
def extract(get_value, metrics): <NEW_LINE> <INDENT> return np.array([get_value(m) for m in metrics])
Extract metrics.
625941cc851cf427c661a607
def test_none_to_none(self): <NEW_LINE> <INDENT> self.assertEqual( get_new_entries(None, None), [], )
What if both lists are none
625941cca8370b7717052998
def get_vlines(pix, w, h): <NEW_LINE> <INDENT> vlines = [] <NEW_LINE> for x in range(w): <NEW_LINE> <INDENT> y1, y2 = (None,None) <NEW_LINE> black = 0 <NEW_LINE> run = 0 <NEW_LINE> for y in range(h): <NEW_LINE> <INDENT> if pix[x,y] != (255,255,255): <NEW_LINE> <INDENT> print(pix[x,y] ) <NEW_LINE> <DEDENT> if pix[x,y] =...
Get start/end pixels of lines containing vertical runs of at least THRESH black pix
625941ccd99f1b3c44c67687