language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static byte asByte(Object value, byte nullValue) { value=convert(Byte.class,value); if (value!=null) { return ((Byte)value).byteValue(); } else { return nullValue; } }
python
def reset(self): """ Clear the active cells. """ self.bumpPhases = np.empty((2,0), dtype="float") self.phaseDisplacement = np.empty((0,2), dtype="float") self.cellsForActivePhases = np.empty(0, dtype="int") self.activeCells = np.empty(0, dtype="int") self.learningCells = np.empty(0, dtyp...
java
@Override public WritableBuffer allocate(int capacityHint) { capacityHint = Math.min(MAX_BUFFER, Math.max(MIN_BUFFER, capacityHint)); return new OkHttpWritableBuffer(new Buffer(), capacityHint); }
java
public static String readString(ByteBuf bf) { byte[] bytes = readRangedBytes(bf); return bytes.length > 0 ? new String(bytes, CharsetUtil.UTF_8) : ""; }
java
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); } }
python
def readBoolean(self): """ Read C{Boolean}. @raise ValueError: Error reading Boolean. @rtype: C{bool} @return: A Boolean value, C{True} if the byte is nonzero, C{False} otherwise. """ byte = self.stream.read(1) if byte == '\x00': retu...
python
def _read_requirements(filename, extra_packages): """Returns a list of package requirements read from the file.""" requirements_file = open(filename).read() hard_requirements = [] for line in requirements_file.splitlines(): if _is_requirement(line): if line.find(';') > -1: ...
python
def write_to(self, group, append=False): """Writes the properties to a `group`, or append it""" data = self.data if append is True: try: # concatenate original and new properties in a single list original = read_properties(group) data =...
python
def threshold_monitor_hidden_threshold_monitor_interface_policy_area_area_value(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor") ...
python
def gaussian_tuple_prior_for_arguments(self, arguments): """ Parameters ---------- arguments: {Prior: float} A dictionary of arguments Returns ------- tuple_prior: TuplePrior A new tuple prior with gaussian priors """ tuple...
java
void setTransition(PdfTransition transition, int page) { PdfDictionary pg = reader.getPageN(page); if (transition == null) pg.remove(PdfName.TRANS); else pg.put(PdfName.TRANS, transition.getTransitionDictionary()); markUsed(pg); }
java
public int length() { try { final StringBuilder s = read(MIN_LENGTH); pushBack.append(s); return s.length(); } catch (IOException ex) { LOGGER.warn("Oops ", ex); } return 0; }
java
Rule KeyDef() { return FirstOf( //found some abc files with only global accidental //assuming it's K:C global accidentals OneOrMoreS(SequenceS( Optional(WSPS()).suppressNode(), GlobalAccidental() )), SequenceS(AnyOf("CDEFGAB").label(BaseNote), OptionalS(KeyNoteAccidental()), O...
python
def find_mecab_dictionary(names): """ Find a MeCab dictionary with a given name. The dictionary has to be installed separately -- see wordfreq's README for instructions. """ suggested_pkg = names[0] paths = [ os.path.expanduser('~/.local/lib/mecab/dic'), '/var/lib/mecab/dic', ...
python
def _count(self, cmd, collation=None): """Internal count helper.""" with self._socket_for_reads() as (sock_info, slave_ok): res = self._command( sock_info, cmd, slave_ok, allowable_errors=["ns missing"], codec_options=self.__write_response_code...
java
public static String hashHex(byte[] data, String alg) throws NoSuchAlgorithmException { return toHex(hash(data, alg)); }
java
public ServerNotificationRegistration getSpecificServerRegistration(RESTRequest request, int clientID, String source_objName, ...
python
def new(): """Creates a new historical technology.""" dir_path = os.path.dirname(os.path.realpath(__file__)) cookiecutter(os.path.join(dir_path, 'historical-cookiecutter/'))
java
public static KeyRange getInputKeyRange(Configuration conf) { String str = conf.get(INPUT_KEYRANGE_CONFIG); return str == null ? null : keyRangeFromString(str); }
java
public void init() throws ServletException { _env= new EnvList(); _cmdPrefix=getInitParameter("commandPrefix"); String tmp = getInitParameter("cgibinResourceBase"); if (tmp==null) tmp = getServletContext().getRealPath("/"); if(log.isDebugEnabled())log.de...
java
public double areaNauticalMiles(Options options) { double topLatRads = Math.toRadians(topEdgeLatitude(options)); double bottomLatRads = Math.toRadians(bottomEdgeLatitude(options)); return Math.PI / 180 * radiusEarthKm * radiusEarthKm * Math.abs(Math.sin(topLatRads) - Math.sin(bo...
python
def compute_ng_stat(gene_graph, pos_ct, alpha=.5): """Compute the clustering score for the gene on its neighbor graph. Parameters ---------- gene_graph : dict Graph of spatially near codons. keys = nodes, edges = key -> value. pos_ct : dict missense mutation count for each codon ...
java
@Subscribe public synchronized void renew(final SchemaAddedEvent schemaAddedEvent) { logicSchemas.put(schemaAddedEvent.getShardingSchemaName(), createLogicSchema(schemaAddedEvent.getShardingSchemaName(), Collections.singletonMap(schemaAddedEvent.getShardingSchemaName(), DataSourceConverter....
java
public static ScrollPanel newScrollPanelY (Widget contents, int maxHeight) { ScrollPanel panel = new ScrollPanel(contents); DOM.setStyleAttribute(panel.getElement(), "maxHeight", maxHeight + "px"); return panel; }
python
def from_msm(cls, msm, n_macrostates, metric=js_metric_array, n_landmarks=None, landmark_strategy='stride', random_state=None, get_linkage=False, fit_only=False): """Create and fit lumped model from pre-existing MSM. Parameters ---------- msm : MarkovS...
java
protected void computeCostEstimates(long childOutputTupleCountEstimate, DatabaseEstimates estimates, ScalarValueHints[] paramHints) { m_estimatedOutputTupleCount = childOutputTupleCountEstimate; m_estimatedProcessedTuple...
python
def block(shape, block_shape): """Create a labels image that divides the image into blocks shape - the shape of the image to be blocked block_shape - the shape of one block returns a labels matrix and the indexes of all labels generated The idea here is to block-process an image by us...
java
public void setValue(Integer newValue) { Integer oldValue = value; value = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.MMCRG__VALUE, oldValue, value)); }
python
def run(self): """Starts or resumes the generator, running until it reaches a yield point that is not ready. """ if self.running or self.finished: return try: self.running = True while True: future = self.future ...
python
def remove_binding(site, hostheader='', ipaddress='*', port=80): ''' Remove an IIS binding. Args: site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. Re...
python
def on_hello(self, message): """ Runs on a hello event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ logger.info("Got a hello") self.identify(self.token) self.heartbeat_thread = Heartbeat(self.ws,...
java
public void operaDesktopAction(String using, int data, String dataString, String dataStringParam) { getScopeServices().getExec().action(using, data, dataString, dataStringParam); }
java
@Override public DescribeProductAsAdminResult describeProductAsAdmin(DescribeProductAsAdminRequest request) { request = beforeClientExecution(request); return executeDescribeProductAsAdmin(request); }
java
public ServiceCachingPolicyBuilder withMaxServiceInstanceIdleTime(int maxServiceInstanceIdleTime, TimeUnit unit) { checkState(maxServiceInstanceIdleTime > 0); checkNotNull(unit); _maxServiceInstanceIdleTimeNanos = unit.toNanos(maxServiceInstanceIdleTime); return this; }
python
def convert_binary_field_to_attachment(env, field_spec): """This method converts the 8.0 binary fields to attachments like Odoo 9.0 makes with the new attachment=True attribute. It has to be called on post-migration script, as there's a call to get the res_name of the target model, which is not yet load...
java
@RequestMapping(value = "/feature/estimates/total/{teamId}", method = GET, produces = APPLICATION_JSON_VALUE) @Deprecated public DataResponse<List<Feature>> featureTotalEstimate( @RequestParam(value = "agileType", required = false) Optional<String> agileType, @RequestParam(value = "estimateMetricType", required...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.STO__IORNTION: setIORNTION((Integer)newValue); return; case AfplibPackage.STO__BORNTION: setBORNTION((Integer)newValue); return; } super.eSet(featureID, newValue); }
python
def _partial_fit(model_and_meta, X, y, fit_params): """ Call partial_fit on a classifiers with training data X and y Arguments --------- model_and_meta : Tuple[Estimator, dict] X, y : np.ndarray, np.ndarray Training data fit_params : dict Extra keyword arguments to pass to p...
python
def expect_table_row_count_to_be_between(self, min_value=0, max_value=None, result_format=None, include_config=False, catch_exceptions=None, meta=None ...
java
@Override public List<Object> listDocumentsInHierarchy() throws Exception { Vector<Object> hierarchy = toHierarchyNodeVector(root); hierarchy.setElementAt(root.getName(), 0); hierarchy.setElementAt(false, 1); hierarchy.setElementAt(false, 2); return hierarchy; }
java
public String selectAggregationByExample(MappedStatement ms) { Class<?> entityClass = getEntityClass(ms); StringBuilder sql = new StringBuilder(); if (isCheckExampleEntityClass()) { sql.append(SqlHelper.exampleCheck(entityClass)); } sql.append("SELECT ${@tk.mybatis.ma...
java
protected static Iterable<AgentTask> getTaskList(List<WeakReference<AgentTask>> tasks) { final Iterable<AgentTask> col = Iterables.transform(tasks, it -> it != null ? it.get() : null); return Iterables.filter(col, it -> it != null); }
java
public void with(Properties source) { Assert.notNull(source, "Source properties cannot be null"); String propertyName = getPropertyName(); getProperties().setProperty(propertyName, source.getProperty(propertyName)); }
java
static public ImageryMetaDataResource getInstanceFromJSON(final JSONObject a_jsonObject, final JSONObject parent) throws Exception { final ImageryMetaDataResource result = new ImageryMetaDataResource(); if(a_jsonObject==null) { throw new Exception("JSON to parse is null"); } result.copyright = parent.getSt...
java
public static void setOptOut(final Context context, boolean optOut) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putBoolean(KEY_OPT_OUT, optOut); editor.apply(); }
java
public static managed_device delete(nitro_service client, managed_device resource) throws Exception { resource.validate("delete"); return ((managed_device[]) resource.delete_resource(client))[0]; }
java
public void addDependencies( String pomPath, List<String> scopes ) throws ProjectException { addDependencies( new Project( pomPath), scopes ); }
java
public static String getCoalesceColumnNames(String columnOrColumnList) { if (Strings.isNullOrEmpty(columnOrColumnList)) { return null; } if (columnOrColumnList.contains(",")) { return "COALESCE(" + columnOrColumnList + ")"; } return columnOrColumnList; }
java
private byte lastL_R_AL() { for (int i = prologue.length(); i > 0; ) { int uchar = prologue.codePointBefore(i); i -= Character.charCount(uchar); byte dirProp = (byte)getCustomizedClass(uchar); if (dirProp == L) { return _L; } ...
python
def initialize_gdt_x86(self, state, concrete_target): """ Create a GDT in the state memory and populate the segment registers. :param state: state which will be modified :param concrete_target: concrete target that will be used to read the fs register :return: ...
java
public static MozuUrl getOrderUrl(Boolean draft, Boolean includeBin, String orderId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}?draft={draft}&includeBin={includeBin}&responseFields={responseFields}"); formatter.formatUrl("draft", draft); formatter.forma...
python
def get_student_by_email(self, email, students=None): """Get a student based on an email address. Calls ``self.get_students()`` to get list of all students, if not passed as the ``students`` parameter. Args: email (str): student email students (list): dictionary...
python
def serialize(self): """This function serialize into a simple dict object. It is used when transferring data to other daemons over the network (http) Here we directly return all attributes :return: json representation of a Daterange :rtype: dict """ return {'day...
python
def async_step(self): """Progress simulation by running all agents once asynchronously. """ assert len(self._agents_to_act) == 0 self._init_step() t = time.time() aiomas.run(until=self.env.trigger_all()) self._agents_to_act = [] self._step_processing_time ...
java
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users public Styler setInput(@NonNull JSONObject result, @NonNull String attribute, boolean inverted) { final String highlightedAttribute = getHighlightedAttribute(result, attribute, inverted, false); return setInput(highlightedAttribute);...
python
def get_attachments_ids(self, ticket_id): """ Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist. """ attachments = self.get_at...
java
public void removeWatch(String path, EventType watchType) throws NotConnectedToServerException, InterruptedException, WatchNotPlacedException { NamespaceEvent event = new NamespaceEvent(path, watchType.getByteValue()); NamespaceEventKey eventKey = new NamespaceEventKey(path, watchType); Object c...
python
def write_aliases(aliases, tempdir): """Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored """ platform = lib.platform() if platform == "unix": home_alias = "cd $BE_DEVE...
python
def pack(self): """Called to create a STOMP message from the internal values. """ headers = ''.join( ['%s:%s\n' % (f, v) for f, v in sorted(self.headers.items())] ) stomp_message = "%s\n%s\n%s%s\n" % (self._cmd, headers, self.body, NULL) # import pprint # ...
java
public void setDefaultProperties(Properties defaultProperties) { this.defaultProperties = new HashMap<>(); for (Object key : Collections.list(defaultProperties.propertyNames())) { this.defaultProperties.put((String) key, defaultProperties.get(key)); } }
java
public List<TLVElement> getChildElements(int tag) { List<TLVElement> elements = new LinkedList<>(); for (TLVElement element : children) { if (tag == element.getType()) { elements.add(element); } } return elements; }
python
def delete(callback=None, path=None, method=Method.DELETE, tags=None, summary="Delete specified resource.", middleware=None): # type: (Callable, Path, Methods, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that deletes resource. """ def inner(c): op = ...
java
public boolean hasIgnoringCase(String value) { if (values.isEmpty()) { return false; } value = value.toLowerCase(); for (String v : values) { if (v.toLowerCase().equals(value)) { return true; } } ...
python
def _setup_transport(self): """Wrap the socket in an SSL object.""" if hasattr(self, 'sslopts'): self.sock = ssl.wrap_socket(self.sock, **self.sslopts) elif hasattr(self, 'sslctx'): self.sock = self.sslctx.wrap_socket(self.sock, ...
python
def __contribution_from_parameters(self, parameter_names): """private method get the prior and posterior uncertainty reduction as a result of some parameter becoming perfectly known Parameters ---------- parameter_names : list parameter that are perfectly known ...
java
public static boolean sameDimensions(Matrix A, Matrix B) { return A.rows() == B.rows() && A.cols() == B.cols(); }
java
private int compress(String argv[], Configuration conf) throws IOException { int i = 0; String cmd = argv[i++]; String srcf = argv[i++]; String dstf = argv[i++]; Path srcPath = new Path(srcf); FileSystem srcFs = srcPath.getFileSystem(getConf()); Path dstPath = new Path(dstf); FileSystem...
python
def roles(self): """gets user groups""" result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
java
public void addImport(String fullyQualifiedName) { String[] importSplit = fullyQualifiedName.split("\\."); String className = importSplit[importSplit.length - 1]; classNameToFullyQualifiedName.put(className, fullyQualifiedName); }
java
protected TrimmedTileSet trim (TileSet aset, OutputStream fout) throws IOException { return TrimmedTileSet.trimTileSet(aset, fout); }
java
private static <K, V> void set(Map<K, Set<V>> map, K key, V value) { Set<V> values = map.get(key); if (values == null) { values = new HashSet<>(); map.put(key, values); } values.add(value); }
python
def _add_view_menu(self): """ Create a default View menu that shows 'Enter Full Screen'. """ mainMenu = self.app.mainMenu() # Create an View menu and make it a submenu of the main menu viewMenu = AppKit.NSMenu.alloc().init() viewMenu.setTitle_(localization["cocoa...
java
public ServiceFuture<DataBoxEdgeDeviceInner> getByResourceGroupAsync(String deviceName, String resourceGroupName, final ServiceCallback<DataBoxEdgeDeviceInner> serviceCallback) { return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(deviceName, resourceGroupName), serviceCallback); }
java
private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) { while (marker < slength) { c = s.charAt(marker...
java
private String getRevIDFromIfMatchHeader() { String ifMatch = getRequestHeaderValue("If-Match"); if (ifMatch == null) { return null; } // Value of If-Match is an ETag, so have to trim the quotes around it: if (ifMatch.length() > 2 && ifMatch.startsWith("\"") && ifMatc...
python
def get_conf(self, test=False): """Send a HTTP request to the satellite (GET /managed_configurations) and update the cfg_managed attribute with the new information Set to {} on failure the managed configurations are a dictionary which keys are the scheduler link instance id and ...
python
def _m2crypto_validate(message, ssldir=None, **config): """ Return true or false if the message is signed appropriately. Four things must be true: 1) The X509 cert must be signed by our CA 2) The cert must not be in our CRL. 3) We must be able to verify the signature using the RSA public key...
python
def extract_scopes(self, request): """ Extract scopes from a request object. """ payload = self.extract_payload(request) if not payload: return None scopes_attribute = self.config.scopes_name() return payload.get(scopes_attribute, None)
java
public static void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable) { printer.log(priority, tag, message, throwable); }
java
@Override public final Object[] toArray() { this.readLock.lock(); try { return this.toArray(new Object[this.size]); } finally { this.readLock.unlock(); } }
java
@GET @Produces({MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE}) public void getWorkerState( @QueryParam("counter") long counter, @QueryParam("hash") long hash, @QueryParam("timeout") long timeout, @Context final HttpServletRequest req ) throws IOException { if...
python
def items(self): """ Returns dictionary items """ return {dep.task: value for dep, value in self._result.items()}.items()
java
public static <T> T deepUnboxAs(Object src, Class<T> result) { return (T) deepUnbox(result, src); }
python
def mute(self, mute): """Mute receiver""" try: if (mute and self._mute == STATE_OFF): self.send_command("MUTE_TOGGLE") self._mute = STATE_ON return True elif not mute and self._mute == STATE_ON: self.send_command("MU...
python
async def _heartbeat_callback(self): """如果设置了心跳,则调用这个协程.""" query = { "MPRPC": self.VERSION, "HEARTBEAT": "ping" } queryb = self.encoder(query) while True: await asyncio.sleep(self.heart_beat) self.writer.write(queryb) i...
python
def fix_identities(self, uniq=None): """Make pattern-tree tips point to same object if they are equal.""" if not hasattr(self, 'children'): return self uniq = list(set(self.flat())) if uniq is None else uniq for i, child in enumerate(self.children): if not hasattr...
python
def prop_unc(jc): """ Propagate uncertainty. :param jc: the Jacobian and covariance matrix :type jc: sequence This method is mainly designed to be used as the target for a multiprocessing pool. """ j, c = jc return np.dot(np.dot(j, c), j.T)
java
private String removeTrailingSlash(String originalPath) { String trailingSlash = "/"; String requestPath = originalPath; if (requestPath != null && !requestPath.isEmpty() && !requestPath.equals(trailingSlash)) { requestPath = requestPath.endsWith(trailingSlash) ? requestPath.substrin...
python
def _new_pivot_query(self): """ Create a new query builder for the pivot table. :rtype: eloquent.orm.Builder """ query = super(MorphToMany, self)._new_pivot_query() return query.where(self._morph_type, self._morph_class)
python
def Corripio_motor_efficiency(P): r'''Estimates motor efficiency using the method in Corripio (1982) as shown in [1]_ and originally in [2]_. Estimation only. .. math:: \eta_M = 0.8 + 0.0319\ln(P_B) - 0.00182\ln(P_B)^2 Parameters ---------- P : float Power, [W] Returns ...
java
public String getName() { if (name == null) { name = "INVALID_TOKEN_NAME"; try { // Build a JwtConsumer that doesn't check signatures or do any validation. JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder() .setSkipAllValid...
java
private void init(AttributeSet attrs) { inflate(getContext(), R.layout.intl_phone_input, this); /**+ * Country spinner */ mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country); mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext()); ...
python
def format_str(self): ''' Return a format string with named fields. ''' if self.static: return self.route.replace('%','%%') out, i = '', 0 for token, value in self.tokens(): if token == 'TXT': out += value.replace('%','%%') elif token == 'ANON': out +=...
python
def html_visit_inheritance_diagram( self: NodeVisitor, node: inheritance_diagram ) -> None: """ Builds HTML output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node. """ inheritance_graph = node["graph"] urls = build_urls(self, node) graphviz_graph = inheritance_graph.bu...
python
def _var_names(var_names, data): """Handle var_names input across arviz. Parameters ---------- var_names: str, list, or None data : xarray.Dataset Posterior data in an xarray Returns ------- var_name: list or None """ if var_names is not None: if isinstance(var_...
java
public static <M extends net.morimekta.providence.PMessage<M, F>, F extends net.morimekta.providence.descriptor.PField> Any wrapMessage(@javax.annotation.Nonnull M message) { return wrapMessage(message, new net.morimekta.providence.serializer.BinarySerializer()); }
java
protected String checkModifyWhitelist(final CatalogType suspect, final CatalogType prevType, final String field) { // should generate this from spec.txt if (suspect instanceof Systemsettings && (field.eq...
java
private Object populateEntityFromHBaseData(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m, Object rowKey) { try { Map<String, Object> relations = new HashMap<String, Object>(); if (entity.getClass().isAssignableFrom(EnhanceEntity.class)) {...
python
def _search_for_import_symbols(self, matches): ''' Just encapsulating a search that takes place fairly often ''' # Sanity check if not hasattr(self.pefile_handle, 'DIRECTORY_ENTRY_IMPORT'): return [] # Find symbols that match pattern = '|'.join(re.escape(match) for ...
java
public static int findEndOfSubExpression(String expression, int start) { int count = 0; for (int i = start; i < expression.length(); i++) { switch (expression.charAt(i)) { case '(': { count++; break; } case ')': { count--; if (count == 0) { return i; } break; }...