code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def write_string(*args, **kwargs): <NEW_LINE> <INDENT> return _pmt_swig.write_string(*args, **kwargs) | write_string(swig_int_ptr obj) -> std::string
Return a string representation of . This is the same output as would be generated by pmt::write. | 625941ca5fcc89381b1e176e |
def retry_on_exception(exceptions): <NEW_LINE> <INDENT> def real_decorator(func): <NEW_LINE> <INDENT> @backoff.on_exception(backoff.expo, exceptions, max_tries=OutputDispatcher.MAX_RETRY_ATTEMPTS, jitter=backoff.full_jitter, on_backoff=backoff_handler(), on_success=success_handler(), on_giveup=giveup_handler()) <NEW_LI... | Decorator function to attempt retry based on passed exceptions | 625941ca63b5f9789fde7196 |
def add_field(self, field): <NEW_LINE> <INDENT> self.__fields.append(field) | field (unicode) | 625941ca851cf427c661a5bf |
def _get_models(self, args): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> models = [] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> arg = arg.lower() <NEW_LINE> match_found = False <NEW_LINE> for model in registry.get_models(): <NEW_LINE> <INDENT> if model._meta.app_label == arg: <NEW_LINE> <INDENT> models.append... | Get Models from registry that match the --models args | 625941ca38b623060ff0ae9e |
def get_panda_skip_rows(args): <NEW_LINE> <INDENT> if args.segmentation: <NEW_LINE> <INDENT> return 5 <NEW_LINE> <DEDENT> elif args.forestfires: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 | Get the number of rows to skip when reading using Panda APIs | 625941caaad79263cf390af0 |
def get_com_names_by_com_indices(self,com_indices): <NEW_LINE> <INDENT> companys = self.get_all_companys_with_index() <NEW_LINE> com_names = [] <NEW_LINE> for index in com_indices: <NEW_LINE> <INDENT> for com in companys: <NEW_LINE> <INDENT> if com.index == index: <NEW_LINE> <INDENT> com_names.append(com.name) <NEW_LIN... | :param com_indices:
:return: | 625941caa219f33f34628a1a |
def get_config(): <NEW_LINE> <INDENT> cfg = VersioneerConfig() <NEW_LINE> cfg.VCS = "git" <NEW_LINE> cfg.style = "pep440" <NEW_LINE> cfg.tag_prefix = "" <NEW_LINE> cfg.parentdir_prefix = "opat-" <NEW_LINE> cfg.versionfile_source = "opat/_version.py" <NEW_LINE> cfg.verbose = False <NEW_LINE> return cfg | Create, populate and return the VersioneerConfig() object. | 625941ca82261d6c526ab54f |
def Recv(endpoints, get_vars, sync=True): <NEW_LINE> <INDENT> assert (type(get_vars) == list) <NEW_LINE> epmap = endpoints.split(",") <NEW_LINE> endpoints = list(set(epmap)) <NEW_LINE> helper = LayerHelper("Recv", **locals()) <NEW_LINE> helper.append_op( type="recv", inputs={"X": get_vars}, outputs={"Out": get_vars}, a... | Receive variables from server side
Args:
endpoints (str): comma seperated IP:PORT pairs in the order
of send_vars to send
get_vars (list): vars to get from server after send completes.
sync (bool): whether to wait the request finish
Returns:
list: list of received variables | 625941cad7e4931a7ee9dfce |
def patched_open(self, *args, **kwargs): <NEW_LINE> <INDENT> error = None <NEW_LINE> for _ in range(8): <NEW_LINE> <INDENT> error = None <NEW_LINE> try: <NEW_LINE> <INDENT> return func(self, *args, **kwargs) <NEW_LINE> <DEDENT> except pyactiveresource.connection.ClientError as e: <NEW_LINE> <INDENT> error = e <NEW_LINE... | Add limits. | 625941ca596a897236089b71 |
def last_flight_assigned(flights, gate): <NEW_LINE> <INDENT> FlightsOnGate = [] <NEW_LINE> for i in range(len(flights)): <NEW_LINE> <INDENT> if flights[i].gate == gate: <NEW_LINE> <INDENT> FlightsOnGate.append(flights[i]) <NEW_LINE> <DEDENT> <DEDENT> FlightsOnGate = sorted(FlightsOnGate, key=lambda flight : flight.depa... | Renvoit le dernier avion affecté à la porte passée en argument | 625941cad18da76e23532586 |
@testing.requires_testing_data <NEW_LINE> def test_label_io_and_time_course_estimates(): <NEW_LINE> <INDENT> stc = read_source_estimate(stc_fname) <NEW_LINE> label = read_label(real_label_fname) <NEW_LINE> stc_label = stc.in_label(label) <NEW_LINE> assert_true(len(stc_label.times) == stc_label.data.shape[1]) <NEW_LINE>... | Test IO for label + stc files
| 625941ca1d351010ab855bcc |
def get_package_version(): <NEW_LINE> <INDENT> base = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> with open(os.path.join(base, "web_deploy/__init__.py")) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> m = version.match(line.strip()) <NEW_LINE> if not m: <NEW_LINE> <INDENT> continue <NEW_LINE> <D... | returns package version without importing it | 625941ca26068e7796caed8e |
def get(self, network, service_name): <NEW_LINE> <INDENT> logger.info('Discovering service %s in network %s', service_name, network) <NEW_LINE> if not isinstance(network, Network): <NEW_LINE> <INDENT> raise DisallowedOperationException( "Network argument to get must be of type butter.types.common.Network") <NEW_LINE> <... | Get a service in "network" named "service_name". | 625941ca8c3a87329515846b |
def test(self, args, targets, python_version): <NEW_LINE> <INDENT> skip_file = 'test/sanity/ansible-doc/skip.txt' <NEW_LINE> skip_modules = set(read_lines_without_comments(skip_file, remove_blank_lines=True)) <NEW_LINE> plugin_type_blacklist = set([ 'action', 'doc_fragments', 'cliconf', 'filter', 'httpapi', 'netconf', ... | :type args: SanityConfig
:type targets: SanityTargets
:type python_version: str
:rtype: TestResult | 625941cafff4ab517eb2f4ed |
def fit_line(x, y): <NEW_LINE> <INDENT> slope, intercept, r_value, p_value, err = stats.linregress(x, y) <NEW_LINE> return slope | slope calculation
Parameters: x and y array | 625941ca16aa5153ce362529 |
def default_frequencies(): <NEW_LINE> <INDENT> if RACE.num_nodes < 5: <NEW_LINE> <INDENT> freqs = { 'b': ['R', 'R', 'R', 'R', None, None, None, None], 'c': [1, 3, 6, 7, None, None, None, None], 'f': [5658, 5732, 5843, 5880, RHUtils.FREQUENCY_ID_NONE, RHUtils.FREQUENCY_ID_NONE, RHUtils.FREQUENCY_ID_NONE, RHUtils.FREQUEN... | Set node frequencies, R1367 for 4, IMD6C+ for 5+. | 625941ca26068e7796caed8f |
def remove_handler(self, handler: Callable[[Variable, float], None]) -> None: <NEW_LINE> <INDENT> self._handlers.discard(handler) | Remove a handler. | 625941ca0a50d4780f666f42 |
def get_count(self, using): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return sum([it.count() for it in self._querysets]) | Request count on each sub-query. | 625941ca71ff763f4b54973b |
def get_centered_molecule(self): <NEW_LINE> <INDENT> center = self.center_of_mass <NEW_LINE> new_coords = np.array(self.cart_coords) - center <NEW_LINE> return Molecule(self.species_and_occu, new_coords, charge=self._charge, spin_multiplicity=self._spin_multiplicity, site_properties=self.site_properties) | Returns a Molecule centered at the center of mass.
Returns:
Molecule centered with center of mass at origin. | 625941ca377c676e91272259 |
def test_file_path(tmpdir): <NEW_LINE> <INDENT> storage = FileSystemStorage(location=str(tmpdir)) <NEW_LINE> assert not storage.exists("test.file") <NEW_LINE> f = io.StringIO("custom contents") <NEW_LINE> f_name = storage.save("test.file", f) <NEW_LINE> assert storage.path(f_name) == os.path.join(str(tmpdir), f_name) | File storage returns the full path of a file | 625941ca5f7d997b87174b48 |
def test_str_method(self): <NEW_LINE> <INDENT> my_amenity = Amenity() <NEW_LINE> string = "[{}] ({}) {}".format(my_amenity.__class__.__name__, my_amenity.id, my_amenity.__dict__) <NEW_LINE> self.assertEqual(str(my_amenity), string) | Checks str method | 625941ca596a897236089b72 |
def parse_input(self, request): <NEW_LINE> <INDENT> required_params_valid = self.check_and_parse_required_params_valid(request) <NEW_LINE> remaining_params_valid = self.check_and_parse_remaining_params_valid(request) <NEW_LINE> if required_params_valid and remaining_params_valid: <NEW_LINE> <INDENT> uid = Users.generat... | Parses request information about registration into a tuple containing
1. The validity of the params (True/False)
2. The parsed params into a dictionary with their post value as main key
and value and status as subkeys
:param request:
:return: Returns True, self.context on success,
... | 625941ca796e427e537b0676 |
def test_route_schedules_with_holes(self): <NEW_LINE> <INDENT> response = self.query_region("routes/R:5/route_schedules?from_datetime=20120615T000000") <NEW_LINE> is_valid_notes(response["notes"]) <NEW_LINE> schedules = get_not_null(response, 'route_schedules') <NEW_LINE> assert len(schedules) == 1, "there should be on... | route_schedule on the line R, which is a Y line with holes in the route schedule | 625941cabe7bc26dc91cd6b1 |
def run(self): <NEW_LINE> <INDENT> if not (self.table): <NEW_LINE> <INDENT> raise Exception("table need to be specified") <NEW_LINE> <DEDENT> path = self.s3_load_path() <NEW_LINE> output = self.output() <NEW_LINE> connection = output.connect() <NEW_LINE> cursor = connection.cursor() <NEW_LINE> self.init_copy(connection... | If the target table doesn't exist, self.create_table
will be called to attempt to create the table. | 625941ca76d4e153a657ebe2 |
def euler136(): <NEW_LINE> <INDENT> pass | >>> euler136()
'to-do' | 625941ca3346ee7daa2b2e1c |
def __init__(self, parent, tool_bar, image_cache, item, controller, show_labels): <NEW_LINE> <INDENT> self.item = item <NEW_LINE> self.tool_bar = tool_bar <NEW_LINE> action = item.action <NEW_LINE> self.control_id = None <NEW_LINE> if action.image is None: <NEW_LINE> <INDENT> self.control = tool_bar.addAction(action.na... | Creates a new tool bar tool for an action item. | 625941ca6aa9bd52df036e55 |
def setup_environment(): <NEW_LINE> <INDENT> data_path = os.path.join(os.path.dirname(__file__), 'data') <NEW_LINE> assert os.path.exists(os.path.join(data_path, '7_param.dat')) <NEW_LINE> key = 'GEOTRANS_DATA' <NEW_LINE> os.environ[key] = data_path | Add the data directory environment variable. This must be done
before the geotrans2_lib is loaded (because that's where the
library is loaded, and the environment is set at load time). | 625941cabe7bc26dc91cd6b2 |
def publish_camera(): <NEW_LINE> <INDENT> producer = KafkaProducer(bootstrap_servers=brokers, value_serializer=lambda v: json.dumps(v).encode('utf-8')) <NEW_LINE> camera_data = {'camera-id':"1","position":"frontspace","image_bytes":"123","frame":"0"} <NEW_LINE> camera = cv2.VideoCapture(0) <NEW_LINE> i = 0 <NEW_LINE> t... | Publish camera video stream to specified Kafka topic.
Kafka Server is expected to be running on the localhost. Not partitioned. | 625941ca091ae35668667010 |
def depthFirstSearch(problem): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> mydict = { } <NEW_LINE> yy_dfs(problem.getStartState(),problem,ans,mydict) <NEW_LINE> return ans | Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start... | 625941ca57b8e32f5248354b |
def register_model_command(self, type, command, handler): <NEW_LINE> <INDENT> if type not in self._models: <NEW_LINE> <INDENT> raise Exception("Unknown model type: %s." % type) <NEW_LINE> <DEDENT> if type not in self._model_commands: <NEW_LINE> <INDENT> self._model_commands[type] = {} <NEW_LINE> <DEDENT> if command in ... | Register a custom request handler associcated with a model type.
Parameters
----------
type : string, required
Unique identifier of an already-registered model type.
command : string, required
Unique-to-the model name of the request.
handler : callback function, required
Function that will be called to handle re... | 625941ca2eb69b55b151c95f |
def __delslice__(self, *args): <NEW_LINE> <INDENT> return _yarp.DVector___delslice__(self, *args) | __delslice__(DVector self, std::vector< double >::difference_type i, std::vector< double >::difference_type j) | 625941ca97e22403b379d04a |
def subtest_download(self): <NEW_LINE> <INDENT> self.session2 = Session(self.config2, ignore_singleton=True) <NEW_LINE> self._logger.debug("Downloader: Sleeping 3 secs to let Session2 start") <NEW_LINE> time.sleep(3) <NEW_LINE> tdef2 = TorrentDef.load(self.torrentfn) <NEW_LINE> dscfg2 = DownloadStartupConfig() <NEW_LIN... | Now download the file via another Session | 625941ca5e10d32532c5efd8 |
def handle_observe_response(self, request, response): <NEW_LINE> <INDENT> if request.mtype is None: <NEW_LINE> <INDENT> response.mtype = CON <NEW_LINE> <DEDENT> if self._serverobservation is None: <NEW_LINE> <INDENT> if response.opt.observe is not None: <NEW_LINE> <INDENT> self.log.info("Dropping observe option from re... | Modify the response according to the Responder's understanding of
the involved observation (eg. drop the observe flag it's not involved
in an observation or the observation was cancelled), and update the
Responder/context if the response modifies the observation state (eg.
by being unsuccessful). | 625941ca287bf620b61d3b15 |
def _register_api(app): <NEW_LINE> <INDENT> app.add_url_rule('/user/', "user_login", user_login, methods=['PUT']) | interface method so the app can register the API (routing) calls. | 625941caeab8aa0e5d26dc09 |
def make_training_graph(graph, test_node, n): <NEW_LINE> <INDENT> graphCopy = graph.copy() <NEW_LINE> edgesBeingRemoved = sorted(nx.edges(graphCopy,test_node))[:n] <NEW_LINE> graphCopy.remove_edges_from(edgesBeingRemoved) <NEW_LINE> return graphCopy | To make a training graph, we need to remove n edges from the graph.
As in lecture, we'll assume there is a test_node for which we will
remove some edges. Remove the edges to the first n neighbors of
test_node, where the neighbors are sorted alphabetically.
E.g., if 'A' has neighbors 'B' and 'C', and n=1, then the edge
... | 625941ca6fb2d068a760f14e |
def process(self): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> if (self.file_handle.closed): <NEW_LINE> <INDENT> self.file_handle = open(self.file_handle.name) <NEW_LINE> <DEDENT> soup = BeautifulSoup(self.file_handle) <NEW_LINE> if not soup.contents[0] == "DOCTYPE NETSCAPE-Bookmark-file-1": <NEW_LINE> <INDENT> raise Exce... | Process an html google bookmarks export and import them into bookie
The export format is a tag as a heading, with urls that have that tag
under that heading. If a url has N tags, it will appear N times, once
under each heading. | 625941ca6e29344779a626c3 |
@node.commandWrap <NEW_LINE> def polyMapSew(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.polyMapSew(*args, **kwargs) | :rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base | 625941cabe8e80087fb20cf4 |
def __parseInfo(self, strIn): <NEW_LINE> <INDENT> workingData = strIn.split("\n") <NEW_LINE> for i in workingData: <NEW_LINE> <INDENT> if "Revision: " in i: <NEW_LINE> <INDENT> return int(i.split("Revision: ")[1]) | Parse info to extract the revision | 625941caf7d966606f6aa0b5 |
def mask2strata(array, value=[1]): <NEW_LINE> <INDENT> strata = np.zeros(array.shape[:-1], np.int16) <NEW_LINE> nodata = np.zeros(array.shape[:-1], np.int16) <NEW_LINE> for i in range(0, array.shape[2]): <NEW_LINE> <INDENT> if len(value) == 1: <NEW_LINE> <INDENT> strata += (array[:, :, i] == value[0]) * (2 ** i) <NEW_L... | create a strata layer from a stack of masks
Args:
array (ndarray): array of maskes
value (ndarray): which value to use
Returns:
strata (ndarray): array of strata | 625941ca796e427e537b0677 |
def valid_host(hostname): <NEW_LINE> <INDENT> suffix = hostname[-3:] <NEW_LINE> if suffix == "com" or suffix == "net" or suffix == "local": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Returns True if hostname ends with .com, .net, .local | 625941ca462c4b4f79d1d782 |
def __init__(self, simulator, position=(0, 0, 0.085), orientation=(0, 0, 0, 1), fixed_base=False, scale=1., urdf=os.path.dirname(__file__) + '/urdfs/youbot/youbot.urdf'): <NEW_LINE> <INDENT> if position is None: <NEW_LINE> <INDENT> position = (0., 0., 0.085) <NEW_LINE> <DEDENT> if len(position) == 2: <NEW_LINE> <INDENT... | Initialize the Youbot robot.
Args:
simulator (Simulator): simulator instance.
position (np.array[float[3]]): Cartesian world position.
orientation (np.array[float[4]]): Cartesian world orientation expressed as a quaternion [x,y,z,w].
fixed_base (bool): if True, the robot base will be fixed in the world... | 625941ca50812a4eaa59c3d3 |
def __init__(self, client, metrics_store, sample_interval): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.metrics_store = metrics_store <NEW_LINE> self.sample_interval = sample_interval <NEW_LINE> self.logger = logging.getLogger(__name__) | :param client: The Elasticsearch client for this cluster.
:param metrics_store: The configured metrics store we write to.
:param sample_interval: An integer controlling the interval, in seconds, between collecting samples. | 625941ca32920d7e50b28281 |
def get_area(self): <NEW_LINE> <INDENT> return self.length*self.height | Calculate the area of the shape | 625941ca24f1403a92600c18 |
@pytest.mark.gen_test <NEW_LINE> def test_double_registration_with_a_coroutine_hanlder( server, service, ThriftTest ): <NEW_LINE> <INDENT> @server.thrift.register(ThriftTest) <NEW_LINE> @server.thrift.register(ThriftTest) <NEW_LINE> def testVoid(request): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> tchannel = TChannel... | Registering twice should override the original.
This is mostly testing that ``build_handler`` correctly passes on the
function name. | 625941ca627d3e7fe0d68f00 |
def pretty(text): <NEW_LINE> <INDENT> return ' '.join([word.capitalize() for word in words(text)]) | Converts the inputted text to "pretty" text by turning camel
humps and underscores/dashes to capitalized words.
(TheQuickBrownFox -> The Quick Brown Fox,
the_quick_fox -> The Quick Fox)
:sa [[#words]]
:param text <str>
:return <str>
:usage |import projex.text
|print projex... | 625941ca004d5f362079a3e4 |
def list_gpus(): <NEW_LINE> <INDENT> re = '' <NEW_LINE> nvidia_smi = ['nvidia-smi', '/usr/bin/nvidia-smi', '/usr/local/nvidia/bin/nvidia-smi'] <NEW_LINE> for cmd in nvidia_smi: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> re = subprocess.check_output([cmd, "-L"], universal_newlines=True) <NEW_LINE> <DEDENT> except OSEr... | Return a list of GPUs
Returns
-------
list of int:
If there are n GPUs, then return a list [0,1,...,n-1]. Otherwise returns
[]. | 625941ca92d797404e30423b |
def test_regenerate_only_if_necessary(self): <NEW_LINE> <INDENT> u <NEW_LINE> self.build_js_translations() <NEW_LINE> mtimes = {} <NEW_LINE> for filename in os.listdir(self.temp_dir): <NEW_LINE> <INDENT> fullname = os.path.join(self.temp_dir, filename) <NEW_LINE> mtimes[filename] = os.path.getmtime(fullname) <NEW_LINE>... | Test that translation files are only generated when necessary. | 625941cad8ef3951e32435ee |
def fill(self, fill_value): <NEW_LINE> <INDENT> self.x.fill(fill_value) | Inplace filling of data array with specified value.
Parameters
----------
fill_value : {scalar, string, etc}
Value to replace every element of the data array.
Returns
-------
out : None
Examples
--------
>>> y = larry([0, 1])
>>> y.fill(9)
>>> y
label_0
0
1
x
array([9, 9]) | 625941cabde94217f3682ea3 |
def __register_thumbnailer(self, thumbnailer): <NEW_LINE> <INDENT> for mt in thumbnailer.get_mime_types(): <NEW_LINE> <INDENT> l = self.__mime_handlers.get(mt, []) <NEW_LINE> l.append(thumbnailer) <NEW_LINE> self.__mime_handlers[mt] = l <NEW_LINE> <DEDENT> self.__thumbnailers[str(thumbnailer)] = thumbnailer | Registers the given Thumbnailer component. | 625941cabe8e80087fb20cf5 |
def test_login_credentials(self): <NEW_LINE> <INDENT> result = self._login() <NEW_LINE> self.assertIn('You have successfully logged in.', result.data) <NEW_LINE> result = self._logout() <NEW_LINE> self.assertIn('You have successfully logged out.', result.data) <NEW_LINE> result = self._login(username='bogus') <NEW_LINE... | Test that logging in by providing a username and password works as
expected. | 625941ca3317a56b86939d0b |
def backtest_custom_bot(self, botguid: str, minutestotest: int): <NEW_LINE> <INDENT> response = super()._execute_request("/BacktestCustomBot", {"botGuid": botguid, "minutesToTest": minutestotest}) <NEW_LINE> try: <NEW_LINE> <INDENT> return HaasomeClientResponse(EnumErrorCode(int(response["ErrorCode"])), response["Erro... | Backtest a custom bot (Note: This function will will make a request to the exchange so don't call to often)
:param botguid: str: Custom bot guid
:param minutestotest: int: Amount of minutes to test in the past
:returns: :class:`~haasomeapi.dataobjects.util.HaasomeClientResponse`
:returns: In .result :class:`~haasomea... | 625941ca3c8af77a43ae3851 |
def filter(self, cls, field=None, value=None): <NEW_LINE> <INDENT> raise OverrideError('filter') | Retrieve all model objects by class and a field | 625941ca71ff763f4b54973c |
def search_nested(self, lines): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if self.fence is None: <NEW_LINE> <INDENT> ws = self.parse_whitespace(line) <NEW_LINE> m = RE_NESTED_FENCE_START.match(line, self.ws_len) <NEW_LINE> if m is not None: <NEW_LINE> <INDENT> start = count <NEW_LI... | Search for nested fenced blocks. | 625941ca8a43f66fc4b54117 |
def parse_iso_date(date_string: str) -> date: <NEW_LINE> <INDENT> if not isinstance(date_string, str): <NEW_LINE> <INDENT> raise ValueError("Expected string") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return datetime.strptime(date_string, '%Y-%m-%d').date() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> ... | Parse a date in the string format defined in ISO 8601. | 625941ca2eb69b55b151c960 |
def MinimalMOST(l, orderingsToEnforce): <NEW_LINE> <INDENT> minimal = None <NEW_LINE> for i_name, i_most in l.items(): <NEW_LINE> <INDENT> not_min = False <NEW_LINE> for j_name, j_most in l.items(): <NEW_LINE> <INDENT> if i_most > j_most: <NEW_LINE> <INDENT> logging.debug("%s not minimal: greater than %s" % (i_most, j_... | Find the minimal MOST among the MOSTs in l, where l is a dictionary of
(name, MOST) pairs | 625941ca167d2b6e31218c47 |
def normalise_input(user_input): <NEW_LINE> <INDENT> remove_spaces = user_input.strip() <NEW_LINE> no_punct = remove_punct(remove_spaces.lower()) <NEW_LINE> created_list = no_punct.split() <NEW_LINE> filtered_words = filter_words(created_list, skip_words) <NEW_LINE> return filtered_words | This function removes all punctuation from the string and converts it to
lower case. It then splits the string into a list of words (also removing
any extra spaces between words) and further removes all "unimportant"
words from the list of words using the filter_words() function. The
resulting list of "important" words... | 625941ca004d5f362079a3e5 |
def accuracy(self, data, convert=False): <NEW_LINE> <INDENT> if convert: <NEW_LINE> <INDENT> results = [(np.argmax(self.feedforward(x)), np.argmax(y)) for (x, y) in zip(*data)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results = [(np.argmax(self.feedforward(x)), y) for (x, y) in zip(*data)] <NEW_LINE> <DEDENT> retu... | Return the number of inputs in ``data`` for which the neural
network outputs the correct result. The neural network's
output is assumed to be the index of whichever neuron in the
final layer has the highest activation.
The flag ``convert`` should be set to False if the data set is
validation or test data (the usual cas... | 625941caa8370b7717052951 |
def test_accessing_attributes_of_inputs(self): <NEW_LINE> <INDENT> button = self.browser.find_by_css('input[name="send"]').first <NEW_LINE> assert_equals(button['name'], 'send') | should allow input's attributes retrieval | 625941cad486a94d0b98e1f7 |
@manager.command <NEW_LINE> def test(coverage=False): <NEW_LINE> <INDENT> import unittest <NEW_LINE> tests = unittest.TestLoader().discover('test') <NEW_LINE> unittest.TextTestRunner(verbosity=2).run(tests) | Run the unit tests. | 625941cad99f1b3c44c67641 |
def rolling_max(frq, rs, window=8): <NEW_LINE> <INDENT> window = 2*(window//2) <NEW_LINE> new_frq = frq[window//2:-window//2] <NEW_LINE> new_rs = [] <NEW_LINE> for i in range(window//2, len(rs)-window//2): <NEW_LINE> <INDENT> new_rs.append(max(rs[i-window//2:i+window//2])) <NEW_LINE> <DEDENT> return np.array(new_frq), ... | Return the rolling maximum of the spectral
acceleration (rs) based on the specified window.
The window is centered at each frequency (x-value).
Parameters
----------
frq : 1D list/tuple/ndarray
Frequencies (x-values) of input.
rs : 1D list/tuple/ndarray
Spectral acceleration (y-values) of input.
Object sh... | 625941ca1b99ca400220ab63 |
def _bi_meta_files(self, m_string_file_flag, m_string_path, m_set_files): <NEW_LINE> <INDENT> df_return = pandas.DataFrame() <NEW_LINE> list_meta_00 = list() <NEW_LINE> list_meta_col = list() <NEW_LINE> if m_string_file_flag == 'all': <NEW_LINE> <INDENT> for string_file in m_set_files: <NEW_LINE> <INDENT> string_file_p... | this method gathers meta data on the designated files; the data gathered
is the file name, length (number of lines), max string length of column, column
names
Requirements:
package pandas
package os
Inputs:
m_string_file_flag
Type: string
Desc: the flag to determine how to get the metadata from each file
m_string_pa... | 625941caad47b63b2c50a031 |
def read_all_ids(self, connection: Connection, tracker_id: int) -> List[int]: <NEW_LINE> <INDENT> raise NotImplementedError() | Reads IDs of all artifacts in the database that belong to the specified tracker
:param connection: Database connection
:param tracker_id: ID of the tracker
:return: List of tracker IDs | 625941ca94891a1f4081bb5b |
def age_model_rdm(participant_tsv): <NEW_LINE> <INDENT> participants = pd.read_csv(participant_tsv, sep=",") <NEW_LINE> subs = np.array(participants["subject"]) <NEW_LINE> ages = np.array(participants["age"]) <NEW_LINE> subs_order = np.argsort(ages) <NEW_LINE> subs = subs[subs_order] <NEW_LINE> ages = ages[subs_order] ... | Parameters
============
subs: list of str
List of subjects.
participant_tsv: str
Path to participant.tsv to read ages.
Returns
========
rdm: 2d-array
Ageing model RDM.
subject_order: list | 625941ca099cdd3c635f0d0c |
def verify_annotation(ann_obj, collection_configuration): <NEW_LINE> <INDENT> issues = [] <NEW_LINE> issues += verify_annotation_types(ann_obj, collection_configuration) <NEW_LINE> issues += verify_equivs(ann_obj, collection_configuration) <NEW_LINE> issues += verify_entity_overlap(ann_obj, collection_configuration) <N... | Verifies the correctness of a given AnnotationFile.
Returns a list of AnnotationIssues. | 625941cabaa26c4b54cb11d2 |
def aggregator(self, data): <NEW_LINE> <INDENT> for d in data: <NEW_LINE> <INDENT> new_emails = mapper(split_email(d.new_value), self.aliases) <NEW_LINE> old_emails = mapper(split_email(d.old_value), self.aliases) <NEW_LINE> agg = self.bugs.get(d.bug_id) or Multiset(allow_negative=True) <NEW_LINE> agg = agg - new_email... | FLATTEN CC LISTS OVER TIME BY BUG
MULTISET COUNTS THE NUMBER OF EMAIL AT BUG CREATION
NEGATIVE MEANS THERE WAS AN ADD WITHOUT A REMOVE (AND NOT IN CURRENT LIST) | 625941ca91f36d47f21ac5a4 |
def find(self, nums1, nums2, k): <NEW_LINE> <INDENT> m, n = len(nums1), len(nums2) <NEW_LINE> t = k <NEW_LINE> while t != 0: <NEW_LINE> <INDENT> if m == 0: <NEW_LINE> <INDENT> return nums2[t] <NEW_LINE> <DEDENT> elif n == 0: <NEW_LINE> <INDENT> return nums1[t] <NEW_LINE> <DEDENT> elif nums1[m // 2] <= nums2[n // 2]: <N... | :param nums1:
:param nums2:
:param k:
:return: | 625941ca29b78933be1e575f |
def hdf5read_opsc_code(cls): <NEW_LINE> <INDENT> return [] | To keep the abstraction going return nothing for HDF5 OPSC code | 625941ca656771135c3eb920 |
def up(self): <NEW_LINE> <INDENT> with self.schema.table('shits') as table: <NEW_LINE> <INDENT> for i in [1,1,2,3]: <NEW_LINE> <INDENT> print(i) <NEW_LINE> <DEDENT> self.integer("lsd_quality") | Run the migrations. | 625941caa8370b7717052952 |
def CPPFLAGS(d_flags, r_flags): <NEW_LINE> <INDENT> env = Environment.GetCurrent() <NEW_LINE> if env.BuildMode() == "debug": <NEW_LINE> <INDENT> env.CppFlags().AddSV(d_flags) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env.CppFlags().AddSV(r_flags) | set module's global preprocess flags
Args:
d_flags : debug mode preprocess flags
r_flags : release mode preprocess flags | 625941cacdde0d52a9e530e5 |
def add_feature_click_day(all_data): <NEW_LINE> <INDENT> for feature in tqdm(['user_id', 'item_id', 'item_brand_id', 'category2_label', 'category3_label', 'context_page_id', 'shop_id', 'item_property_topic_k_15' ]): <NEW_LINE> <INDENT> feature_path = feature_data_path+'_2_7_' + feature + '_clicks_day.pkl' <NEW_LINE> if... | 向总体数据添加特征
feature=['user_id', 'item_id', 'item_brand_id', 'shop_id', 'user_gender_id', 'context_page_id',
'user_occupation_id', 'user_age_level']
拼接键[feature, 'day'] | 625941ca187af65679ca51d0 |
def get_fingerprint(group): <NEW_LINE> <INDENT> return cl.Counter(g.cycle_decomposition.count for g in group) | A histogram of cycle counts of permutations in a group. | 625941cad7e4931a7ee9dfcf |
def new_repo_config(): <NEW_LINE> <INDENT> config_defaults = { 'index.file': INDEX_FILE, 'index.format_version': INDEX_FORMAT_VERSION, 'recipes.default': 'HashDigestWorker, ThumbWorker, AutorotWorker, MetadataWorker', 'thumbnails.sidecar_dir': THUMB_SIDECAR_DIR, 'checksums.sidecar_enabled': SHA1_SIDECAR_ENABLED, 'check... | Return default repo configuration (Config instance). | 625941ca07f4c71912b11534 |
def modify(self, text): <NEW_LINE> <INDENT> default_definition = pretty_markdown.settings().get('default_missing_link_definition') <NEW_LINE> return link_utils.discover_missing_links(text, default_definition=default_definition) | Adds empty link definitions for reference links. | 625941cacc40096d61595a03 |
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): <NEW_LINE> <INDENT> costs = [] <NEW_LINE> for i in range(num_iterations): <NEW_LINE> <INDENT> grads, cost = propagate(w, b, X, Y) <NEW_LINE> dw = grads["dw"] <NEW_LINE> db = grads["db"] <NEW_LINE> w = w - (learning_rate*dw) <NEW_LINE> b = b - ... | This function optimizes w and b by running a gradient descent algorithm
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of shape (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
... | 625941ca851cf427c661a5c1 |
def to_numpy_array(self, image, rescale=None, channel_first=True): <NEW_LINE> <INDENT> self._ensure_format_supported(image) <NEW_LINE> if isinstance(image, PIL.Image.Image): <NEW_LINE> <INDENT> image = np.array(image) <NEW_LINE> <DEDENT> if is_torch_tensor(image): <NEW_LINE> <INDENT> image = image.numpy() <NEW_LINE> <D... | Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first
dimension.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to convert to a NumPy array.
rescale (`bool`, *optional*):
Whether or not to apply the scaling factor (to... | 625941caff9c53063f47c2a6 |
def upsert_frontend(self, fe_id, be_id, route="Path(`\/`)"): <NEW_LINE> <INDENT> payload = {"Frontend": {"Id": fe_id, "Route": route, "Type": "http", "BackendId": be_id}} <NEW_LINE> resp = requests.post(self.endpoint + "/v2/frontends", data=json.dumps(payload)) <NEW_LINE> return resp.json() | POST 'application/json' /v2/frontends | 625941ca046cf37aa974cdfa |
def preplace(p, *args, **kwargs): <NEW_LINE> <INDENT> def _replacer(*_, **__): <NEW_LINE> <INDENT> return p(*args, **kwargs) <NEW_LINE> <DEDENT> return promise(_replacer) | Replace promise arguments.
This will force the promise to disregard any arguments
the promise is fulfilled with, and to be called with the
provided arguments instead. | 625941ca9c8ee82313fbb827 |
def pollExternal(self, fileset): <NEW_LINE> <INDENT> logging.debug("Feeder name %s" % (fileset.name).split(":")[1]) <NEW_LINE> try: <NEW_LINE> <INDENT> factory = WMFactory("default", "WMCore.WMBSFeeder." + (fileset.name).split(":")[1]) <NEW_LINE> feeder = factory.loadObject( classname = "Feeder", getFrom... | Call relevant external source and get file details | 625941ca293b9510aa2c3349 |
def apply_method(self, r, **attr): <NEW_LINE> <INDENT> if r.name == "target": <NEW_LINE> <INDENT> if r.http == "POST" and r.representation == "json": <NEW_LINE> <INDENT> table = r.table <NEW_LINE> target_id = r.id <NEW_LINE> if not current.auth.s3_has_permission("update", table, record_id=target_id): <NEW_LINE> <INDENT... | Entry point for REST API
@param r: the S3Request
@param attr: controller arguments | 625941ca090684286d50ed97 |
def hostname_to_uid(hostname: str) -> str: <NEW_LINE> <INDENT> if hostname.startswith("Sonos-"): <NEW_LINE> <INDENT> baseuid = hostname.split("-")[1].replace(".local.", "") <NEW_LINE> <DEDENT> elif hostname.startswith("sonos"): <NEW_LINE> <INDENT> baseuid = hostname[5:].replace(".local.", "") <NEW_LINE> <DEDENT> else: ... | Convert a Sonos hostname to a uid. | 625941cad268445f265b4f20 |
def run_db_interaction(self, desc, func, *args, **kwargs): <NEW_LINE> <INDENT> return defer.ensureDeferred( self._store.db_pool.runInteraction(desc, func, *args, **kwargs) ) | Run a function with a database connection
Args:
desc (str): description for the transaction, for metrics etc
func (func): function to be run. Passed a database cursor object
as well as *args and **kwargs
*args: positional args to be passed to func
**kwargs: named args to be passed to func
Retu... | 625941ca3539df3088e2e3fd |
def put(self,api,data=None): <NEW_LINE> <INDENT> return requests.put(url=api,data=data,timeout=60) | api: URL
data: 文件流 | 625941caa219f33f34628a1c |
def evaluate(self, predicted_adj_mat: np.array, make_plots: bool = True): <NEW_LINE> <INDENT> true_edges, false_edges = [], [] <NEW_LINE> y_score = [] <NEW_LINE> for i, (u, v) in enumerate(self.test_edges): <NEW_LINE> <INDENT> score = predicted_adj_mat[u, v] <NEW_LINE> y_score.append(score) <NEW_LINE> true_edges.append... | Evaluate the performance of the link prediction algorithm with the generated graph
fill the
:return: | 625941cab57a9660fec33936 |
def _build(self, board, pseudo_ou_effects): <NEW_LINE> <INDENT> cross_pieces = white.select_white_hi_ry_board(board=board) <NEW_LINE> diagonal_pieces = white.select_white_ka_um_board(board=board) <NEW_LINE> ky_pieces = white.select_white_ky_board(board=board) <NEW_LINE> outputs = {} <NEW_LINE> for direction, pseudo_eff... | 利きの長い駒で王手しているかを判定する
王手の場合は擬似的な王の利きの範囲に他の駒を動かせられれ王手を防げるので、
pseudo_ou_effectsを利用して判定する
王手がかかっている可能性があるのは手番側のみなのなので、逆のパターンはない
:param board:
:param pseudo_ou_effects:
:return: | 625941ca3d592f4c4ed1d121 |
def addSecondaryStructure( self ): <NEW_LINE> <INDENT> dssp = Dssp( self.m ) <NEW_LINE> rmodel = dssp.run() <NEW_LINE> self.m.residues.set( 'secondary', rmodel['dssp'], comment='secondary structure from DSSP', version= T.dateString() + ' ' + self.version(), default='.') <NEW_LINE> self.m.residues.set('dssp_acc', rmode... | Adds a residue profile with the secondary structure as
calculated by the DSSP program.
Profile code::
B = residue in isolated beta-bridge
E = extended strand, participates in beta ladder
G = 3-helix (3/10 helix)
I = 5 helix (pi helix)
T = hydrogen bonded turn
S = bend
. = loop or irregular
@raise ExeCon... | 625941ca8c3a87329515846d |
def readJob(fd): <NEW_LINE> <INDENT> job = {} <NEW_LINE> job['id'] = struct.unpack("Q", fd.read(8))[0] <NEW_LINE> if job['id'] == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> job['pri'] = struct.unpack("I", fd.read(4))[0] <NEW_LINE> _ = struct.unpack("I", fd.read(4))[0] <NEW_LINE> job['del... | 读出一条 job | 625941ca6aa9bd52df036e56 |
def pre_validate(self): <NEW_LINE> <INDENT> pass | Validate pre-execution requirements | 625941ca5166f23b2e1a520b |
def _filter_scene_day_only_products( input_scene: Scene, filter_criteria: dict, sza_threshold: float = 100.0, day_fraction: Optional[float] = None ): <NEW_LINE> <INDENT> if day_fraction is None: <NEW_LINE> <INDENT> day_fraction = 0.1 <NEW_LINE> <DEDENT> logger.info("Running day coverage filtering...") <NEW_LINE> day_fi... | Run filtering for products that need a certain amount of day data. | 625941ca3eb6a72ae02ec58e |
def get_device_for_mac(mac_addr): <NEW_LINE> <INDENT> if HAS_FIREWALLD_NM and nm_is_imported: <NEW_LINE> <INDENT> client = NM.Client.new(None) <NEW_LINE> for nm_dev in client.get_devices(): <NEW_LINE> <INDENT> iface = nm_dev.get_iface() <NEW_LINE> if iface == "lo": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if nm... | Get device for the MAC address from ifcfg file | 625941ca6fb2d068a760f14f |
def linear_inverse(self, y, verbose=None): <NEW_LINE> <INDENT> if verbose is None: <NEW_LINE> <INDENT> verbose = self.verbose <NEW_LINE> <DEDENT> num_samples = y.shape[0] <NEW_LINE> if y.shape[1] != self.output_dim: <NEW_LINE> <INDENT> er = "Serious dimensionality inconsistency" <NEW_LINE> raise TrainingException(er) <... | Linear inverse approximation method. | 625941ca925a0f43d2549f29 |
def get_or_make_blank(name): <NEW_LINE> <INDENT> template, created = Template.objects.get_or_create(name=name) <NEW_LINE> if not template.file: <NEW_LINE> <INDENT> result = settings.MEDIA_ROOT + 'blank.odt' <NEW_LINE> template.file.save( 'blank.odt', File(open(result)) ) <NEW_LINE> template.save() <NEW_LINE> <DEDENT> r... | Get a template. If it doesn't exist create one that will be a blank document to prevent errors | 625941ca283ffb24f3c559b4 |
def splitport(hostport): <NEW_LINE> <INDENT> pseudoparsed = urllib.parse.SplitResult(None, hostport, None, None, None) <NEW_LINE> host, port = pseudoparsed.hostname, pseudoparsed.port <NEW_LINE> if port == numbers.constants.COAP_PORT: <NEW_LINE> <INDENT> port = None <NEW_LINE> <DEDENT> return host, port | Like urllib.parse.splitport, but return port as int, and as None if it
equals the CoAP default port. Also, it allows giving IPv6 addresses like a netloc:
>>> splitport('foo')
('foo', None)
>>> splitport('foo:5683')
('foo', None)
>>> splitport('[::1]:56830')
('::1', 56830) | 625941ca1b99ca400220ab64 |
def test_init(self): <NEW_LINE> <INDENT> self.assertEqual(self.new_creds.uname, "liz") <NEW_LINE> self.assertEqual(self.new_creds.passwrd, "pass") | Test for case initialization | 625941ca63d6d428bbe445a2 |
def vtec_ps_handler(fdict, arg): <NEW_LINE> <INDENT> suffix = arg["name"] <NEW_LINE> default_p, default_s = arg["default"].split(".") <NEW_LINE> value = html_escape(fdict.get(f"phenomena{suffix}", default_p)) <NEW_LINE> s = make_select(f"phenomena{suffix}", value, VTEC_PHENOMENA) <NEW_LINE> value = html_escape(fdict.ge... | Handle VTEC Phenomena + Significance. | 625941ca23849d37ff7b3142 |
def __init__(self, *, channel, target_id, message_type, **kwds): <NEW_LINE> <INDENT> self.channel = channel <NEW_LINE> self.target_id = target_id <NEW_LINE> self.message_type = message_type <NEW_LINE> self.__dict__.update(kwds) <NEW_LINE> pass | Raises an exception if the message fails certain validity checks. | 625941ca2c8b7c6e89b35873 |
def guide_letter(self): <NEW_LINE> <INDENT> n = (self.pos + self.guide_offset) % self.num_pins <NEW_LINE> return self.letters[n] | Returns the letter of the pin that is in position to effect the guide
arm. To check to see if this pin will effect the guide arm, call
is_effective(). | 625941ca4e696a04525c94fe |
def update_azure_storage_profile_with_http_info(self, id, body, **kwargs): <NEW_LINE> <INDENT> all_params = ['id', 'body', 'api_version'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_reque... | Update Azure storage profile # noqa: E501
Update Azure storage profile # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_azure_storage_profile_with_http_info(id, body, async_req=True)
>>> result = thread.get(... | 625941ca377c676e9127225b |
def __proxy_status(self, job_directory, job_id): <NEW_LINE> <INDENT> state_change = None <NEW_LINE> if not job_directory.has_metadata(JOB_FILE_PREPROCESSED): <NEW_LINE> <INDENT> proxy_status = status.PREPROCESSING <NEW_LINE> <DEDENT> elif job_directory.has_metadata(JOB_FILE_FINAL_STATUS): <NEW_LINE> <INDENT> proxy_stat... | Determine state with proxied job manager and if this job needs
to be marked as deactivated (this occurs when job first returns a
complete status from proxy. | 625941caa05bb46b383ec8d4 |
def guess_extension_from_headers(h): <NEW_LINE> <INDENT> if h.get('content-type') == 'application/pdf': <NEW_LINE> <INDENT> return '.pdf' <NEW_LINE> <DEDENT> if h.get('content-encoding') == 'x-gzip' and h.get('content-type') == 'application/postscript': <NEW_LINE> <INDENT> return '.ps.gz' <NEW_LINE> <DEDENT> if h.get('... | Given headers from an ArXiV e-print response, try and guess what the file
extension should be.
Based on: https://arxiv.org/help/mimetypes | 625941ca8e05c05ec3eea427 |
def __init__(self, uniformity, dom_shape, scale, seed=None): <NEW_LINE> <INDENT> self.init_params = util.init_params_from_locals(locals()) <NEW_LINE> self.u = uniformity <NEW_LINE> assert 0 <= uniformity and uniformity <= 1 <NEW_LINE> n = numpy.prod(dom_shape) <NEW_LINE> hist = numpy.zeros(n) <NEW_LINE> num_nonzero = m... | Generate synthetic data of varying uniformity
uniformity: parameter in [0,1] where 1 produces perfectly uniform data, 0 is maximally non-uniform
All cells set to zero except fraction equal to 'uniformity' value.
All non-zero cells are set to same value, then shuffled randomly. | 625941ca462c4b4f79d1d783 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.