language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def similar_filter_r(self, sentence_list): ''' Filter mutually similar sentences. Args: sentence_list: The list of sentences. Returns: The list of filtered sentences. ''' result_list = [] recursive_list = [] try: ...
python
def _make_fits(self): """Generates the data fits for any variables set for fitting in the shell.""" a = self.tests[self.active] args = self.curargs #We need to generate a fit for the data if there are any fits specified. if len(args["fits"]) > 0: for fit in list(args[...
python
def debug(self, msg, *args, **kwargs): """ Log a message with DEBUG level. Automatically includes stack info unless it is specifically not included. """ kwargs.setdefault('inc_stackinfo', True) self.log(DEBUG, msg, args, **kwargs)
java
public void setDefaultTags(java.util.Collection<MessageTag> defaultTags) { if (defaultTags == null) { this.defaultTags = null; return; } this.defaultTags = new com.amazonaws.internal.SdkInternalList<MessageTag>(defaultTags); }
python
def connect(self, logfile=None, force_discovery=False, tracefile=None): """Connect to the device. Args: logfile (file): Optional file descriptor for session logging. The file must be open for write. The session is logged only if ``log_session=True`` was passed to the constru...
python
def thing_type_present(name, thingTypeName, thingTypeDescription, searchableAttributesList, region=None, key=None, keyid=None, profile=None): ''' Ensure thing type exists. .. versionadded:: 2016.11.0 name The name of the state definition thingTypeName Name of the thing typ...
python
def fetch_all_kernels(self): r""" Returns a generator that yields all of the kernels available to the droplet :rtype: generator of `Kernel`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for kern in api.pagin...
python
def i2c_bitrate(self): """I2C bitrate in kHz. Not every bitrate is supported by the host adapter. Therefore, the actual bitrate may be less than the value which is set. The power-on default value is 100 kHz. """ ret = api.py_aa_i2c_bitrate(self.handle, 0) _raise...
python
def reverse_search_history(event): """ Search backward starting at the current line and moving `up` through the history as necessary. This is an incremental search. """ event.cli.current_search_state.direction = IncrementalSearchDirection.BACKWARD event.cli.push_focus(SEARCH_BUFFER)
java
public Predicate newPredicate(Span<Term> span) { String newId = idManager.getNextId(AnnotationType.PREDICATE); Predicate newPredicate = new Predicate(newId, span); annotationContainer.add(newPredicate, Layer.SRL, AnnotationType.PREDICATE); return newPredicate; }
python
def get_extra_commands(): """Use the configuration to discover additional CLI packages to load""" from ambry.run import find_config_file from ambry.dbexceptions import ConfigurationError from ambry.util import yaml try: plugins_dir = find_config_file('cli.yaml') except ConfigurationErro...
java
public static Path sourcePathFromParityPath(Path parityPath, FileSystem fs) throws IOException { String parityPathStr = parityPath.toUri().getPath(); for (Codec codec : Codec.getCodecs()) { String prefix = codec.getParityPrefix(); if (parityPathStr.startsWith(prefix)) { // Remove th...
java
private static void mapToWriter(Map<?, ?> map, JsonWriter writer) throws IOException { writer.beginObject(); for (Map.Entry<?, ?> entry : map.entrySet()) { writer.name(String.valueOf(entry.getKey())); writeValue(entry.getValue(), writer); } writer.endObject(); }
python
def _handle_api_error(self, error): """ New Relic cheerfully provides expected API error codes depending on your API call deficiencies so we convert these to exceptions and raise them for the user to handle as they see fit. """ status_code = error.response.status_code ...
java
@SuppressWarnings("ChainOfInstanceofChecks") private CellInfo fromCellLocation(CellLocation cellLocation) { try { if (cellLocation instanceof GsmCellLocation) { GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation; CellIdentityGsm identity = CellIdenti...
java
public <RESP extends J4pResponse<REQ>, REQ extends J4pRequest> List<RESP> execute(List<REQ> pRequests) throws J4pException { return this.<RESP, REQ>execute(pRequests, null); }
python
def getWidth(self): """ Get the width of the text output for the table. @rtype: int @return: Width in characters for the text output, including the newline character. """ width = 0 if self.__width: width = sum( abs(x) for x in self.__widt...
python
def load(self, file=CONFIG_FILE): """ load a configuration file. loads default config if file is not found """ if not os.path.exists(file): print("Config file was not found under %s. Default file has been created" % CONFIG_FILE) self._settings = yaml.load(DEFAULT_...
python
def verify(jwsjs): """Return (decoded headers, payload) if all signatures in jwsjs are consistent, else raise ValueError. Caller must decide whether the keys are actually trusted.""" get_ed25519ll() # XXX forbid duplicate keys in JSON input using object_pairs_hook (2.7+) recipients = jwsjs["rec...
python
def separate(string): """ Separate a string into smaller parts: first consonant (or head), vowel, last consonant (if any). >>> separate('tuong') ['t','uo','ng'] >>> separate('ohmyfkinggod') ['ohmyfkingg','o','d'] """ def atomic_separate(string, last_chars, last_is_vowel): if...
java
private final void setInMemoryItemSize(AbstractItem item) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setInMemoryItemSize", item); // If we have an Item, we can ask it for its estimated size. if (item != null) { _inMemoryI...
python
def get_open_orders(self, market=None): """ Get all orders that you currently have opened. A specific market can be requested. Endpoint: 1.1 /market/getopenorders 2.0 /key/market/getopenorders :param market: String literal for the market (ie. BTC-LTC) :t...
python
def get_mor_by_moid(si, obj_type, obj_moid): ''' Get reference to an object of specified object type and id si ServiceInstance for the vSphere or ESXi server (see get_service_instance) obj_type Type of the object (vim.StoragePod, vim.Datastore, etc) obj_moid ID of the obje...
python
def process_resource(self, req, resp, resource): """ Process the request after routing. The resource is required to determine if a model based resource is being used for validations so skip processing if no `resource.model` attribute is present. """ try: mod...
java
public static Node getParentOfNode(Node node) throws RuntimeException { Node parent; short nodeType = node.getNodeType(); if (Node.ATTRIBUTE_NODE == nodeType) { Document doc = node.getOwnerDocument(); /* TBD: if(null == doc) { throw new RuntimeException(XSLMe...
java
public static void printProgress(char showChar, int totalLen, double rate) { Assert.isTrue(rate >= 0 && rate <= 1, "Rate must between 0 and 1 (both include)"); printProgress(showChar, (int) (totalLen * rate)); }
python
def plot(self, **kwargs): """ Produce a pretty-plot of the estimate. """ set_kwargs_drawstyle(kwargs, "default") return _plot_estimate( self, estimate=getattr(self, self._estimate_name), confidence_intervals=self.confidence_interval_, **kwargs )
java
@Override public HttpFilterBuilder addFilter(RequestFilter<HttpRequest> filter) { return httpFilterChainBuilder.addFilter(new NotHttpRequestFilter(filter)); }
java
public static GetSignedUrlTaskParameters deserialize(String taskParameters) { JaxbJsonSerializer<GetSignedUrlTaskParameters> serializer = new JaxbJsonSerializer<>(GetSignedUrlTaskParameters.class); try { GetSignedUrlTaskParameters params = serializer.deserialize(t...
java
@SuppressWarnings("deprecation") private ResourceBundle findResourceBundle(Object o) { ResourceBundle result = null; Parameters p = o.getClass().getAnnotation(Parameters.class); if (p != null && ! isEmpty(p.resourceBundle())) { result = ResourceBundle.getBundle(p.resourceBundle(), Locale.getDefault...
python
def find_path(self, start, end, grid): """ find a path from start to end node on grid using the A* algorithm :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return: """ self.start_time = time...
python
def BadResponse(body, request, status_code=None, headers=None): """ Construct a Bad HTTP response (defined in DEFAULT_BAD_RESPONSE_CODE) :param body: The body of the response :type body: ``str`` :param request: The HTTP request :type request: :clas...
java
private IBlockIconProvider getWallIconProvider() { return (state, side) -> { if (side == EnumFacing.SOUTH || (side == EnumFacing.WEST && WallComponent.isCorner(state))) return insideIcon; return defaultIcon; }; }
java
private int sectionToWire(DNSOutput out, int section, Compression c, int maxLength) { int n = sections[section].size(); int pos = out.current(); int rendered = 0; Record lastrec = null; for (int i = 0; i < n; i++) { Record rec = (Record)sections[section].get(i); if (lastrec != null && !sameSet(rec, las...
python
def binary(self): """Return the name of the build.""" def _get_binary(): # Retrieve all entries from the remote virtual folder parser = self._create_directory_parser(self.path) if not parser.entries: raise errors.NotFoundError('No entries found', self....
python
def get_ptrm_dec_and_inc(self): """not included in spd.""" PTRMS = self.PTRMS[1:] CART_pTRMS_orig = numpy.array([lib_direct.dir2cart(row[1:4]) for row in PTRMS]) #B_lab_dir = [self.B_lab_dir[0], self.B_lab_dir[1], 1.] # dir tmin, tmax = self.t_Arai[0], self.t_Arai[-1] ptr...
python
def trimNs(seq, line, newagp): """ Test if the sequences contain dangling N's on both sides. This component needs to be adjusted to the 'actual' sequence range. """ start, end = line.component_beg, line.component_end size = end - start + 1 leftNs, rightNs = 0, 0 lid, lo = line.component_...
python
def get_tags(self, rev=None): """ Return the tags for the current revision as a set """ rev = rev or 'HEAD' return set(self._invoke('tag', '--points-at', rev).splitlines())
python
def _is_ipv4(self, ip): """ Return true if given arg is a valid IPv4 address """ try: p = IPy.IP(ip) except ValueError: return False if p.version() == 4: return True return False
java
public static String encodeUTF8(String chars) { try { return URLEncoder.encode(chars, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); // thanks JDK 1.4 } }
python
def priority_sort(list_, priority): r""" Args: list_ (list): priority (list): desired order of items Returns: list: reordered_list CommandLine: python -m utool.util_list --test-priority_argsort Example: >>> # ENABLE_DOCTEST >>> from utool.util_list ...
python
def get_primary_domain(self): """ Returns the primary domain of the tenant """ try: domain = self.domains.get(is_primary=True) return domain except get_tenant_domain_model().DoesNotExist: return None
java
public NotificationChain basicSetName(JvmParameterizedTypeReference newName, NotificationChain msgs) { JvmParameterizedTypeReference oldName = name; name = newName; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SarlPackage.SARL_BEHAVIOR_UNIT__N...
python
def banner(text, border='=', width=80): """Center _text_ in a banner _width_ wide with _border_ characters. Args: text (str): What to write in the banner border (str): Border character width (int): How long the border should be """ text_padding = '{0:^%d}' % (width) LOG.info...
java
public static Map<String, String> getVariableMapByPrefix( final Collection<Variable> variables, final String prefix) { final Map<String, String> shortlistMap = new HashMap<>(); if (variables != null && prefix != null) { for (final Variable var : getVariablesByRegex(variables, Reportal.REPO...
java
private boolean bfsComparison(Node root, Node other) { if(root instanceof Content || other instanceof Content) { return root.equals(other); } if(! root.equals(other)) { return false; } List<Node> a = ((Element)root).getChildElements(); List<Node> ...
python
def try_storage(self, identifier, req, resp, resource, uri_kwargs): """Try to find user in configured user storage object. Args: identifier: User identifier. Returns: user object. """ if identifier is None: user = None # note: if use...
java
public OtpMsg receiveMsg() throws IOException, OtpErlangExit, OtpAuthException { final Object o = queue.get(); if (o instanceof OtpMsg) { return (OtpMsg) o; } else if (o instanceof IOException) { throw (IOException) o; } else if (o instanceof OtpErlan...
java
public Observable<ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner> beginListRoutesTableSummaryAsync(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { return beginListRoutesTableSummaryWithServiceResponseAsync(resourceGroupName, crossConnectionName, peer...
python
def await_connection(host, port): """Wait for the mongo-orchestration server to accept connections.""" for i in range(CONNECT_ATTEMPTS): try: conn = socket.create_connection((host, port), CONNECT_TIMEOUT) conn.close() return True except (IOError, socket.error)...
python
def Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1): r'''Calculates two-phase pressure drop with the Friedel correlation. .. math:: \Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}} .. math:: H = \...
java
public void addFilterAfter(IRuleFilter filter, Class<? extends IRuleFilter> afterFilter) { int index = getIndexOfClass(filters, afterFilter); if (index == -1) { throw new FilterAddException("filter " + afterFilter.getSimpleName() + " has not been added"); } filters.add(index ...
python
def list_exchanges_for_vhost(self, vhost): """ A list of all exchanges in a given virtual host. :param vhost: The vhost name :type vhost: str """ return self._api_get('/api/exchanges/{0}'.format( urllib.parse.quote_plus(vhost) ))
python
def logged_insert(self, user): """Create and insert the document and log the event in the change log""" # Insert the frame's document self.insert() # Log the insert entry = ChangeLogEntry({ 'type': 'ADDED', 'documents': [self], 'user': user ...
python
def distinct(expr, on=None, *ons): """ Get collection with duplicate rows removed, optionally only considering certain columns :param expr: collection :param on: sequence or sequences :return: dinstinct collection :Example: >>> df.distinct(['name', 'id']) >>> df['name', 'id'].distinct...
java
public void init(BaseSession parentSessionObject, Record record, Map<String, Object> objectID) { if (m_application == null) m_application = new MainApplication(null, null, null); this.addToApplication(); super.init(parentSessionObject, record, objectID); }
python
def SetCoreGRRKnowledgeBaseValues(kb, client_obj): """Set core values from GRR into the knowledgebase.""" client_schema = client_obj.Schema kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, "")) if not kb.fqdn: kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, "")) versions...
python
def get_machine_category_usage(start, end): """Return a tuple of cpu hours and number of jobs for a given period Keyword arguments: start -- start date end -- end date """ cache = MachineCategoryCache.objects.get( date=datetime.date.today(), start=start, end=end) retur...
java
public static sslcipher[] get(nitro_service service, String ciphergroupname[]) throws Exception{ if (ciphergroupname !=null && ciphergroupname.length>0) { sslcipher response[] = new sslcipher[ciphergroupname.length]; sslcipher obj[] = new sslcipher[ciphergroupname.length]; for (int i=0;i<ciphergroupname.leng...
python
def _store_result(self, task_id, result, status, traceback=None, request=None): """Store return value and status of an executed task.""" self.TaskModel._default_manager.store_result( task_id, result, status, traceback=traceback, children=self.current_task_ch...
java
public int[] executeBatchPreparedStatement(String statement, Collection inParamsBatch) throws SQLException { return executeBatchPreparedStatement(statement, inParamsBatch, true); }
java
public void marshall(CreateWorkteamRequest createWorkteamRequest, ProtocolMarshaller protocolMarshaller) { if (createWorkteamRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createWorkteamRe...
java
public static <E> void marshallCollection(Collection<E> collection, ObjectOutput out) throws IOException { marshallCollection(collection, out, ObjectOutput::writeObject); }
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case XbasePackage.XPOSTFIX_OPERATION__OPERAND: return operand != null; } return super.eIsSet(featureID); }
python
def getTaskInfos(self): """ .. note:: Experimental Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage, ordered by partition ID. .. versionadded:: 2.4.0 """ if self._port is None or self._secret is None: raise Exception("Not supporte...
python
def visit_ifexp(self, node): """return an astroid.IfExp node as string""" return "%s if %s else %s" % ( self._precedence_parens(node, node.body, is_left=True), self._precedence_parens(node, node.test, is_left=True), self._precedence_parens(node, node.orelse, is_left=F...
python
def _pretend_to_run(self, migration, method): """ Pretend to run the migration. :param migration: The migration :type migration: orator.migrations.migration.Migration :param method: The method to execute :type method: str """ self._note("") names...
python
def detachRequest(GmmCause_presence=0): """DETACH REQUEST Section 9.4.5""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndForceToStandby() packet = a / b / c if GmmCause_presence is 1: e = GmmCause(ieiGC=0x25) packet = packet / e return packet
python
def _send(self, messages): """A helper method that does the actual sending.""" if len(messages) == 1: to_send = self._build_message(messages[0]) if to_send is False: # The message was missing recipients. # Bail. return False ...
python
def __sort_toplevel_items(self): """ Sort the root file items in alphabetical order if 'sort_files_alphabetically' is True, else order the items as specified in the 'self.ordered_editor_ids' list. """ if self.show_all_files is False: return c...
java
public static void vertical(GrayS16 input, GrayI16 output, int radius, @Nullable IWorkArrays work) { InputSanityCheck.checkSameShape(input , output); Kernel1D_S32 kernel = FactoryKernel.table1D_I32(radius); ConvolveJustBorder_General_SB.vertical(kernel,ImageBorderValue.wrap(input,0),output); if(BoofConcurrency...
python
def init_process(self) -> None: """ GunicornWorker 初始化回调 """ default_loop = asyncio.get_event_loop() if default_loop.is_running(): default_loop.close() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) else: ...
python
def send(self, group_id=None, message_dict=None): """ Send this current message to a group. `message_dict` can be a dictionary formatted according to http://docs.fiesta.cc/list-management-api.html#messages If message is provided, this method will ignore object-level variables. "...
python
def set_formatter(log_formatter): """Override the default log formatter with your own.""" # Add our formatter to all the handlers root_logger = logging.getLogger() for handler in root_logger.handlers: handler.setFormatter(logging.Formatter(log_formatter))
java
public static void optimizeGraphicsSpeed(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED); g.setRenderingHint(RenderingHints....
java
public String getNewNodeIdIfUnavailable( final String nodeId ) { final String newNodeId; if ( nodeId == null ) { newNodeId = getMemcachedNodeId(); } else { if ( !isNodeAvailable( nodeId ) ) { newNodeId = getAvailableNodeId( nodeId ); ...
java
@Override public UpdateRadiusResult updateRadius(UpdateRadiusRequest request) { request = beforeClientExecution(request); return executeUpdateRadius(request); }
java
public static String expand(String keyString, Properties properties) { return PropertyUtil.expand(keyString, (Map) properties); }
java
public static void computeAutoGeneratedAxisValues(float start, float stop, int steps, AxisAutoValues outValues) { double range = stop - start; if (steps == 0 || range <= 0) { outValues.values = new float[]{}; outValues.valuesNumber = 0; return; } doub...
python
def array(data, **kwargs): """Create an array filled with `data`. The `data` argument should be a NumPy array or array-like object. For other parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import numpy as np >>> import zarr >>> a = np.arange(100000000).re...
java
public static Seconds from(TemporalAmount amount) { if (amount instanceof Seconds) { return (Seconds) amount; } Objects.requireNonNull(amount, "amount"); int seconds = 0; for (TemporalUnit unit : amount.getUnits()) { long value = amount.get(unit); ...
java
private void generateEdges(StringBuilder result, TextInBox parent) { if (!getTree().isLeaf(parent)) { Rectangle2D.Double b1 = getBoundsOfNode(parent); double x1 = b1.getCenterX(); double y1 = b1.getCenterY(); for (TextInBox child : getChildren(parent)) { Rectangle2D.Double b2 = getBoundsOfNode(child);...
python
def sentence(self, padding=75): """ Get sentence """ vec = word_to_vector(self.sentence_str) vec += [-1] * (padding - self.sentence_length) return np.array(vec, dtype=np.int32)
java
public ListUsersResult withUserList(User... userList) { if (this.userList == null) { setUserList(new java.util.ArrayList<User>(userList.length)); } for (User ele : userList) { this.userList.add(ele); } return this; }
java
public ObjectAccessor<T> getDefaultValuesAccessor(TypeTag enclosingType, Set<String> nonnullFields, AnnotationCache annotationCache) { ObjectAccessor<T> result = buildObjectAccessor(); for (Field field : FieldIterable.of(type)) { if (NonnullAnnotationVerifier.fieldIsNonnull(field, annotation...
java
@Override public Resource getErrorpage(SlingHttpServletRequest request, int status) { Resource errorpage = null; ResourceResolver resolver = request.getResourceResolver(); if (StringUtils.isNotBlank(errorpagesPath)) { if (errorpagesPath.startsWith("/")) { // if t...
java
@FFDCIgnore(value = { InterruptedException.class }) public void checkinClient(Client client) { boolean done = false; //If no more space. Return. Shouldn't be checking more than we have. Shouldn't happen besides unit test anyways. if (clients.remainingCapacity() == 0) { if (Trace...
java
public final void synpred25_InternalSARL_fragment() throws RecognitionException { // InternalSARL.g:11564:7: ( ( ( ( ruleValidID ) ) '=' ) ) // InternalSARL.g:11564:8: ( ( ( ruleValidID ) ) '=' ) { // InternalSARL.g:11564:8: ( ( ( ruleValidID ) ) '=' ) // InternalSARL.g:11565:...
python
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Orographic Gage File Read from File Method """ # Set file extension property self.fileExtension = extension # Open file and parse into HmetRecords ...
python
def _debug_dump_dom(el): """Debugging helper. Prints out `el` contents.""" import xml.dom.minidom s = [el.nodeName] att_container = el.attributes for i in range(att_container.length): attr = att_container.item(i) s.append(' @{a}="{v}"'.format(a=attr.name, v=attr.value)) for c in...
java
public synchronized void start() { Preconditions.checkState(mProcess == null, "Master is already running"); LOG.info("Starting master with port {}", mProperties.get(PropertyKey.MASTER_RPC_PORT)); mProcess = new ExternalProcess(mProperties, LimitedLifeMasterProcess.class, new File(mLogsDir, "master.o...
python
def get_task_positions_objs(client, list_id): ''' Gets a list containing the object that encapsulates information about the order lists are laid out in. This list will always contain exactly one object. See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: A ...
python
def toxml(self): """ Exports this object into a LEMS XML object """ return '<StateVariable name="{0}" dimension="{1}"'.format(self.name, self.dimension) +\ (' exposure="{0}"'.format(self.exposure) if self.exposure else '') +\ '/>'
java
private static Name checkNotReserved(Name name, String action) { if (isReserved(name)) { throw new IllegalArgumentException("cannot " + action + ": " + name); } return name; }
java
public <T> T get(Class<T> targetClass) { try { return doGet(targetClass); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } }
java
private void writeResultsToFile(ValidationPlanResult planResult) throws IOException { /** * first set any report messages (probably exceptional that the * translation report needs to get set outside the embl-api-core package * due to the need for embl-ff writers **/ for (ValidationResult result : plan...
java
public void addVariantDatasetMetadata(VariantStudyMetadata variantStudyMetadata) { if (variantStudyMetadata != null) { VariantStudyMetadata found = getVariantStudyMetadata(variantStudyMetadata.getId()); // if there is not any study with that ID then we add the new one // TODO...
python
def _dt_to_epoch(dt): """Convert datetime to epoch seconds.""" try: epoch = dt.timestamp() except AttributeError: # py2 epoch = (dt - datetime(1970, 1, 1)).total_seconds() return epoch
java
public static void repeat(char c, int count, StringBuilder sb) { for (int i = 0; i < count; i++) { sb.append(c); } }
python
def getLinkInfo(self, wanInterfaceId=1, timeout=1): """Execute GetInfo action to get basic WAN link information's. :param int wanInterfaceId: the id of the WAN device :param float timeout: the timeout to wait for the action to be executed :return: basic WAN link information's :r...