language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static InputStream getStream(URL url) { Assert.notNull(url); try { return url.openStream(); } catch (IOException e) { throw new IORuntimeException(e); } }
java
private void doAttribute(Node receivedElement, Node receivedAttribute, Node sourceElement, XmlMessageValidationContext validationContext, NamespaceContext namespaceContext, TestContext context) { if (receivedAttribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) { return; } Strin...
java
private void computeContainment( int imageArea ) { // mark that the track is in the inlier set and compute the containment rectangle contRect.x0 = contRect.y0 = Double.MAX_VALUE; contRect.x1 = contRect.y1 = -Double.MAX_VALUE; for( AssociatedPair p : motion.getModelMatcher().getMatchSet() ) { Point2D_F64 t = ...
java
public Vector<Object> marshallize() { Vector<Object> parameters = new Vector<Object>(); parameters.add(ENVTYPE_NAME_IDX, StringUtils.defaultString(name)); return parameters; }
java
protected void spoolInputStream() { if (spoolFile != null || data != null) // already spooled { return; } byte[] buffer = new byte[0]; byte[] tmpBuff = new byte[2048]; int read = 0; int len = 0; SpoolFile sf = null; OutputStream sfout = null; try...
python
def _sort_kw_matches(skw_matches, limit=0): """Return a resized version of keywords to the given length.""" sorted_keywords = list(skw_matches.items()) sorted(sorted_keywords, key=cmp_to_key(_skw_matches_comparator)) return limit and sorted_keywords[:limit] or sorted_keywords
java
@Nonnull public static String getFormatted (@Nonnull final BigInteger aValue, @Nonnull final Locale aDisplayLocale) { ValueEnforcer.notNull (aValue, "Value"); ValueEnforcer.notNull (aDisplayLocale, "DisplayLocale"); return NumberFormat.getIntegerInstance (aDisplayLocale).format (aValue); }
java
public CertificateBundle mergeCertificate(String vaultBaseUrl, String certificateName, List<byte[]> x509Certificates) { return mergeCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, x509Certificates).toBlocking().single().body(); }
python
def _approximate_eigenvalues(A, tol, maxiter, symmetric=None, initial_guess=None): """Apprixmate eigenvalues. Used by approximate_spectral_radius and condest. Returns [W, E, H, V, breakdown_flag], where W and E are the eigenvectors and eigenvalues of the Hessenberg matrix ...
python
def consistency(self, consistency): """ Sets the consistency level for the operation. See :class:`.ConsistencyLevel`. .. code-block:: python for user in User.objects(id=3).consistency(CL.ONE): print(user) """ clone = copy.deepcopy(self) clone...
java
public RenderScript getRenderScript() { if (renderScript == null) { renderScript = RenderScript.create(context, renderScriptContextType); } return renderScript; }
python
def ConfirmarDefinitivo(self, numero_carta_de_porte, numero_ctg, establecimiento=None, codigo_cosecha=None, peso_neto_carga=None, **kwargs): "Confirma arribo definitivo CTG" ret = self.client.confirmarDefinitivo(request=dict( ...
python
def _iso_info(iso_year, iso_week): "Give all the iso info we need from one calculation" prev_year_start = _iso_year_start(iso_year-1) year_start = _iso_year_start(iso_year) next_year_start = _iso_year_start(iso_year+1) first_day = year_start + dt.timedelta(weeks=iso_week-1) last_day = first_day ...
python
def get_port_channel_detail_input_last_aggregator_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail input = ET.SubElement(get_port_channel_detail, "...
python
def visible_object_layers(self): """ This must return layer objects This is not required for custom data formats. :return: Sequence of pytmx object layers/groups """ return (layer for layer in self.tmx.visible_layers if isinstance(layer, pytmx.TiledObjectGroup))
python
def run(self): """Run install process.""" try: self.linux.verify_system_status() except InstallSkipError: Log.info('Install skipped.') return work_dir = tempfile.mkdtemp(suffix='-rpm-py-installer') Log.info("Created working directory '{0}'".fo...
java
public String generateExistingClassCodeForTable(final TableModel table) { final ST template = this.stGroup.getInstanceOf("existingTableClass"); LOG.debug("Filling template..."); template.add("table", table); LOG.debug("Rendering template..."); return template.render(); ...
python
def difference(self, other, joinBy=None, exact=False): """ *Wrapper of* ``DIFFERENCE`` DIFFERENCE is a binary, non-symmetric operator that produces one sample in the result for each sample of the first operand, by keeping the same metadata of the first operand sample and only th...
java
public CsvFieldError getFirstFieldError() { for(CsvError item : this.errors) { if(item instanceof CsvFieldError) { return (CsvFieldError) item; } } return null; }
python
def tickets_create_many(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets" api_path = "/api/v2/tickets/create_many.json" return self.call(api_path, method="POST", data=data, **kwargs)
java
public byte[] toByteArray() { final int size = getSize(); final ByteBuffer buff = ByteBuffer.allocate(size); // Add type byte buff.put(type.getValue()); // add flags byte byte flagSRC = 0x00; for (AceFlag flag : getFlags()) { flagSRC |= flag.getValu...
java
public static Driver driver( String uri, AuthToken authToken ) { return driver( uri, authToken, Config.defaultConfig() ); }
java
public List<String> selectProjectPermissionsOfGroup(DbSession session, String organizationUuid, @Nullable Integer groupId, long projectId) { return mapper(session).selectProjectPermissionsOfGroup(organizationUuid, groupId, projectId); }
java
public DBInstance withReadReplicaDBInstanceIdentifiers(String... readReplicaDBInstanceIdentifiers) { if (this.readReplicaDBInstanceIdentifiers == null) { setReadReplicaDBInstanceIdentifiers(new java.util.ArrayList<String>(readReplicaDBInstanceIdentifiers.length)); } for (String ele :...
python
def parse_query(query, ilogger): """ Gets either a list of videos from a query, parsing links and search queries and playlists Args: query (str): The YouTube search query ilogger (logging.logger): The logger to log API calls to Returns: queue (list): The items obtained from...
java
public static long getUriSize(String urlStr) { HttpURLConnection conn = null; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.getInputStream(); return conn.getContentLengthLo...
java
@SafeVarargs public static <T> T checkPreconditions( final T value, final ContractConditionType<T>... conditions) throws PreconditionViolationException { final Violations violations = innerCheckAll(value, conditions); if (violations != null) { throw new PreconditionViolationException( ...
java
public CSLType toType(Key type) { String s = type.getValue(); if (s.equalsIgnoreCase(TYPE_ARTICLE)) { return CSLType.ARTICLE_JOURNAL; } else if (s.equalsIgnoreCase(TYPE_PROCEEDINGS)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_MANUAL)) { return CSLType.BOOK; } else if (s.equalsIgnoreCas...
python
def _get_portfolio_info(self, portfolio_code): """ 获取组合信息 """ url = self.PORTFOLIO_URL + portfolio_code portfolio_page = self.s.get(url) match_info = re.search(r'(?<=SNB.cubeInfo = ).*(?=;\n)', portfolio_page.text) if match_info is N...
java
public static final <T extends Calendar> Function<T, LocalTime> calendarToLocalTime(Chronology chronology) { return new CalendarToLocalTime<T>(chronology); }
java
public java.util.List<String> getCacheNodeIdsToRemove() { if (cacheNodeIdsToRemove == null) { cacheNodeIdsToRemove = new com.amazonaws.internal.SdkInternalList<String>(); } return cacheNodeIdsToRemove; }
python
def _driver_signing_reg_reverse_conversion(cls, val, **kwargs): ''' converts the string value seen in the GUI to the correct registry value for secedit ''' if val is not None: if val.upper() == 'SILENTLY SUCCEED': return ','.join(['3', '0']) ...
java
public void addConverter(ValueConverter<?, ?> converter) { getInitializationState().requireNotInitilized(); if (this.converters == null) { this.converters = new ArrayList<>(); } this.converters.add(converter); }
java
public static base_response delete(nitro_service client, String acl6name) throws Exception { nsacl6 deleteresource = new nsacl6(); deleteresource.acl6name = acl6name; return deleteresource.delete_resource(client); }
java
public static Identity createExtendedIdentifier(String namespaceUri, String namespacePrefix, String identifierName) { return createExtendedIdentifier(namespaceUri, namespacePrefix, identifierName, null, ""); }
python
def write(self, file_or_filename, prog=None, format='xdot'): """ Writes the case data in Graphviz DOT language. The format 'raw' is used to dump the Dot representation of the Case object, without further processing. The output can be processed by any of graphviz tools, defined in 'prog'...
java
public static Identity fromByteArray(final byte[] anArray) throws PersistenceBrokerException { // reverse of the serialize() algorithm: // read from byte[] with a ByteArrayInputStream, decompress with // a GZIPInputStream and then deserialize by reading from the ObjectInputStream ...
java
public static BufferedImage loadPGM( String fileName , BufferedImage storage ) throws IOException { return loadPGM(new FileInputStream(fileName), storage); }
java
public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); }
python
def show_metrics(metrics, all_branches=False, all_tags=False): """ Args: metrics (list): Where each element is either a `list` if an xpath was specified, otherwise a `str` """ for branch, val in metrics.items(): if all_branches or all_tags: logger.info("{branch}:"...
java
public final boolean nextBoolean(final double probability) { int y; int z; if (probability < 0.0 || probability > 1.0) throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive."); if (probability==0.0) return false; // fix ha...
python
def requester( url, main_url=None, delay=0, cook=None, headers=None, timeout=10, host=None, proxies=[None], user_agents=[None], failed=None, processed=None ): """Handle the requests and return the response body.""" cook ...
java
public static final void setIntAttribute(Path path, String attribute, int value, LinkOption... options) throws IOException { attribute = attribute.startsWith("user:") ? attribute : "user:"+attribute; Files.setAttribute(path, attribute, Primitives.writeInt(value), options); }
python
def call(self, command, params=None, expect_body=True, stream=False): """ Sends the provided command to Serf for evaluation, with any parameters as the message body. """ if self._socket is None: raise SerfConnectionError('handshake must be made first') header...
python
def search(self, q, **kw): """Search Gnip for given query, returning deserialized response.""" url = '{base_url}/search/{stream}'.format(**vars(self)) params = { 'q': q, } params.update(self.params) params.update(kw) response = self.session.get(url, ...
java
private void mergeValuesLength(int begin, int end) { if (begin < end) { int bValue = toIntUnsigned(getValue(begin)); int eValue = toIntUnsigned(getValue(end)); int eLength = toIntUnsigned(getLength(end)); int newLength = eValue - bValue + eLength; setLength(begin, (short) newLength); ...
java
void setParent(JMFMessageData parent) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "setParent", new Object[] { parent }); synchronized (getMessageLockArtefact()) { // If the parent is a JSMessageData then this is straight forward ...
java
@NonNull @Override public MutableDictionary setDouble(@NonNull String key, double value) { return setValue(key, value); }
python
def to_structure(matrix, alpha=1): """Compute best matching 3D genome structure from underlying input matrix using ShRec3D-derived method from Lesne et al., 2014. Link: https://www.ncbi.nlm.nih.gov/pubmed/25240436 The method performs two steps: first compute distance matrix by treating contact dat...
java
private void batch_insert(Collection<Integer> set, boolean parallel) { for(int i : set) store[size++] = i; if(parallel) Arrays.parallelSort(store, 0, size); else Arrays.sort(store, 0, size); }
java
public void release() { this.parent = null; this.id = null; this.facesJspId = null; this.created = false; this.bodyContent = null; this.isNestedInIterator = false; _nextChildIndex = 0; }
java
public Parameters copyMergingIntoCurrentNamespace(final Parameters paramsToAdd) { // we use the immutable map builder even though it requires tracking seen // items separately to maintain determinism final ImmutableMap.Builder<String, String> newParamsMap = ImmutableMap.builder(); final Set<String> seen...
python
def is_binary(filename): """ Returns True if the file is binary """ with open(filename, 'rb') as fp: data = fp.read(1024) if not data: return False if b'\0' in data: return True return False
java
private SqlModality deduceModality(SqlNode query) { if (query instanceof SqlSelect) { SqlSelect select = (SqlSelect) query; return select.getModifierNode(SqlSelectKeyword.STREAM) != null ? SqlModality.STREAM : SqlModality.RELATION; } else if (query.getKind() == SqlKind.VALUES) { return SqlModality....
java
public String readQuery(String queryKey) { String result = m_queries.get(queryKey); if (result != null) { result = result.replace('\t', ' '); result = result.replace('\n', ' '); result = result.replace('\r', ' '); } return result; }
python
def Validate(self, type_names): """Filtered types need to be RDFValues.""" errs = [n for n in self._RDFTypes(type_names) if not self._GetClass(n)] if errs: raise DefinitionError("Undefined RDF Types: %s" % ",".join(errs))
python
def requestMarketDepth(self, contracts=None, num_rows=10): """ Register to streaming market data updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdepth.htm """ if num_rows > 10: num_rows = 10 if contracts == None: co...
python
def start_app(app_id, is_finished=False): """ update app state to 'Running' """ state = constant.STATE_APP_RUNNING if is_finished else constant.STATE_APP_STARTING app_update_state(app_id, state)
java
public boolean isSelectedPartially(TreePath path) { CheckedNode cn = nodesCheckingState.get(path); return cn.isSelected && cn.hasChildren && !cn.allChildrenSelected; }
java
boolean localDestination(String name, PdfDestination destination) { Object obj[] = (Object[])localDestinations.get(name); if (obj == null) obj = new Object[3]; if (obj[2] != null) return false; obj[2] = destination; localDestinations.put(name, obj); ...
java
public static <T> SimplePath<T> path(Class<? extends T> type, Path<?> parent, String property) { return simplePath(type, parent, property); }
java
public void handleCameraPreviewTouchEvent(MotionEvent ev) { if (mFullScreen != null) mFullScreen.handleTouchEvent(ev); if (mDisplayRenderer != null) mDisplayRenderer.handleTouchEvent(ev); }
java
public static Titan1Vertex createVertex(Titan1Graph graph, Vertex source) { if (source == null) { return null; } return new Titan1Vertex(graph, source); }
python
def _conn(queue): ''' Return an sqlite connection ''' queue_dir = __opts__['sqlite_queue_dir'] db = os.path.join(queue_dir, '{0}.db'.format(queue)) log.debug('Connecting to: %s', db) con = sqlite3.connect(db) tables = _list_tables(con) if queue not in tables: _create_table(c...
java
@Override public DescribeRobotApplicationResult describeRobotApplication(DescribeRobotApplicationRequest request) { request = beforeClientExecution(request); return executeDescribeRobotApplication(request); }
java
protected static Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); for (int i = 0; (cookies != null) && (i < cookies.length); i++) { if (name.equalsIgnoreCase(cookies[i].getName())) { return cookies[i]; } ...
python
def to_dense(self, sampling_rate): ''' Convert the current sparse column to a dense representation. Returns: A DenseRunVariable. Args: sampling_rate (int, str): Sampling rate (in Hz) to use when constructing the DenseRunVariable. Returns: A Dense...
python
def allow(self, channel, message): """ Allow plugins to filter content. """ return all( filter(channel, message) for filter in _load_filters() )
java
public JspPropertyGroupType<JspConfigType<T>> getOrCreateJspPropertyGroup() { List<Node> nodeList = childNode.get("jsp-property-group"); if (nodeList != null && nodeList.size() > 0) { return new JspPropertyGroupTypeImpl<JspConfigType<T>>(this, "jsp-property-group", childNode, nodeList.get...
java
public boolean isAssignableFrom(Key<? super T> key) { Objects.requireNonNull(key); for (Class<? extends Annotation> annType : _annTypes) { if (! containsType(annType, key._annTypes)) { return false; } } if (_type instanceof ParameterizedType) { if (! (key._type instanceof P...
java
@Override public DeleteScheduledActionResult deleteScheduledAction(DeleteScheduledActionRequest request) { request = beforeClientExecution(request); return executeDeleteScheduledAction(request); }
java
public static TomcatService forClassPath(Class<?> clazz, String docBase) { return TomcatServiceBuilder.forClassPath(clazz, docBase).build(); }
python
def readline(self, f): """A helper method that only reads uncommented lines""" while True: line = f.readline() if len(line) == 0: raise EOFError line = line[:line.find('#')] line = line.strip() if len(line) > 0: ...
python
def enable_mesos_basic_authentication(principal, password): """ enables and adds a new authorized principal """ restart = False secrets_file = '/etc/mesos/secrets' secrets_entry = '%s %s' % (principal, password) if not file_contains(filename=secrets_file, text=secrets_entry,...
java
protected int[] rankUnfeasibleSolutions(List<S> population){ int numberOfViolatedConstraintsBySolution1, numberOfViolatedConstraintsBySolution2; int indexOfFirstSolution, indexOfSecondSolution, indexOfWeight; double overallConstraintViolationSolution1, overallConstraintViolationSolution2; ...
java
@Nullable public static Class <?> getPrimitiveWrapperClass (@Nullable final Class <?> aClass) { if (isPrimitiveWrapperType (aClass)) return aClass; return PRIMITIVE_TO_WRAPPER.get (aClass); }
java
public <T> AsyncMutateInBuilder arrayAddUnique(String path, T value) { this.mutationSpecs.add(new MutationSpec(Mutation.ARRAY_ADD_UNIQUE, path, value)); return this; }
java
private void startWatcher() { if (m_watcher == null) { try { m_watcher = new CmsUploadTimeoutWatcher(this); m_watcher.start(); } catch (Exception e) { LOG.info( Messages.get().getBundle().key(Messages.LOG_UPLOAD_CREATE_...
java
public Quaternionf invert(Quaternionf dest) { float invNorm = 1.0f / (x * x + y * y + z * z + w * w); dest.x = -x * invNorm; dest.y = -y * invNorm; dest.z = -z * invNorm; dest.w = w * invNorm; return dest; }
python
def _init_metadata(self): """stub""" self._source_assessment_taken_id_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'source_assessment_taken_id'), 'element_label': ...
python
def get_ssh_subsystem_names(self): """ Return a list of possible SSH subsystem names. Different NXOS versions use different SSH subsystem names for netconf. Therefore, we return a list so that several can be tried, if necessary. The Nexus device handler also accepts ""...
java
private void writeAssignment(ResourceAssignment mpxj) { ResourceAssignmentType xml = m_factory.createResourceAssignmentType(); m_project.getResourceAssignment().add(xml); Task task = mpxj.getTask(); Task parentTask = task.getParentTask(); Integer parentTaskUniqueID = parentTask == null ...
java
public void incRetryCount () { m_nRetries++; m_aPreviousRetryDT = PDTFactory.getCurrentLocalDateTime (); m_aNextRetryDT = m_aPreviousRetryDT.plusMinutes (PDServerConfiguration.getReIndexRetryMinutes ()); }
java
@Override public ListStackInstancesResult listStackInstances(ListStackInstancesRequest request) { request = beforeClientExecution(request); return executeListStackInstances(request); }
java
public CommandLine parseArgs(final String[] args) throws CLIToolOptionsException { final CommandLine line = super.parseArgs(args); if (args.length > 0 && !args[0].startsWith("-")) { try { action = Actions.valueOf(args[0]); } catch (IllegalArgumentException e) { ...
java
public static String repeatString( String pattern, int repeats ) { StringBuilder buffer = new StringBuilder( pattern.length() * repeats ); for( int i = 0; i < repeats; i++ ) { buffer.append( pattern ); } return new String( buffer ); }
python
def is_url(value, **kwargs): """Indicate whether ``value`` is a URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_, `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, ...
python
def parse_example_line(lisp_string: str) -> Dict: """ Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) ...
java
public void encode(BsonWriter writer, T value, EncoderContext encoderContext) { writer.writeStartDocument(); encodeVariables(writer, value, encoderContext); writer.writeEndDocument(); }
java
public static void main(String [] args){ displayCopyright(); if (!checkArgs(args)) { displayHelp(); return; } //get model dir String modelDir = args[1]; CRFSegmenter segmenter = new CRFSegmenter(modelDir); //taggi...
java
private static void checkBlockEndContext(RenderUnitNode node, Context endContext) { if (!endContext.isValidEndContextForContentKind( MoreObjects.firstNonNull(node.getContentKind(), SanitizedContentKind.HTML))) { String msg = String.format( "A block of kind=\"%s\" cannot end in ...
java
public void processReceivedMessage( Message message, Session session ) throws IOException { this.logger.fine( "The DM's HTTP client is about to process a message (" + message + ") received through a web socket." ); // HttpMessage if( message instanceof HttpMessage ) { HttpMessage httpMsg = (HttpMessage) messa...
python
def to_microseconds(value): """Convert a datetime to microseconds since the unix epoch. Args: value (datetime.datetime): The datetime to covert. Returns: int: Microseconds since the unix epoch. """ if not value.tzinfo: value = value.replace(tzinfo=pytz.utc) # Regardless...
python
def key_by(self, key_selector): """Applies a key_by operator to the stream. Attributes: key_attribute_index (int): The index of the key attributed (assuming tuple records). """ op = Operator( _generate_uuid(), OpType.KeyBy, "...
python
def compute_accept_value(key: Union[str, bytes]) -> str: """Computes the value for the Sec-WebSocket-Accept header, given the value for Sec-WebSocket-Key. """ sha1 = hashlib.sha1() sha1.update(utf8(key)) sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") # Magic value ...
java
protected Resource getDownloadResource() { String pathToDownload = (String)m_file.getValue(); if (m_donwloadAll.getValue().booleanValue()) { pathToDownload = ZIP_PATH; writeZipFile(); } final File downloadFile = new File(pathToDownload); return new Str...
java
protected int findMatchingVersionIndex(String dbVersion) { int index = 0; int matchingVersionIndex = -1; while (matchingVersionIndex < 0 && index < ACTIVITI_VERSIONS.size()) { if (ACTIVITI_VERSIONS.get(index).matches(dbVersion)) { matchingVersionIndex = index; ...
java
protected static Document getDocument(InputStream in) throws Exception { DocumentBuilder builder = XmlTransformUtility.borrowDocumentBuilder(); Document doc = null; try { doc = builder.parse(in); } finally { XmlTransformUtility.returnDocumentBuilder(bu...
python
def encode(self): """ Returns binary string representation of this struct. :returns: Structure encoded as binary string for keepass database. :rtype: bytes """ ret = bytearray() for name, len, typecode in self.format: value = getattr(self, nam...
java
public static AnnotationValue getAnnotationValue( AnnotationMirror annotationMirror, String elementName) { return getAnnotationElementAndValue(annotationMirror, elementName).getValue(); }