language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static ParseException newParseException(String message, Object... args) { return newParseException(null, message, args); }
python
def p_object_literal(self, p): """object_literal : LBRACE RBRACE | LBRACE property_list RBRACE | LBRACE property_list COMMA RBRACE """ if len(p) == 3: p[0] = self.asttypes.Object() else: p[0] = self.asttypes.Obje...
java
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) { return asyncSupplyStage(screenExecutor(executor), supplier); }
python
def get_roles(server_context, container_path=None): """ Gets the set of permissions and roles available from the server :param server_context: A LabKey server context. See utils.create_server_context. :param container_path: :return: """ url = server_context.build_url(security_controller, 'ge...
python
def search_model(self, q, text, lookup=None): '''Implements :meth:`stdnet.odm.SearchEngine.search_model`. It return a new :class:`stdnet.odm.QueryElem` instance from the input :class:`Query` and the *text* to search.''' words = self.words_from_text(text, for_search=True) if not words: ...
java
private MetaHolder createCopy(MetaHolder source, ExecutionType executionType) { return MetaHolder.builder() .obj(source.getObj()) .method(source.getMethod()) .ajcMethod(source.getAjcMethod()) .fallbackExecutionType(source.getFallbackExecutionType()...
python
def search(self, query_term): """DEPRECIATED Method takes a query term and searches Fedora Repository using SPARQL search endpoint and returns a RDF graph of the search results. Args: query_term(str): String to search repository Returns: rdflib.Graph() ...
java
public static final void close(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { Log.e(TAG, "something went wrong on close", e); } }
python
def Schade(mp, rhop, dp, rhog, D): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_. .. math:: Fr_s = \mu^{0.11}\left(\frac{D}{d_p}\right)^{0.025}\left(\frac{\rho_p} {\rho_f}\right)^{0.34} .. math:: ...
java
private static void encodeKey(ByteBuf buf, byte[] key) { if (key == null || key.length == 0) { return; } buf.writeBytes(key); }
java
public void connect(String cluster_name, Address target, long timeout) throws Exception { ch.connect(cluster_name, target, timeout); }
java
private void init_storage_parameters() { first_quick_size_block = first_quick_size * grain_size; last_quick_size_block = last_quick_size * grain_size; last_ql_index = last_quick_size + 1 - first_quick_size; ql_heads = new Listhead[last_ql_index + 1]; }
python
def _get_phi_al_regional(self, C, mag, vs30measured, rrup): """ Returns intra-event (Phi) standard deviation (equation 24, page 1046) """ phi_al = np.ones((len(vs30measured))) s1 = np.ones_like(phi_al) * C['s1e'] s2 = np.ones_like(phi_al) * C['s2e'] s1[vs30measure...
python
def try_except_handler(self, node): """Handler for try except statement to ignore excepted exceptions.""" # List all excepted exception's names excepted_types = [] for handler in node.handlers: if handler.type is None: excepted_types = None bre...
python
def _submit(self, body, future): """Enqueue a problem for submission to the server. This method is thread safe. """ self._submission_queue.put(self._submit.Message(body, future))
java
public <E extends Exception> boolean setMiddleIf(final M newMiddle, Try.BiPredicate<? super Triple<L, M, R>, ? super M, E> predicate) throws E { if (predicate.test(this, newMiddle)) { this.middle = newMiddle; return true; } return false; }
python
def add(self, _mapping=None, **kwargs): """ Add the given item/score pairs to the ZSet. Arguments are specified as ``item1, score1, item2, score2...``. """ if _mapping is not None: _mapping.update(kwargs) mapping = _mapping else: mappin...
java
@Override protected void initFilesystem() throws DataStoreException { super.initFilesystem(); String baseName = descriptor.getName(); File dataFolder = descriptor.getDataFolder(); // Delete old recycled files File[] oldRecycledFiles = BlockBasedDataStoreTools.findRecycledJournalFiles(baseName, dat...
python
def setData(self, index: QModelIndex, value, role=None): """Update selected_ids on click on index cell.""" if not (index.isValid() and role == Qt.CheckStateRole): return False c_id = self.get_item(index).Id self._set_id(c_id, value == Qt.Checked, index) return True
java
public Deployment deploy(URL url, Context context, ClassLoader parent) throws DeployException { boolean extracted = false; File destination = null; try { File f = new File(url.toURI()); if (!f.exists()) throw new IOException("Archive " + url.toExternalForm() + "...
python
def scale(self, data, unit): """Scales quantity to obtain dimensionful quantity. Args: data (numpy.array): the quantity that should be scaled. dim (str): the dimension of data as defined in phyvars. Return: (float, str): scaling factor and unit string. ...
java
public void parseProperty(Element propertyElement, ActivityImpl activity) { String id = propertyElement.attribute("id"); String name = propertyElement.attribute("name"); // If name isn't given, use the id as name if (name == null) { if (id == null) { addError("Invalid property usage on li...
java
@Override public void visit(final Family family) { for (final GedObject gob : family.getAttributes()) { gob.accept(this); } }
java
protected void readDataOutput(org.w3c.dom.Node xmlNode, StartNode startNode) { String id = ((Element) xmlNode).getAttribute("id"); String outputName = ((Element) xmlNode).getAttribute("name"); dataOutputs.put(id, outputName); }
java
private void addCSSFromAnnotation(final Parent parent) { if (annotation != null && annotation.css().length > 0) { for (final String cssFile : annotation.css()) { final URL uri = getClass().getResource(cssFile); if (uri != null) { final String uriToCss = uri.toExternalForm(); parent.getStylesheets...
java
public static boolean isMergedRegion(Sheet sheet, int row, int column) { final int sheetMergeCount = sheet.getNumMergedRegions(); CellRangeAddress ca; for (int i = 0; i < sheetMergeCount; i++) { ca = sheet.getMergedRegion(i); if (row >= ca.getFirstRow() && row <= ca.getLastRow() && column >= ca.getFirs...
java
public void quadTo(Point3d controlPoint, Point3d endPoint) { ensureSlots(true, 6); this.types[this.numTypesProperty.get()] = PathElementType.QUAD_TO; this.numTypesProperty.set(this.numTypesProperty.get()+1); this.coordsProperty[this.numCoordsProperty.get()] = controlPoint.xProperty; this.numCoordsProperty.se...
java
@SuppressWarnings("unchecked") protected void map(KEYIN key, VALUEIN value, Context context) throws IOException, InterruptedException { context.write((KEYOUT) key, (VALUEOUT) value); }
java
public Record [] getSectionArray(int section) { if (sections[section] == null) return emptyRecordArray; List l = sections[section]; return (Record []) l.toArray(new Record[l.size()]); }
python
def register_function_hooks(self, func): """Looks at an object method and registers it for relevent transitions.""" for hook_kind, hooks in func.xworkflows_hook.items(): for field_name, hook in hooks: if field_name and field_name != self.state_field: conti...
java
public static byte[] bytes(Streamable streamable) { if (streamable == null) return null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { streamable.write(stream); } catch (IOException e) { throw new ApplicationException(e); } ret...
java
private int transSweep(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags, int start) { boolean try_ = true; Ptr ipp = null; Ptr opp = null; while (try_) { try_ = false; for (int i = start; i < numTranscoders; i++) { ...
java
private boolean handleSpan(TextCursor cursor, int blockEnd, ArrayList<MDText> elements) { if (mode != MODE_ONLY_LINKS) { int spanStart = findSpanStart(cursor, blockEnd); if (spanStart >= 0) { char span = cursor.text.charAt(spanStart); int spanEnd = findSpa...
java
@Override public final void handle(final Map<String, Object> pReqVars, final IRequestData pRequestData) throws Exception { String processorName = pRequestData.getParameter("nmPrc"); if (processorName == null) { //WHandlerAndJsp requires handle NULL request: return; } try { this.s...
java
public void marshall(SourceRevision sourceRevision, ProtocolMarshaller protocolMarshaller) { if (sourceRevision == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(sourceRevision.getActionName(), ACTIO...
python
def index(self): """ Reset inspector buffers and index project sources dependencies. This have to be executed each time an event occurs. Note: If a Boussole exception occurs during operation, it will be catched and an error flag will be set to ``True`` so event ...
python
def list(self, entityid=None): """ Return the entity with the given entity ID in short form. If no entity ID is given, all records are listed. It returns a dictionary of the form: {eid : {'id' : 'isActive' : 'name' : 'revisionNr' : 'state' : 'type' : }} """ params = {} if ent...
java
private static DateTimeRule toWallTimeRule(DateTimeRule rule, int rawOffset, int dstSavings) { if (rule.getTimeRuleType() == DateTimeRule.WALL_TIME) { return rule; } int wallt = rule.getRuleMillisInDay(); if (rule.getTimeRuleType() == DateTimeRule.UTC_TIME) { wall...
java
public ClassBuilder<T> withField(String field, Class<?> fieldClass) { fields.put(field, fieldClass); return this; }
python
def remove_end_optionals(ir_blocks): """Return a list of IR blocks as a copy of the original, with EndOptional blocks removed.""" new_ir_blocks = [] for block in ir_blocks: if not isinstance(block, EndOptional): new_ir_blocks.append(block) return new_ir_blocks
python
def train(input_dir, batch_size, max_steps, output_dir, checkpoint, cloud_train_config): """Train model in the cloud with CloudML trainer service.""" import google.datalab.ml as ml if checkpoint is None: checkpoint = _util._DEFAULT_CHECKPOINT_GSURL staging_package_url = _util.repackage_to_staging...
python
def l1_error(true, pred): """L1 distance between tensors true and pred.""" return tf.reduce_sum(tf.abs(true - pred)) / tf.to_float(tf.size(pred))
python
def info_for_tags(filename,tags): '''return a dictionary for the given ``tags`` in the header of the DICOM file ``filename`` ``tags`` is expected to be a list of tuples that contains the DICOM address in hex values. basically a rewrite of :meth:`info` because it's so slow. This is a lot faster and more re...
java
public Object invoke(FacesContext context, Object[] params) throws EvaluationException, MethodNotFoundException { try { return m.invoke(context.getELContext(), params); } catch (javax.el.MethodNotFoundException e) { throw new MethodNotFound...
java
public final InstanceConfig getInstanceConfig(InstanceConfigName name) { GetInstanceConfigRequest request = GetInstanceConfigRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); return getInstanceConfig(request); }
java
public MethodParameterInfo[] getParameterInfo() { if (parameterInfo == null) { // Get params from the type descriptor, and from the type signature if available final List<TypeSignature> paramTypeDescriptors = getTypeDescriptor().getParameterTypeSignatures(); final List<TypeSi...
python
def _zforce_xyz(self,x,y,z): """Evaluation of the z force as a function of (x,y,z) in the aligned coordinate frame""" return -2.*np.pi*self._rhoc_M * self.a**3*self._b*self._c * \ _forceInt(x, y, z, self._a2, self._b2*self._a2, self._c2*self._a2, self.n, 2)
python
def this_year(self): """ Get EighthBlocks from this school year only. """ start_date, end_date = get_date_range_this_year() return self.filter(date__gte=start_date, date__lte=end_date)
java
public Observable<ServiceResponse<Page<RecordSetInner>>> listAllByDnsZoneNextWithServiceResponseAsync(final String nextPageLink) { return listAllByDnsZoneNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<RecordSetInner>>, Observable<ServiceResponse<Page<RecordSetInner>>>>()...
java
private MilestoneManager getAnimatedPathManager(final MilestoneLister pMilestoneLister) { final Paint slicePaint = getStrokePaint(COLOR_POLYLINE_ANIMATED, LINE_WIDTH_BIG); return new MilestoneManager(pMilestoneLister, new MilestoneLineDisplayer(slicePaint)); }
java
public TldExtensionType<WebJsptaglibraryDescriptor> getOrCreateTaglibExtension() { List<Node> nodeList = model.get("taglib-extension"); if (nodeList != null && nodeList.size() > 0) { return new TldExtensionTypeImpl<WebJsptaglibraryDescriptor>(this, "taglib-extension", model, nodeList.get(...
java
private void updatePositions(int position) { for (int i = position; i < m_subEntries.size(); i++) { m_subEntries.get(i).setPosition(i); } }
java
public CommandInfo command_query(final DeviceProxy deviceProxy, final String commandName) throws DevFailed { build_connection(deviceProxy); CommandInfo info = null; if (deviceProxy.url.protocol == TANGO) { // try 2 times for reconnection if requ...
python
def _process_response(self, request, response): """Log user operation.""" log_format = self._get_log_format(request) if not log_format: return response params = self._get_parameters_from_request(request) # log a message displayed to user messages = django_mes...
python
def create_data_file_by_format(directory_path = None): """ Browse subdirectories to extract stata and sas files """ stata_files = [] sas_files = [] for root, subdirs, files in os.walk(directory_path): for file_name in files: file_path = os.path.join(root, file_name) ...
python
def to_html(self): """Render as html Args: None Returns: Str the html representation Raises: Errors are propagated """ text = self.text if text is None: text = self.uri return '<a href="%s"%s>%s</a>' % ( ...
java
private void createGlyf(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf"); int size = 0; int start = 0; int endOffset = 0; // Store this as the last loca if (entry != null) { p...
java
public static void appendPaddedInteger(StringBuffer buf, long value, int size) { try { appendPaddedInteger((Appendable)buf, value, size); } catch (IOException e) { // StringBuffer does not throw IOException } }
python
def _make_value(self, value): """ Constructs a _child_spec value from a native Python data type, or an appropriate Asn1Value object :param value: A native Python value, or some child of Asn1Value :return: An object of type _child_spec """ ...
python
def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent): """ Submits the packaged application to spark using a `spark-submit` subprocess Parameters ---------- lane_yaml (str): Path to the YAML lane definition file dist_dir (str): Path to the directory where the packaged code...
python
def remove_field(self, field_name): """Remove the field with the received field name from model.""" field = self._fields.pop(field_name, None) if field is not None and field.default is not None: if six.callable(field.default): self._default_callables.pop(field.key, No...
java
@Override public com.liferay.commerce.product.model.CPDefinitionSpecificationOptionValue getCPDefinitionSpecificationOptionValue( long CPDefinitionSpecificationOptionValueId) throws com.liferay.portal.kernel.exception.PortalException { return _cpDefinitionSpecificationOptionValueLocalService.getCPDefinitionSpeci...
java
public DescribeFileSystemsRequest withFileSystemIds(String... fileSystemIds) { if (this.fileSystemIds == null) { setFileSystemIds(new java.util.ArrayList<String>(fileSystemIds.length)); } for (String ele : fileSystemIds) { this.fileSystemIds.add(ele); } re...
java
public static String formatPeriodISO(final long startMillis, final long endMillis) { return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault()); }
python
def greplines(pattern, lines): """Given a list of strings *lines* return the lines that match pattern. """ res = [] for line in lines: match = re.search(pattern, line) if match is not None: res.append(line) return res
java
public Server openSsl() throws SSLException, CertificateException { SelfSignedCertificate cert = new SelfSignedCertificate(); sslContext = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()) .sslProvider(SslProvider.OPENSSL) .build(); return this; ...
java
protected void addMethodNodes(String desc) { Type[] args = Type.getArgumentTypes(desc); Type ret = Type.getReturnType(desc); Node currentNode = this.currentNode; Element tmp = doc.createElementNS(XML_URI,"arguments"); currentNode.appendChild(tmp); this.currentNode = tmp; ...
python
def del_store(source, store, saltenv='base'): ''' Delete the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to delete the certificate from saltenv The salt envir...
python
def sync_s3(self): """Walk the media/static directories and syncs files to S3""" bucket, key = self.open_s3() for directory in self.DIRECTORIES: for root, dirs, files in os.walk(directory): self.upload_s3((bucket, key, self.AWS_BUCKET_NAME, directory), root, files, di...
python
def save(self, mark): """Save a position in this collection. :param mark: The position to save :type mark: Mark :raises: DBError, NoTrackingCollection """ self._check_exists() obj = mark.as_dict() try: # Make a 'filter' to find/update existing...
java
public static MozuUrl updateFacetUrl(Integer facetId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/facets/{facetId}?responseFields={responseFields}"); formatter.formatUrl("facetId", facetId); formatter.formatUrl("responseFields", responseFields); return n...
java
public static List<CommercePriceEntry> findByCommercePriceListId( long commercePriceListId, int start, int end) { return getPersistence() .findByCommercePriceListId(commercePriceListId, start, end); }
java
private void printUsage() { String WINDOWS_SAMPLE_PATH = "C:\\temp\\newRepository"; String UNIX_SAMPLE_PATH = "/tmp/newRepository"; Calendar calendar = Calendar.getInstance(); DateFormat df1 = new SimpleDateFormat(getLocalizedString("CWTRA0001I")); DateFormat df2 = new SimpleDa...
python
def plot_vs(fignum, Xs, c, ls): """ plots vertical lines at Xs values Parameters _________ fignum : matplotlib figure number Xs : list of X values for lines c : color for lines ls : linestyle for lines """ fig = plt.figure(num=fignum) for xv in Xs: bounds = plt.axis...
java
public CmsJspResourceWrapper getWrap() { if (m_resourceWrapper == null) { m_resourceWrapper = CmsJspResourceWrapper.wrap(m_cms, m_resource); } return m_resourceWrapper; }
python
def admin_view_url(admin_site: AdminSite, obj, view_type: str = "change", current_app: str = None) -> str: """ Get a Django admin site URL for an object. """ app_name = obj._meta.app_label.lower() model_name = obj._meta.object_name.lower() ...
python
def run(): """Compare two or more sets of GO IDs. Best done using sections.""" obj = CompareGOsCli() obj.write(obj.kws.get('xlsx'), obj.kws.get('ofile'), obj.kws.get('verbose', False))
java
public static acolyte.jdbc.Connection connection(final StatementHandler handler, final Properties info) { return connection(handler, new ResourceHandler.Default(), info); }
java
private void initialize(Integer minimum, Integer maximum) { minimumSpanWidth = minimum; maximumSpanWidth = maximum; spanWidth = (minimum != null && maximum != null && minimum.equals(maximum)) ? minimum : null; singlePositionQuery = spanWidth != null && spanWidth.equals(1); }
java
public static <K, V> RubyHash<K, V> rh(K key1, V value1, K key2, V value2) { RubyHash<K, V> rh = newRubyHash(); rh.put(key1, value1); rh.put(key2, value2); return rh; }
java
public static base_response unset(nitro_service client, filterpostbodyinjection resource, String[] args) throws Exception{ filterpostbodyinjection unsetresource = new filterpostbodyinjection(); return unsetresource.unset_resource(client,args); }
java
public synchronized static void initPublicIP() { if (StringUtils.isNotBlank(PUBLIC_IP)) { return; } try { final URL url = new URL("http://checkip.amazonaws.com"); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); ur...
java
@Override protected void suspendFaxJobImpl(FaxJob faxJob) { //get fax job HylaFaxJob hylaFaxJob=(HylaFaxJob)faxJob; //get client HylaFAXClient client=this.getHylaFAXClient(); try { this.suspendFaxJob(hylaFaxJob,client); } catc...
java
public static void checkDescriptor(DatasetDescriptor descriptor) { Preconditions.checkNotNull(descriptor, "Descriptor cannot be null"); Schema schema = descriptor.getSchema(); checkSchema(schema); if (descriptor.isPartitioned()) { // marked as [BUG] because this is checked in DatasetDescriptor ...
java
@Override public Analyzer analyzer() { // Setup stopwords CharArraySet stops = stopwords == null ? getDefaultStopwords(language) : getStopwords(stopwords); return buildAnalyzer(language, stops); }
python
def handle_pagination(self, page_num=None, page_size=None): """ Handle retrieving and processing the next page of results. """ self._response_json = self.get_next_page(page_num=page_num, page_size=page_size) self.update_attrs() self.position = 0 self.values = self.process_page()
java
public void setOndblclick(java.lang.String ondblclick) { getStateHelper().put(PropertyKeys.ondblclick, ondblclick); handleAttribute("ondblclick", ondblclick); }
java
public void addDependecy(Object from, Object... to) { PropertyInterface fromProperty = Keys.getProperty(from); if (!dependencies.containsKey(fromProperty.getPath())) { dependencies.put(fromProperty.getPath(), new ArrayList<PropertyInterface>()); } List<PropertyInterface> list = dependencies.get(fromProperty....
java
public <V extends ViewGroup> void setTypeface(V viewGroup, @StringRes int strResId) { setTypeface(viewGroup, mApplication.getString(strResId)); }
java
public static int procWait (Process process) throws OSHelperException { try { return process.waitFor (); } catch (InterruptedException ex) { throw new OSHelperException ("Received an InterruptedException when waiting for an external process to terminate.", ex); } }
java
@Override protected void paintComponent(Graphics g) { if (type == TYPE_PLAIN) { point.updateWeight(RunVisualizer.getCurrentTimestamp(), decayRate); if (point.weight() < decayThreshold) { getParent().remove(this); return; } } Color color = getCo...
java
public int deleteLogs(String topic, String password) { if (!config.getAuthentication().auth(password)) { return -1; } int value = 0; synchronized (logCreationLock) { Pool<Integer, Log> parts = logs.remove(topic); if (parts != null) { Li...
python
def get_events_for_subscription(access_token, subscription_id, start_timestamp): '''Get the insights evens for a subsctipion since the specific timestamp. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. start_timestamp (str): t...
java
public static void deleteGriddedCoverageExtension(GeoPackageCore geoPackage) { List<String> coverageTables = geoPackage .getTables(ContentsDataType.GRIDDED_COVERAGE); for (String table : coverageTables) { geoPackage.deleteTable(table); } GriddedTileDao griddedTileDao = geoPackage.getGriddedTileDao(); ...
python
def model_import(self): """ Import and instantiate the non-JIT models and the JIT models. Models defined in ``jits`` and ``non_jits`` in ``models/__init__.py`` will be imported and instantiated accordingly. Returns ------- None """ # non-JIT mode...
java
public static <T, R, I extends Interceptor<T>> Function<T, R> intercept(Function<T, R> innermost, Iterable<I> interceptors) { dbc.precondition(interceptors != null, "cannot create an interceptor chain with a null iterable of interceptors"); return new InterceptorChain<>(innermost, interceptors.iterator(...
python
def results(self, Pc): r""" Places the results of the IP simulation into the Phase object. Parameters ---------- Pc : float Capillary Pressure at which phase configuration was reached """ phase = self.project.find_phase(self) net = self.proj...
java
public Map<Object, Boolean> getContains() { if (m_contains == null) { m_contains = CmsCollectionsGenericWrapper.createLazyMap(new CmsContainsTransformer()); } return m_contains; }
python
def render(filepath, ctx=None, paths=None, ask=False, filters=None): """ Compile and render template and return the result as a string. :param template_file: Absolute or relative path to the template file :param ctx: Context dict needed to instantiate templates :param paths: Template search paths ...
python
def get_profile(self, ann_el_demand_per_sector): """ Get the profiles for the given annual demand Parameters ---------- ann_el_demand_per_sector : dictionary Key: sector, value: annual value Returns ------- pandas.DataFrame : Table with all profiles ...