language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private int getValueAccordingBoundaries(final int value) { // check boundaries final int newValue; if (value < 0) { newValue = 0; } else if (value > getMaxValue()) { newValue = getMaxValue(); } else { newValue = value; } return newValue; }
python
def _find_unpurge_targets(desired, **kwargs): ''' Find packages which are marked to be purged but can't yet be removed because they are dependencies for other installed packages. These are the packages which will need to be 'unpurged' because they are part of pkg.installed states. This really just applies to Debian-based Linuxes. ''' return [ x for x in desired if x in __salt__['pkg.list_pkgs'](purge_desired=True, **kwargs) ]
python
def cells(self): """The number of cells in the MOC. This gives the total number of cells at all orders, with cells from every order counted equally. >>> m = MOC(0, (1, 2)) >>> m.cells 2 """ n = 0 for (order, cells) in self: n += len(cells) return n
python
def _get_users_of_group(config, group): """ Utility to query fas for users of a group. """ if not group: return set() fas = fmn.rules.utils.get_fas(config) return fmn.rules.utils.get_user_of_group(config, fas, group)
java
public void processResetRequestAck(long dmeVersion, SendDispatcher sendDispatcher) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "processResetRequestAck", Long.valueOf(dmeVersion)); // Only consider non-stale request acks if (dmeVersion >= _latestDMEVersion) { if (dmeVersion > _latestDMEVersion) _latestDMEVersion = dmeVersion; _slowedGetTOM.applyToEachEntry(new AddToEagerTOM(_slowedGetTOM, dmeVersion)); sendDispatcher.sendResetRequestAckAck(dmeVersion); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "processResetRequestAck"); }
java
public static Component createDropDown(FontIcon icon, Component content, String title) { return createDropDown(getDropDownButtonHtml(icon), content, title); }
java
public static void appendPath(StringBuilder buffer, String... segments) { for (int i = 0; i < segments.length; i++) { String s = segments[i]; if (i > 0) { buffer.append(SEPARATOR); } buffer.append(s); } }
java
synchronized boolean processHeartbeat( TaskTrackerStatus trackerStatus, boolean initialContact) { String trackerName = trackerStatus.getTrackerName(); synchronized (taskTrackers) { synchronized (trackerExpiryQueue) { boolean seenBefore = updateTaskTrackerStatus(trackerName, trackerStatus); TaskTracker taskTracker = getTaskTracker(trackerName); if (initialContact) { // If it's first contact, then clear out // any state hanging around if (seenBefore) { LOG.warn("initialContact but seenBefore from Tracker : " + trackerName); lostTaskTracker(taskTracker); } } else { // If not first contact, there should be some record of the tracker if (!seenBefore) { LOG.warn("Status from unknown Tracker : " + trackerName); updateTaskTrackerStatus(trackerName, null); return false; } } if (initialContact) { // if this is lost tracker that came back now, and if it blacklisted // increment the count of blacklisted trackers in the cluster if (isBlacklisted(trackerName)) { faultyTrackers.incrBlackListedTrackers(1); } addNewTracker(taskTracker); } } } updateTaskStatuses(trackerStatus); updateNodeHealthStatus(trackerStatus); return true; }
java
public static PluginManager getInstance() { if (_instance == null) { _instance = new PluginManager(); _instance.classInformation = new HashMap<String, ClassInformation>(); _instance.methodInformation = new HashMap<String, com.groupon.odo.proxylib.models.Method>(); _instance.jarInformation = new ArrayList<String>(); if (_instance.proxyLibPath == null) { //Get the System Classloader ClassLoader sysClassLoader = Thread.currentThread().getContextClassLoader(); //Get the URLs URL[] urls = ((URLClassLoader) sysClassLoader).getURLs(); for (int i = 0; i < urls.length; i++) { if (urls[i].getFile().contains("proxylib")) { // store the path to the proxylib _instance.proxyLibPath = urls[i].getFile(); break; } } } _instance.initializePlugins(); } return _instance; }
java
public String[] getPinyinFromChar(char c) { String s = Integer.toHexString(c).toUpperCase(); return tables.get(s); }
java
public void setTrackLocation( RectangleLength2D_I32 location ) { this.location.set(location); // massage the rectangle so that it has an odd width and height // otherwise it could experience a bias when localizing this.location.width += 1- this.location.width%2; this.location.height += 1- this.location.height%2; failed = false; }
python
def diff_to_new_interesting_lines(unified_diff_lines: List[str] ) -> Dict[int, str]: """ Extracts a set of 'interesting' lines out of a GNU unified diff format. Format: gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html @@ from-line-numbers to-line-numbers @@ line-from-either-file ... @@ start,count start,count @@ line-from-either-file ... @@ single start,count @@ line-from-either-file ... Examples: Deleted line (5 is the deleted LOC, 7 is the guessed would-have-been loc in the updated file given other changes pushing the line around): @@ 5 7,0 @@ - content-of-line Added line: @@ 5,0 7 @@ + content-of-line Modified chunk: @@ 10,15 11,5 @@ - removed-line + added-line ... Args: unified_diff_lines: Lines of output from git diff. Returns: A dictionary of "touched lines", with key equal to the line number and value equal to the reason the line was touched. Includes added lines and lines near changes (including removals). """ interesting_lines = dict() for diff_line in unified_diff_lines: # Parse the 'new file' range parts of the unified diff. if not diff_line.startswith('@@ '): continue change = diff_line[3:diff_line.index(' @@', 3)] new = change.split(' ')[1] start = int(new.split(',')[0]) count = 1 if ',' not in new else int(new.split(',')[1]) # The lines before and after a deletion should still be covered. if count == 0: for i in range(start, start + 2): interesting_lines[i] = 'is near a removal' else: for i in range(start, start + count): interesting_lines[i] = 'is new or changed' return interesting_lines
java
public static FigShareClient to(String endpoint, int version, String clientKey, String clientSecret, String tokenKey, String tokenSecret) { return new FigShareClient(endpoint, version, clientKey, clientSecret, tokenKey, tokenSecret); }
java
public final void mJavaLetter() throws RecognitionException { try { // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1379:2: ( ( 'a' .. 'z' | 'A' .. 'Z' | '$' | '_' ) |{...}?~ ( '\\u0000' .. '\\u007F' | '\\uD800' .. '\\uDBFF' ) |{...}? ( '\\uD800' .. '\\uDBFF' ) ( '\\uDC00' .. '\\uDFFF' ) ) int alt27=3; int LA27_0 = input.LA(1); if ( (LA27_0=='$'||(LA27_0 >= 'A' && LA27_0 <= 'Z')||LA27_0=='_'||(LA27_0 >= 'a' && LA27_0 <= 'z')) ) { alt27=1; } else if ( ((LA27_0 >= '\u0080' && LA27_0 <= '\uD7FF')||(LA27_0 >= '\uDC00' && LA27_0 <= '\uFFFF')) ) { alt27=2; } else if ( ((LA27_0 >= '\uD800' && LA27_0 <= '\uDBFF')) ) { alt27=3; } else { NoViableAltException nvae = new NoViableAltException("", 27, 0, input); throw nvae; } switch (alt27) { case 1 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1379:4: ( 'a' .. 'z' | 'A' .. 'Z' | '$' | '_' ) { if ( input.LA(1)=='$'||(input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 2 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1380:6: {...}?~ ( '\\u0000' .. '\\u007F' | '\\uD800' .. '\\uDBFF' ) { if ( !((Character.isJavaIdentifierStart(input.LA(1)))) ) { throw new FailedPredicateException(input, "JavaLetter", "Character.isJavaIdentifierStart(input.LA(1))"); } if ( (input.LA(1) >= '\u0080' && input.LA(1) <= '\uD7FF')||(input.LA(1) >= '\uDC00' && input.LA(1) <= '\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; case 3 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1382:9: {...}? ( '\\uD800' .. '\\uDBFF' ) ( '\\uDC00' .. '\\uDFFF' ) { if ( !((Character.isJavaIdentifierStart(Character.toCodePoint((char)input.LA(-1), (char)input.LA(1))))) ) { throw new FailedPredicateException(input, "JavaLetter", "Character.isJavaIdentifierStart(Character.toCodePoint((char)input.LA(-1), (char)input.LA(1)))"); } if ( (input.LA(1) >= '\uD800' && input.LA(1) <= '\uDBFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } if ( (input.LA(1) >= '\uDC00' && input.LA(1) <= '\uDFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse; } } break; } } finally { // do for sure before leaving } }
python
def from_arrays(cls, arrays, name=None, **kwargs): """Creates a new instance of self from the given (list of) array(s). This is done by calling numpy.rec.fromarrays on the given arrays with the given kwargs. The type of the returned array is cast to this class, and the name (if provided) is set. Parameters ---------- arrays : (list of) numpy array(s) A list of the arrays to create the FieldArray from. name : {None|str} What the output array should be named. For other keyword parameters, see the numpy.rec.fromarrays help. Returns ------- array : instance of this class An array that is an instance of this class in which the field data is from the given array(s). """ obj = numpy.rec.fromarrays(arrays, **kwargs).view(type=cls) obj.name = name return obj
java
public Element appendToXml(Element parentNode, List<String> parametersToIgnore) { for (Map.Entry<String, Serializable> entry : m_configurationObjects.entrySet()) { String name = entry.getKey(); // check if the parameter should be ignored if ((parametersToIgnore == null) || !parametersToIgnore.contains(name)) { // now serialize the parameter name and value Object value = entry.getValue(); if (value instanceof List) { @SuppressWarnings("unchecked") List<String> values = (List<String>)value; for (String strValue : values) { // use the original String as value Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } else { // use the original String as value String strValue = get(name); Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } } return parentNode; }
java
public void unsubscribeOrderbook(final BitfinexOrderBookSymbol symbol) { final UnsubscribeChannelCommand command = new UnsubscribeChannelCommand(symbol); client.sendCommand(command); }
python
def rgb(color,default=(0,0,0)): """ return rgb tuple for named color in rgb.txt or a hex color """ c = color.lower() if c[0:1] == '#' and len(c)==7: r,g,b = c[1:3], c[3:5], c[5:] r,g,b = [int(n, 16) for n in (r, g, b)] return (r,g,b) if c.find(' ')>-1: c = c.replace(' ','') if c.find('gray')>-1: c = c.replace('gray','grey') if c in x11_colors.keys(): return x11_colors[c] return default
java
@Override public boolean add(E e) { if (capacity <= linkedBlockingDeque.size()) linkedBlockingDeque.removeFirst(); return linkedBlockingDeque.add(e); }
java
public DynamoDBDeleteExpression withExpressionAttributeNames( java.util.Map<String, String> expressionAttributeNames) { setExpressionAttributeNames(expressionAttributeNames); return this; }
python
def get_current_executions(self): """Get all current running executions. :return: Returns a set of running Executions or empty list. :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + 'getCurrentExecutions', headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() self.get_current_executions() return try: result = request.json() except ValueError as error: raise Exception( "Not a valid result for" + "get_current_executions, protocol error: " + error) if 'executions' not in result.keys(): return None executions = [] for execution_data in result['executions']: exe = Execution(execution_data) executions.append(exe) return executions
java
public void clickInList(int line, int index, int id) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickInList("+line+", "+index+", " + id +")"); } clicker.clickInList(line, index, id, false, 0); }
python
def _delete_partition(self, tenant_id, tenant_name): """Function to delete a service partition. """ self.dcnm_obj.delete_partition(tenant_name, fw_const.SERV_PART_NAME)
python
def load(self, value): """Load the value of the DigitWord from a JSON representation of a list. The representation is validated to be a string and the encoded data a list. The list is then validated to ensure each digit is a valid digit""" if not isinstance(value, str): raise TypeError('Expected JSON string') _value = json.loads(value) self._validate_word(value=_value) self.word = _value
python
def complete_block(self): """Return code lines **with** bootstrap""" return "".join(line[SOURCE] for line in self._boot_lines + self._source_lines)
java
public int getScale(int column) throws SQLException { sourceResultSet.checkColumnBounds(column); VoltType type = sourceResultSet.table.getColumnType(column - 1); Integer result = type.getMaximumScale(); if (result == null) { result = 0; } return result; }
python
def _Close(self): """Closes the file-like object.""" super(VHDIFile, self)._Close() for vhdi_file in self._parent_vhdi_files: vhdi_file.close() for file_object in self._sub_file_objects: file_object.close() self._parent_vhdi_files = [] self._sub_file_objects = []
java
private static boolean nodeListsAreEqual(final NodeList a, final NodeList b) { if (a == b) { return true; } if ((a == null) || (b == null)) { return false; } if (a.getLength() != b.getLength()) { return false; } for (int i = 0; i < a.getLength(); ++i) { if (!nodesAreEqual(a.item(i), b.item(i))) { return false; } } return true; }
java
@Override public final void endElement(final String ns, final String lName, final String qName) throws SAXException { // the actual element name is either in lName or qName, depending // on whether the parser is namespace aware String name = lName == null || lName.length() == 0 ? qName : lName; // Fire "end" events for all relevant rules in reverse order Rule r = (Rule) RULES.match(match); if (r != null) { r.end(name); } // Recover the previous match expression int slash = match.lastIndexOf('/'); if (slash >= 0) { match = match.substring(0, slash); } else { match = ""; } }
python
def to_latex(self): """ Returns an interval representation """ if self.low == self.high: if self.low * 10 % 10 == 0: return "{0:d}".format(int(self.low)) else: return "{0:0.2f}".format(self.low) else: t = "" if self.low == -np.inf: t += r"(-\infty, " elif self.low * 10 % 10 == 0: t += r"[{0:d}, ".format(int(self.low)) else: t += r"[{0:0.2f}, ".format(self.low) if self.high == np.inf: t += r"\infty)" elif self.high * 10 % 10 == 0: t += r"{0:d}]".format(int(self.high)) else: t += r"{0:0.2f}]".format(self.high) return t
java
private static CSLName[] toAuthors(List<Map<String, Object>> authors) { CSLName[] result = new CSLName[authors.size()]; int i = 0; for (Map<String, Object> a : authors) { CSLNameBuilder builder = new CSLNameBuilder(); if (a.containsKey(FIELD_FIRSTNAME)) { builder.given(strOrNull(a.get(FIELD_FIRSTNAME))); } if (a.containsKey(FIELD_LASTNAME)) { builder.family(strOrNull(a.get(FIELD_LASTNAME))); } builder.parseNames(true); result[i] = builder.build(); ++i; } return result; }
python
def d2logpdf_dlink2(self, inv_link_f, y, Y_metadata=None): """ Hessian at y, given link(f), w.r.t link(f) i.e. second derivative logpdf at y given link(f_i) and link(f_j) w.r.t link(f_i) and link(f_j) The hessian will be 0 unless i == j .. math:: \\frac{d^{2} \\ln p(y_{i}|\lambda(f_{i}))}{d^{2}\\lambda(f)} = \\frac{(v+1)((y_{i}-\lambda(f_{i}))^{2} - \\sigma^{2}v)}{((y_{i}-\lambda(f_{i}))^{2} + \\sigma^{2}v)^{2}} :param inv_link_f: latent variables inv_link(f) :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: Y_metadata which is not used in student t distribution :returns: Diagonal of hessian matrix (second derivative of likelihood evaluated at points f) :rtype: Nx1 array .. Note:: Will return diagonal of hessian, since every where else it is 0, as the likelihood factorizes over cases (the distribution for y_i depends only on link(f_i) not on link(f_(j!=i)) """ e = y - inv_link_f hess = ((self.v + 1)*(e**2 - self.v*self.sigma2)) / ((self.sigma2*self.v + e**2)**2) return hess
python
def _resume_with_session_id( self, server_info: ServerConnectivityInfo, ssl_version_to_use: OpenSslVersionEnum ) -> bool: """Perform one session resumption using Session IDs. """ session1 = self._resume_ssl_session(server_info, ssl_version_to_use) try: # Recover the session ID session1_id = self._extract_session_id(session1) except IndexError: # Session ID not assigned return False if session1_id == '': # Session ID empty return False # Try to resume that SSL session session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1) try: # Recover the session ID session2_id = self._extract_session_id(session2) except IndexError: # Session ID not assigned return False # Finally, compare the two Session IDs if session1_id != session2_id: # Session ID assigned but not accepted return False return True
java
public static long readUnsignedIntegerLittleEndian(byte[] buffer, int offset) { long value; value = (buffer[offset] & 0xFF); value |= (buffer[offset + 1] & 0xFF) << 8; value |= (buffer[offset + 2] & 0xFF) << 16; value |= ((long)(buffer[offset + 3] & 0xFF)) << 24; return value; }
java
public static void writeOutSilent(Expression value, BytecodeContext bc, int mode) throws TransformerException { Position start = value.getStart(); Position end = value.getEnd(); value.setStart(null); value.setEnd(null); value.writeOut(bc, mode); value.setStart(start); value.setEnd(end); }
python
def parse_command_line_parameters(): """ Parses command line arguments """ usage = 'usage: %prog [options] fasta_filepath' version = 'Version: %prog 0.1' parser = OptionParser(usage=usage, version=version) # A binary 'verbose' flag parser.add_option('-p', '--is_protein', action='store_true', dest='is_protein', default=False, help='Pass if building db of protein sequences [default:' ' False, nucleotide db]') parser.add_option('-o', '--output_dir', action='store', type='string', dest='output_dir', default=None, help='the output directory [default: directory ' 'containing input fasta_filepath]') opts, args = parser.parse_args() num_args = 1 if len(args) != num_args: parser.error('Must provide single filepath to build database from.') return opts, args
python
def add_catalogue_cluster(self, catalogue, vcl, flagvector, cluster_id=None, overlay=True): """ Creates a plot of a catalogue showing where particular clusters exist """ # Create simple magnitude scaled point basemap self.add_size_scaled_points(catalogue.data['longitude'], catalogue.data['latitude'], catalogue.data['magnitude'], shape="o", alpha=0.8, colour=(0.5, 0.5, 0.5), smin=1.0, sscale=1.5, overlay=True) # If cluster ID is not specified just show mainshocks if cluster_id is None: idx = flagvector == 0 self.add_size_scaled_points(catalogue.data['longitude'][idx], catalogue.data['latitude'][idx], catalogue.data['magnitude'][idx], shape="o", colour="r", smin=1.0, sscale=1.5, overlay=overlay) return if not isinstance(cluster_id, collections.Iterable): cluster_id = [cluster_id] for iloc, clid in enumerate(cluster_id): if iloc == (len(cluster_id) - 1): # On last iteration set overlay to function overlay temp_overlay = overlay else: temp_overlay = True idx = vcl == clid self.add_size_scaled_points( catalogue.data["longitude"][idx], catalogue.data["latitude"][idx], catalogue.data["magnitude"][idx], shape="o", colour=DISSIMILAR_COLOURLIST[(iloc + 1) % NCOLS], smin=1.0, sscale=1.5, overlay=temp_overlay)
python
def parse_JSON(self, JSON_string): """ Parses a list of *UVIndex* instances out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: a list of *UVIndex* instances or an empty list if no data is available :raises: *ParseResponseError* if it is impossible to find or parse the data needed to build the result, *APIResponseError* if the JSON string embeds an HTTP status error """ if JSON_string is None: raise parse_response_error.ParseResponseError('JSON data is None') d = json.loads(JSON_string) uvindex_parser = UVIndexParser() return [uvindex_parser.parse_JSON(json.dumps(item)) for item in d]
java
@Override public EClass getIfcTextureVertexList() { if (ifcTextureVertexListEClass == null) { ifcTextureVertexListEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(721); } return ifcTextureVertexListEClass; }
java
public void setItem(java.util.Collection<EndpointBatchItem> item) { if (item == null) { this.item = null; return; } this.item = new java.util.ArrayList<EndpointBatchItem>(item); }
python
def delete(uuid): ''' Remove an installed image uuid : string Specifies uuid to import CLI Example: .. code-block:: bash salt '*' imgadm.delete e42f8c84-bbea-11e2-b920-078fab2aab1f ''' ret = {} cmd = 'imgadm delete {0}'.format(uuid) res = __salt__['cmd.run_all'](cmd, python_shell=False) retcode = res['retcode'] if retcode != 0: ret['Error'] = _exit_status(retcode) return ret # output: Deleted image d5b3865c-0804-11e5-be21-dbc4ce844ddc result = [] for image in res['stdout'].splitlines(): image = [var for var in image.split(" ") if var] result.append(image[2]) return result
python
def keyPressEvent(self, event): """ Qt override. """ if event.key() in [Qt.Key_Enter, Qt.Key_Return]: QTableWidget.keyPressEvent(self, event) # To avoid having to enter one final tab self.setDisabled(True) self.setDisabled(False) self._parent.keyPressEvent(event) else: QTableWidget.keyPressEvent(self, event)
java
public static String[] getByJNDI() { try { Class<?> dirContext = Class.forName("javax.naming.directory.DirContext"); Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); Class<?> initialDirContext = Class.forName("javax.naming.directory.InitialDirContext"); Constructor<?> constructor = initialDirContext.getConstructor(Hashtable.class); Object obj = constructor.newInstance(env); Method m = dirContext.getMethod("getEnvironment"); Hashtable newEnv = (Hashtable) m.invoke(obj); String dns = (String) newEnv.get("java.naming.provider.url"); String dnsTrim = dns.replace("dns://", ""); return dnsTrim.split(" "); } catch (Exception e) { e.printStackTrace(); } return null; }
java
byte[] decodeLikeAnEngineer(final byte[] input) { if (input == null) { throw new NullPointerException("input"); } if ((input.length & 0x01) == 0x01) { throw new IllegalArgumentException( "input.length(" + input.length + ") is not even"); } final byte[] output = new byte[input.length >> 1]; int index = 0; // index in input for (int i = 0; i < output.length; i++) { output[i] = (byte) ((decodeHalf(input[index++]) << 4) | decodeHalf(input[index++])); } return output; }
java
private static HyphenationPattern[] sortPatterns(HyphenationPattern[] patternArray) { Comparator<HyphenationPattern> comparator = new Comparator<HyphenationPattern>() { @Override public int compare(HyphenationPattern p1, HyphenationPattern p2) { return (p2.getWordPart().length() - p1.getWordPart().length()); } }; Arrays.sort(patternArray, comparator); return patternArray; }
java
public static String get(final String key, String def) { if (key == null) { throw new NullPointerException("key"); } if (key.isEmpty()) { throw new IllegalArgumentException("key must not be empty."); } String value = null; try { if (System.getSecurityManager() == null) { value = System.getProperty(key); } else { value = AccessController.doPrivileged(new PrivilegedAction<String>() { @Override public String run() { return System.getProperty(key); } }); } } catch (SecurityException e) { logger.warn("Unable to retrieve a system property '{}'; default values will be used.", key, e); } if (value == null) { return def; } return value; }
java
@Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { threadPoolController.resumeIfPaused(); return threadPool.invokeAll(interceptorsActive ? wrap(tasks) : tasks); }
java
public static ParameterizedAnalyticsQuery parameterized(final String statement, final JsonObject namedParams) { return new ParameterizedAnalyticsQuery(statement, null, namedParams, null); }
python
def generateImplicitParameters(cls, obj): """ Create PRODID, VERSION, and VTIMEZONEs if needed. VTIMEZONEs will need to exist whenever TZID parameters exist or when datetimes with tzinfo exist. """ for comp in obj.components(): if comp.behavior is not None: comp.behavior.generateImplicitParameters(comp) if not hasattr(obj, 'prodid'): obj.add(ContentLine('PRODID', [], PRODID)) if not hasattr(obj, 'version'): obj.add(ContentLine('VERSION', [], cls.versionString)) tzidsUsed = {} def findTzids(obj, table): if isinstance(obj, ContentLine) and (obj.behavior is None or not obj.behavior.forceUTC): if getattr(obj, 'tzid_param', None): table[obj.tzid_param] = 1 else: if type(obj.value) == list: for item in obj.value: tzinfo = getattr(obj.value, 'tzinfo', None) tzid = TimezoneComponent.registerTzinfo(tzinfo) if tzid: table[tzid] = 1 else: tzinfo = getattr(obj.value, 'tzinfo', None) tzid = TimezoneComponent.registerTzinfo(tzinfo) if tzid: table[tzid] = 1 for child in obj.getChildren(): if obj.name != 'VTIMEZONE': findTzids(child, table) findTzids(obj, tzidsUsed) oldtzids = [toUnicode(x.tzid.value) for x in getattr(obj, 'vtimezone_list', [])] for tzid in tzidsUsed.keys(): tzid = toUnicode(tzid) if tzid != u'UTC' and tzid not in oldtzids: obj.add(TimezoneComponent(tzinfo=getTzid(tzid)))
java
public void setDefaultTransactionIsolation(final int transactionIsolation) { if (Connection.TRANSACTION_READ_UNCOMMITTED == transactionIsolation || Connection.TRANSACTION_READ_COMMITTED == transactionIsolation || Connection.TRANSACTION_REPEATABLE_READ == transactionIsolation || Connection.TRANSACTION_SERIALIZABLE == transactionIsolation) { props.put(PROPS_TRANSACTION_ISOLATION, String.valueOf(transactionIsolation)); } else { throw new IllegalArgumentException("Unsupported level [" + transactionIsolation + "]"); } }
java
public String rtmpPublishUrl(String streamKey, int expireAfterSeconds) { long expire = System.currentTimeMillis() / 1000 + expireAfterSeconds; String path = String.format("/%s/%s?e=%d", hub, streamKey, expire); String token; try { token = auth.sign(path); } catch (Exception e) { e.printStackTrace(); return null; } return String.format("rtmp://%s%s&token=%s", rtmpPublishDomain, path, token); }
python
def ep(self, exc: Exception) -> bool: """Return False if the exception had not been handled gracefully""" if not isinstance(exc, ConnectionAbortedError): return False if len(exc.args) != 2: return False origin, reason = exc.args logging.getLogger(__name__).warning('Exited') return True
python
def set_text(self, x, y, text): """Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position """ col, row = get_pos(x, y) for i,c in enumerate(text): self.chars[row][col+i] = c
python
def add_bounding_box(self, color=None, corner_factor=0.5, line_width=None, opacity=1.0, render_lines_as_tubes=False, lighting=None, reset_camera=None, loc=None): """ Adds an unlabeled and unticked box at the boundaries of plot. Useful for when wanting to plot outer grids while still retaining all edges of the boundary. Parameters ---------- corner_factor : float, optional If ``all_edges``, this is the factor along each axis to draw the default box. Dafuault is 0.5 to show the full box. corner_factor : float, optional This is the factor along each axis to draw the default box. Dafuault is 0.5 to show the full box. line_width : float, optional Thickness of lines. opacity : float, optional Opacity of mesh. Should be between 0 and 1. Default 1.0 loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ kwargs = locals() _ = kwargs.pop('self') _ = kwargs.pop('loc') self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] return renderer.add_bounding_box(**kwargs)
java
protected static List<String> listDeliveryStreams() { ListDeliveryStreamsRequest listDeliveryStreamsRequest = new ListDeliveryStreamsRequest(); ListDeliveryStreamsResult listDeliveryStreamsResult = firehoseClient.listDeliveryStreams(listDeliveryStreamsRequest); List<String> deliveryStreamNames = listDeliveryStreamsResult.getDeliveryStreamNames(); while (listDeliveryStreamsResult.isHasMoreDeliveryStreams()) { if (deliveryStreamNames.size() > 0) { listDeliveryStreamsRequest.setExclusiveStartDeliveryStreamName(deliveryStreamNames.get(deliveryStreamNames.size() - 1)); } listDeliveryStreamsResult = firehoseClient.listDeliveryStreams(listDeliveryStreamsRequest); deliveryStreamNames.addAll(listDeliveryStreamsResult.getDeliveryStreamNames()); } return deliveryStreamNames; }
java
public static void main(String[] args) throws Exception { AdPerformanceConfig config = new AdPerformanceConfig(); config.parse(AdTrackingBenchmark.class.getName(), args); AdTrackingBenchmark benchmark = new AdTrackingBenchmark(config); benchmark.runBenchmark(); }
java
@Override public void write(ITuple key, NullWritable value) throws IOException { if(isClosing()) { throw new IOException("Index is already closing"); } heartBeater.needHeartBeat(); try { try { batch.add(converter.convert(key, value)); if(batch.size() > batchSize) { batchWriter.queueBatch(batch); batch.clear(); } } catch(SolrServerException e) { throw new IOException(e); } } finally { heartBeater.cancelHeartBeat(); } }
python
def split(mesh, only_watertight=True, adjacency=None, engine=None): """ Split a mesh into multiple meshes from face connectivity. If only_watertight is true, it will only return watertight meshes and will attempt single triangle/quad repairs. Parameters ---------- mesh: Trimesh only_watertight: if True, only return watertight components adjacency: (n,2) list of face adjacency to override using the plain adjacency calculated automatically. engine: str, which engine to use. ('networkx', 'scipy', or 'graphtool') Returns ---------- meshes: list of Trimesh objects """ if adjacency is None: adjacency = mesh.face_adjacency # if only watertight the shortest thing we can split has 3 triangles if only_watertight: min_len = 3 else: min_len = 1 components = connected_components(edges=adjacency, nodes=np.arange(len(mesh.faces)), min_len=min_len, engine=engine) meshes = mesh.submesh(components, only_watertight=only_watertight) return meshes
python
def _check_value(self, tag, value): """Ensure that the element matching C{tag} can have the given C{value}. @param tag: The tag to consider. @param value: The value to check @return: The unchanged L{value}, if valid. @raises L{WSDLParseError}: If the value is invalid. """ if value is None: if self._schema.children_min_occurs[tag] > 0: raise WSDLParseError("Missing tag '%s'" % tag) return value return value
python
def child(self, name): """ Create a new instance of this class derived from the current instance such that: (new.trace_id == current.trace_id and new.parent_span_id == current.span_id) The new L{Trace} instance will have a new unique span_id and if set the endpoint of the current L{Trace} object. @param name: C{str} name describing the new span represented by the new Trace object. @returns: L{Trace} """ trace = self.__class__( name, trace_id=self.trace_id, parent_span_id=self.span_id) trace.set_endpoint(self._endpoint) return trace
java
double getMarginValue(final double defaultMargin) { double margin = model.get(BasicSceneGenerator.Margin.class); if (margin == AUTOMATIC) margin = defaultMargin; return margin; }
python
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space via calculation of soft-bins over dihdral angle space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ x = [] for a in self.types: func = getattr(md, 'compute_%s' % a) _, y = func(traj) res = vm.pdf(y[..., np.newaxis], loc=self.loc, kappa=self.kappa) #we reshape the results using a Fortran-like index order, #so that it goes over the columns first. This should put the results #phi dihedrals(all bin0 then all bin1), psi dihedrals(all_bin1) x.extend(np.reshape(res, (1, -1, self.n_bins*y.shape[1]), order='F')) return np.hstack(x)
java
public void printInputControl(PrintWriter out, String strFieldDesc, String strFieldName, String strSize, String strMaxSize, String strValue, String strControlType, String strFieldType) { out.println(" <xfm:" + strControlType + " xform=\"form1\" ref=\"" + strFieldName + "\" cols=\"" + strSize + "\" type=\"" + strFieldType + "\">"); out.println(" <xfm:caption>" + strFieldDesc + "</xfm:caption>"); out.println(" </xfm:" + strControlType + ">"); }
java
@Override public void login(LoginCredential credential, LoginOpCall opLambda) throws LoginFailureException { doLogin(credential, createLoginOption(opLambda)); // exception if login failure }
java
public Set<String> getIdsForTermWithAncestors(String s) { if (!indexByName.containsKey(s)) return new HashSet<String>(); Stack<String> idsToConsider = new Stack<String>(); idsToConsider.addAll(getIdsForTerm(s)); Set<String> resultIds = new HashSet<String>(); while (!idsToConsider.isEmpty()) { String id = idsToConsider.pop(); if (!resultIds.contains(id)) { resultIds.add(id); idsToConsider.addAll(terms.get(id).getIsA()); } } return resultIds; }
java
public void addModalButton(final ToolbarModalAction modalAction) { final IButton button = new IButton(); button.setWidth(buttonSize); button.setHeight(buttonSize); button.setIconSize(buttonSize - WidgetLayout.toolbarStripHeight); button.setIcon(modalAction.getIcon()); button.setActionType(SelectionType.CHECKBOX); button.setRadioGroup(CONTROLLER_RADIO_GROUP); button.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { if (button.isSelected()) { if (currentModalAction != null) { currentModalAction.onDeselect(event); } modalAction.onSelect(event); currentModalAction = modalAction; } else { modalAction.onDeselect(event); currentModalAction = null; } } }); button.setShowRollOver(false); button.setShowFocused(true); button.setTooltip(modalAction.getTooltip()); button.setDisabled(modalAction.isDisabled()); if (getMembers() != null && getMembers().length > 0) { LayoutSpacer spacer = new LayoutSpacer(); spacer.setWidth(WidgetLayout.toolbarPadding); super.addMember(spacer); } modalAction.addToolbarActionHandler(new ToolbarActionHandler() { public void onToolbarActionDisabled(ToolbarActionDisabledEvent event) { button.setDisabled(true); } public void onToolbarActionEnabled(ToolbarActionEnabledEvent event) { button.setDisabled(false); } }); super.addMember(button); }
python
def connect_redis(redis_client, name=None, transaction=False): """ Connect your redis-py instance to redpipe. Example: .. code:: python redpipe.connect_redis(redis.StrictRedis(), name='users') Do this during your application bootstrapping. You can also pass a redis-py-cluster instance to this method. .. code:: python redpipe.connect_redis(rediscluster.StrictRedisCluster(), name='users') You are allowed to pass in either the strict or regular instance. .. code:: python redpipe.connect_redis(redis.StrictRedis(), name='a') redpipe.connect_redis(redis.Redis(), name='b') redpipe.connect_redis(rediscluster.StrictRedisCluster(...), name='c') redpipe.connect_redis(rediscluster.RedisCluster(...), name='d') :param redis_client: :param name: nickname you want to give to your connection. :param transaction: :return: """ return ConnectionManager.connect_redis( redis_client=redis_client, name=name, transaction=transaction)
java
public long roundHalfEven(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor < diffToCeiling) { // Closer to the floor - round floor return floor; } else if (diffToCeiling < diffFromFloor) { // Closer to the ceiling - round ceiling return ceiling; } else { // Round to the instant that makes this field even. If both values // make this field even (unlikely), favor the ceiling. if ((get(ceiling) & 1) == 0) { return ceiling; } return floor; } }
python
def getAll(self, event_name): """Gets all the events of a certain name that have been received so far. This is a non-blocking call. Args: callback_id: The id of the callback. event_name: string, the name of the event to get. Returns: A list of SnippetEvent, each representing an event from the Java side. """ raw_events = self._event_client.eventGetAll(self._id, event_name) return [snippet_event.from_dict(msg) for msg in raw_events]
python
def __set_web_authentication_detail(self): """ Sets up the WebAuthenticationDetail node. This is required for all requests. """ # Start of the authentication stuff. web_authentication_credential = self.client.factory.create('WebAuthenticationCredential') web_authentication_credential.Key = self.config_obj.key web_authentication_credential.Password = self.config_obj.password # Encapsulates the auth credentials. web_authentication_detail = self.client.factory.create('WebAuthenticationDetail') web_authentication_detail.UserCredential = web_authentication_credential # Set Default ParentCredential if hasattr(web_authentication_detail, 'ParentCredential'): web_authentication_detail.ParentCredential = web_authentication_credential self.WebAuthenticationDetail = web_authentication_detail
python
def _add_getter(self): """ Add a read-only ``{prop_name}`` property to the element class for this child element. """ property_ = property(self._getter, None, None) # assign unconditionally to overwrite element name definition setattr(self._element_cls, self._prop_name, property_)
python
def getBitmapFromRect(self, x, y, w, h): """ Capture the specified area of the (virtual) screen. """ min_x, min_y, screen_width, screen_height = self._getVirtualScreenRect() img = self._getVirtualScreenBitmap() # TODO # Limit the coordinates to the virtual screen # Then offset so 0,0 is the top left corner of the image # (Top left of virtual screen could be negative) x1 = min(max(min_x, x), min_x+screen_width) - min_x y1 = min(max(min_y, y), min_y+screen_height) - min_y x2 = min(max(min_x, x+w), min_x+screen_width) - min_x y2 = min(max(min_y, y+h), min_y+screen_height) - min_y return numpy.array(img.crop((x1, y1, x2, y2)))
python
def image(self, fname, group=None, scaled=None, dtype=None, idxexp=None, zoom=None, gray=None): """Get named image. Parameters ---------- fname : string Filename of image group : string or None, optional (default None) Name of image group scaled : bool or None, optional (default None) Flag indicating whether images should be on the range [0,...,255] with np.uint8 dtype (False), or on the range [0,...,1] with np.float32 dtype (True). If the value is None, scaling behaviour is determined by the `scaling` parameter passed to the object initializer, otherwise that selection is overridden. dtype : data-type or None, optional (default None) Desired data type of images. If `scaled` is True and `dtype` is an integer type, the output data type is np.float32. If the value is None, the data type is determined by the `dtype` parameter passed to the object initializer, otherwise that selection is overridden. idxexp : index expression or None, optional (default None) An index expression selecting, for example, a cropped region of the requested image. This selection is applied *before* any `zoom` rescaling so the expression does not need to be modified when the zoom factor is changed. zoom : float or None, optional (default None) Optional rescaling factor to apply to the images. If the value is None, support rescaling behaviour is determined by the `zoom` parameter passed to the object initializer, otherwise that selection is overridden. gray : bool or None, optional (default None) Flag indicating whether RGB images should be converted to grayscale. If the value is None, behaviour is determined by the `gray` parameter passed to the object initializer. Returns ------- img : ndarray Image array Raises ------ IOError If the image is not accessible """ if scaled is None: scaled = self.scaled if dtype is None: if self.dtype is None: dtype = np.uint8 else: dtype = self.dtype if scaled and np.issubdtype(dtype, np.integer): dtype = np.float32 if zoom is None: zoom = self.zoom if gray is None: gray = self.gray if group is None: pth = os.path.join(self.bpth, fname) else: pth = os.path.join(self.bpth, group, fname) try: img = np.asarray(imageio.imread(pth), dtype=dtype) except IOError: raise IOError('Could not access image %s in group %s' % (fname, group)) if scaled: img /= 255.0 if idxexp is not None: img = img[idxexp] if zoom is not None: if img.ndim == 2: img = sni.zoom(img, zoom) else: img = sni.zoom(img, (zoom,)*2 + (1,)*(img.ndim-2)) if gray: img = rgb2gray(img) return img
java
public static BoxResourceIterable<Info> getAllFileCollaborations(final BoxAPIConnection api, String fileID, int pageSize, String... fields) { QueryStringBuilder builder = new QueryStringBuilder(); if (fields.length > 0) { builder.appendParam("fields", fields); } return new BoxResourceIterable<BoxCollaboration.Info>( api, GET_ALL_FILE_COLLABORATIONS_URL.buildWithQuery(api.getBaseURL(), builder.toString(), fileID), pageSize) { @Override protected BoxCollaboration.Info factory(JsonObject jsonObject) { String id = jsonObject.get("id").asString(); return new BoxCollaboration(api, id).new Info(jsonObject); } }; }
python
def user_session_show(self, user_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/sessions#show-session" api_path = "/api/v2/users/{user_id}/sessions/{id}.json" api_path = api_path.format(user_id=user_id, id=id) return self.call(api_path, **kwargs)
python
def _on_error_page_write_error(self, status_code, **kwargs): """Replaces the default Tornado error page with a Django-styled one""" if oz.settings.get('debug'): exception_type, exception_value, tback = sys.exc_info() is_breakpoint = isinstance(exception_value, oz.error_pages.DebugBreakException) frames = oz.error_pages.get_frames(tback, is_breakpoint) frames.reverse() if is_breakpoint: exception_type = 'Debug breakpoint' exception_value = '' self.render(oz.settings["error_pages_template"], exception_type=exception_type, exception_value=exception_value, frames=frames, request_input=self.request.body, request_cookies=self.cookies, request_headers=self.request.headers, request_path=self.request.uri, request_method=self.request.method, response_output="".join(self._write_buffer), response_headers=self._headers, prettify_object=oz.error_pages.prettify_object, ) return oz.break_trigger
python
def _new_type(cls, args): """Creates a new class similar to namedtuple. Pass a list of field names or None for no field name. >>> x = ResultTuple._new_type([None, "bar"]) >>> x((1, 3)) ResultTuple(1, bar=3) """ fformat = ["%r" if f is None else "%s=%%r" % f for f in args] fformat = "(%s)" % ", ".join(fformat) class _ResultTuple(cls): __slots__ = () _fformat = fformat if args: for i, a in enumerate(args): if a is not None: vars()[a] = property(itemgetter(i)) del i, a return _ResultTuple
python
def get_table_list(self, cursor): """ Returns a list of table names in the current database and schema. """ cursor.execute(""" SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v', '') AND n.nspname = '%s' AND pg_catalog.pg_table_is_visible(c.oid)""" % self.connection.schema_name) return [TableInfo(row[0], {'r': 't', 'v': 'v'}.get(row[1])) for row in cursor.fetchall() if row[0] not in self.ignored_tables]
python
def GetHostMemPhysFreeMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysFreeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
python
def _CreateMethod(self, method_name): """Create a method wrapping an invocation to the SOAP service. Args: method_name: A string identifying the name of the SOAP method to call. Returns: A callable that can be used to make the desired SOAP request. """ soap_service_method = self.zeep_client.service[method_name] def MakeSoapRequest(*args): AddToUtilityRegistry('zeep') soap_headers = self._GetZeepFormattedSOAPHeaders() packed_args = self._PackArguments(method_name, args) try: return soap_service_method( *packed_args, _soapheaders=soap_headers)['body']['rval'] except zeep.exceptions.Fault as e: error_list = () if e.detail is not None: underlying_exception = e.detail.find( '{%s}ApiExceptionFault' % self._GetBindingNamespace()) fault_type = self.zeep_client.get_element( '{%s}ApiExceptionFault' % self._GetBindingNamespace()) fault = fault_type.parse( underlying_exception, self.zeep_client.wsdl.types) error_list = fault.errors or error_list raise googleads.errors.GoogleAdsServerFault( e.detail, errors=error_list, message=e.message) return MakeSoapRequest
java
private void doSubstitutions(NodeTraversal t, Config config, Node n) { if (n.isTaggedTemplateLit()) { // This is currently not supported, since tagged template literals have a different calling // convention than ordinary functions, so it's unclear which arguments are expected to be // replaced. Specifically, there are no direct string arguments, and for arbitrary tag // functions it's not clear that it's safe to inline any constant placeholders. compiler.report(JSError.make(n, STRING_REPLACEMENT_TAGGED_TEMPLATE)); return; } checkState(n.isNew() || n.isCall()); if (!config.isReplaceAll()) { // Note: the first child is the function, but the parameter id is 1 based. for (int parameter : config.parameters) { Node arg = n.getChildAtIndex(parameter); if (arg != null) { replaceExpression(t, arg, n); } } } else { // Replace all parameters. Node firstParam = n.getSecondChild(); for (Node arg = firstParam; arg != null; arg = arg.getNext()) { arg = replaceExpression(t, arg, n); } } }
java
static void waitForPipelineToFinish(PipelineResult result) { try { // Check to see if we are creating a template. // This should throw {@link UnsupportedOperationException} when creating a template. result.getState(); State state = result.waitUntilFinish(); LOG.info("Job finished with state: " + state.name()); if (state != State.DONE) { System.exit(1); } } catch (UnsupportedOperationException e) { LOG.warn("Unable to wait for pipeline to finish.", e); } }
python
def load(filename, compressed=True, prealloc=None): """ Loads a tensor from disk. """ # switch load based on file ext _, file_ext = os.path.splitext(filename) if compressed: if file_ext != COMPRESSED_TENSOR_EXT: raise ValueError('Can only load compressed tensor with %s extension' %(COMPRESSED_TENSOR_EXT)) data = np.load(filename)['arr_0'] else: if file_ext != TENSOR_EXT: raise ValueError('Can only load tensor with .npy extension') data = np.load(filename) # fill prealloc tensor if prealloc is not None: prealloc.reset() prealloc.add_batch(data) return prealloc # init new tensor tensor = Tensor(data.shape, data.dtype, data=data) return tensor
python
def asDictionary(self): """ returns the object as a python dictionary """ value = self._dict if value is None: template = { "hasM" : self._hasM, "hasZ" : self._hasZ, "rings" : [], "spatialReference" : self.spatialReference } for part in self._rings: lpart = [] for pt in part: if isinstance(pt, list): lpart.append(pt) elif isinstance(pt, Point): lpart.append(pt.asList) template['rings'].append(lpart) del lpart self._dict = template return self._dict
python
def groupby(self, dimensions, container_type=None, group_type=None, **kwargs): """Groups object by one or more dimensions Applies groupby operation over the specified dimensions returning an object of type container_type (expected to be dictionary-like) containing the groups. Args: dimensions: Dimension(s) to group by container_type: Type to cast group container to group_type: Type to cast each group to dynamic: Whether to return a DynamicMap **kwargs: Keyword arguments to pass to each group Returns: Returns object of supplied container_type containing the groups. If dynamic=True returns a DynamicMap instead. """ if self.ndims == 1: self.param.warning('Cannot split Map with only one dimension.') return self elif not isinstance(dimensions, list): dimensions = [dimensions] container_type = container_type if container_type else type(self) group_type = group_type if group_type else type(self) dimensions = [self.get_dimension(d, strict=True) for d in dimensions] with item_check(False): return util.ndmapping_groupby(self, dimensions, container_type, group_type, sort=True, **kwargs)
java
public static <T> Response call(RestUtils.RestCallable<T> callable, AlluxioConfiguration alluxioConf) { return call(callable, alluxioConf, null); }
python
def dict_encode(in_dict): """returns a new dictionary with encoded values useful for encoding http queries (python < 3)""" if _IS_PY2: out_dict = {} for k, v in list(in_dict.items()): if isinstance(v, unicode): v = v.encode('utf8') elif isinstance(v, str): # Must be encoded in UTF-8 v.decode('utf8') out_dict[k] = v return out_dict else: raise NotImplementedError
python
def _is_projection_updated_instance(self): """ This method tries to guess if instance was update since last time. If return True, definitely Yes, if False, this means more unknown :return: bool """ last = self._last_workflow_started_time if not self._router.public_api_in_use: most_recent = self.get_most_recent_update_time() else: most_recent = None if last and most_recent: return last < most_recent return False
python
def create_toc(doctree, depth=9223372036854775807, writer_name='html', exclude_first_section=True, href_prefix=None, id_prefix='toc-ref-'): """ Create a Table of Contents (TOC) from the given doctree Returns: (docutils.core.Publisher instance, output string) `writer_name`: represents a reST writer name and determines the type of output returned. Example: pub = blazeutils.rst.rst2pub(toc_rst) pub, html_output = blazeutils.rst.create_toc(pub.document) # a full HTML document (probably not what you want most of the time) print html_output # just the TOC print pub.writer.parts['body'] """ # copy the doctree since Content alters some settings on the original # document doctree = doctree.deepcopy() # we want to be able to customize ids to avoid clashes if needed doctree.settings.auto_id_prefix = id_prefix details = { 'depth': depth, } # Assuming the document has one primary heading and then sub-sections, we # want to be able to give just the sub-sections startnode = None if exclude_first_section: nodes = doctree.traverse(docutils.nodes.section) if nodes: startnode = nodes[0] # use the Contents transform to build the TOC node structure from the # document c = Contents(doctree) # this startnode isn't really used as the start node, its only used for # to pull settings from c.startnode = BlankObject(details=details) # since this toc is detached from the rest of the document, we don't want # backlinks c.backlinks = 'none' # build the nodes toc_nodes = c.build_contents(startnode or doctree) # create a new document with the new nodes toc_doc = new_document(None) toc_doc += toc_nodes # fix fragements that reference the same page if href_prefix: prefix_refids(toc_doc, href_prefix) # setup a publisher and publish from the TOC document reader = docutils.readers.doctree.Reader(parser_name='null') pub = Publisher( reader, None, None, source=io.DocTreeInput(toc_doc), destination_class=io.StringOutput ) pub.set_writer(writer_name) final_settings_overrides = default_rst_opts.copy() pub.process_programmatic_settings( None, final_settings_overrides, None) output = pub.publish() return pub, output
java
public static void fillUniform(GrayF32 img, Random rand , float min , float max) { float range = max-min; float[] data = img.data; for (int y = 0; y < img.height; y++) { int index = img.getStartIndex() + y * img.getStride(); for (int x = 0; x < img.width; x++) { data[index++] = rand.nextFloat()*range+min; } } }
java
Get generateContinueRequest(String cmcontinue) { return newRequestBuilder() // .param("cmcontinue", MediaWiki.urlEncode(cmcontinue)) // .buildGet(); }
java
public static int append(char[] target, int limit, int char32) { // Check for irregular values if (char32 < CODEPOINT_MIN_VALUE || char32 > CODEPOINT_MAX_VALUE) { throw new IllegalArgumentException("Illegal codepoint"); } // Write the UTF-16 values if (char32 >= SUPPLEMENTARY_MIN_VALUE) { target[limit++] = getLeadSurrogate(char32); target[limit++] = getTrailSurrogate(char32); } else { target[limit++] = (char) char32; } return limit; }
java
@Indexable(type = IndexableType.DELETE) @Override public CommerceCurrency deleteCommerceCurrency(long commerceCurrencyId) throws PortalException { return commerceCurrencyPersistence.remove(commerceCurrencyId); }
java
@Override public Long zunionstore(final byte[] dstkey, final byte[]... sets) { checkIsInMultiOrPipeline(); client.zunionstore(dstkey, sets); return client.getIntegerReply(); }
java
public static boolean isSARLAnnotation(Class<?> type) { return (type != null && Annotation.class.isAssignableFrom(type)) && isSARLAnnotation(type.getPackage().getName()); }
python
def _attempt_YYYYMMDD(arg, errors): """ try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like, arg is a passed in as an object dtype, but could really be ints/strings with nan-like/or floats (e.g. with nan) Parameters ---------- arg : passed value errors : 'raise','ignore','coerce' """ def calc(carg): # calculate the actual result carg = carg.astype(object) parsed = parsing.try_parse_year_month_day(carg / 10000, carg / 100 % 100, carg % 100) return tslib.array_to_datetime(parsed, errors=errors)[0] def calc_with_mask(carg, mask): result = np.empty(carg.shape, dtype='M8[ns]') iresult = result.view('i8') iresult[~mask] = tslibs.iNaT masked_result = calc(carg[mask].astype(np.float64).astype(np.int64)) result[mask] = masked_result.astype('M8[ns]') return result # try intlike / strings that are ints try: return calc(arg.astype(np.int64)) except ValueError: pass # a float with actual np.nan try: carg = arg.astype(np.float64) return calc_with_mask(carg, notna(carg)) except ValueError: pass # string with NaN-like try: mask = ~algorithms.isin(arg, list(tslib.nat_strings)) return calc_with_mask(arg, mask) except ValueError: pass return None
java
void setOrthoShadowMatrix(Matrix4f modelMtx, GVRLight light) { GVROrthogonalCamera camera = (GVROrthogonalCamera) getCamera(); if (camera == null) { return; } float w = camera.getRightClippingDistance() - camera.getLeftClippingDistance(); float h = camera.getTopClippingDistance() - camera.getBottomClippingDistance(); float near = camera.getNearClippingDistance(); float far = camera.getFarClippingDistance(); modelMtx.invert(); modelMtx.get(mTempMtx); camera.setViewMatrix(mTempMtx); mShadowMatrix.setOrthoSymmetric(w, h, near, far); mShadowMatrix.mul(modelMtx); sBiasMatrix.mul(mShadowMatrix, mShadowMatrix); mShadowMatrix.getColumn(0, mTemp); light.setVec4("sm0", mTemp.x, mTemp.y, mTemp.z, mTemp.w); mShadowMatrix.getColumn(1, mTemp); light.setVec4("sm1", mTemp.x, mTemp.y, mTemp.z, mTemp.w); mShadowMatrix.getColumn(2, mTemp); light.setVec4("sm2", mTemp.x, mTemp.y, mTemp.z, mTemp.w); mShadowMatrix.getColumn(3, mTemp); light.setVec4("sm3", mTemp.x, mTemp.y, mTemp.z, mTemp.w); }
java
public void disconnect(final ComposableBody msg) throws BOSHException { if (msg == null) { throw(new IllegalArgumentException( "Message body may not be null")); } Builder builder = msg.rebuild(); builder.setAttribute(Attributes.TYPE, TERMINATE); send(builder.build()); }
python
def encode_ulid_base32(binary): """ Encode 16 binary bytes into a 26-character long base32 string. :param binary: Bytestring or list of bytes :return: ASCII string of 26 characters :rtype: str """ assert len(binary) == 16 if not py3 and isinstance(binary, str): binary = [ord(b) for b in binary] symbols = _symbols return ''.join([ symbols[(binary[0] & 224) >> 5], symbols[binary[0] & 31], symbols[(binary[1] & 248) >> 3], symbols[((binary[1] & 7) << 2) | ((binary[2] & 192) >> 6)], symbols[(binary[2] & 62) >> 1], symbols[((binary[2] & 1) << 4) | ((binary[3] & 240) >> 4)], symbols[((binary[3] & 15) << 1) | ((binary[4] & 128) >> 7)], symbols[(binary[4] & 124) >> 2], symbols[((binary[4] & 3) << 3) | ((binary[5] & 224) >> 5)], symbols[binary[5] & 31], symbols[(binary[6] & 248) >> 3], symbols[((binary[6] & 7) << 2) | ((binary[7] & 192) >> 6)], symbols[(binary[7] & 62) >> 1], symbols[((binary[7] & 1) << 4) | ((binary[8] & 240) >> 4)], symbols[((binary[8] & 15) << 1) | ((binary[9] & 128) >> 7)], symbols[(binary[9] & 124) >> 2], symbols[((binary[9] & 3) << 3) | ((binary[10] & 224) >> 5)], symbols[binary[10] & 31], symbols[(binary[11] & 248) >> 3], symbols[((binary[11] & 7) << 2) | ((binary[12] & 192) >> 6)], symbols[(binary[12] & 62) >> 1], symbols[((binary[12] & 1) << 4) | ((binary[13] & 240) >> 4)], symbols[((binary[13] & 15) << 1) | ((binary[14] & 128) >> 7)], symbols[(binary[14] & 124) >> 2], symbols[((binary[14] & 3) << 3) | ((binary[15] & 224) >> 5)], symbols[binary[15] & 31], ])
java
protected String getPath( final Bundle bundle ) { if( m_pathManifestHeader != null ) { final Object value = bundle.getHeaders().get( m_pathManifestHeader ); if( value instanceof String && ( (String) value ).trim().length() > 0 ) { String path = (String) value; if( !path.endsWith( "/" ) ) { path = path + "/"; } return path; } } return m_path; }