language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def sync(self): """ Upload the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the h...
java
public boolean isUnifiableWith(SyntacticCategory other) { Map<Integer, String> myAssignedVariables = Maps.newHashMap(); Map<Integer, String> otherAssignedVariables = Maps.newHashMap(); Map<Integer, Integer> variableRelabeling = Maps.newHashMap(); // System.err.println("unifying: " + this + " " + other)...
python
def get_rating_metadata(self): """Gets the metadata for a rating. return: (osid.Metadata) - metadata for the rating *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template met...
java
@Override public List<CommerceTaxFixedRateAddressRel> findByCommerceTaxMethodId( long commerceTaxMethodId) { return findByCommerceTaxMethodId(commerceTaxMethodId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
public void marshall(MathActivity mathActivity, ProtocolMarshaller protocolMarshaller) { if (mathActivity == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(mathActivity.getName(), NAME_BINDING); ...
java
@Override public CommerceShippingMethod fetchByG_E(long groupId, String engineKey) { return fetchByG_E(groupId, engineKey, true); }
java
@SuppressWarnings("unchecked") public static void addIQProvider(String elementName, String namespace, Object provider) { validate(elementName, namespace); // First remove existing providers String key = removeIQProvider(elementName, namespace); if (provider instanceof IQP...
python
def press_event(self): """ The mouse press event that initiated a mouse drag, if any. """ if self.mouse_event.press_event is None: return None ev = self.copy() ev.mouse_event = self.mouse_event.press_event return ev
java
@Help(help = "Change a user's password") public void changePassword(String oldPassword, String newPassword) throws SDKException { HashMap<String, String> requestBody = new HashMap<>(); requestBody.put("old_pwd", oldPassword); requestBody.put("new_pwd", newPassword); requestPut("changepwd", requestBod...
python
def declare_namespace(packageName): """Declare that package 'packageName' is a namespace package""" _imp.acquire_lock() try: if packageName in _namespace_packages: return path = sys.path parent, _, _ = packageName.rpartition('.') if parent: declare_...
java
public void getAllWvWUpgradeID(Callback<List<Integer>> callback) throws NullPointerException { gw2API.getAllWvWUpgradeIDs().enqueue(callback); }
java
public static void apply(MutableFst fst, ProjectType pType) { if (pType == ProjectType.INPUT) { fst.setOutputSymbolsAsCopyFromThatInput(fst); } else if (pType == ProjectType.OUTPUT) { fst.setInputSymbolsAsCopyFromThatOutput(fst); } for (int i = 0; i < fst.getStateCount(); i++) { Mutab...
java
public static String format(final long millis, final String pattern, final Locale locale) { return format(new Date(millis), pattern, null, locale); }
java
public OperationStatus updateSubList(UUID appId, String versionId, UUID clEntityId, int subListId, WordListBaseUpdateObject wordListBaseUpdateObject) { return updateSubListWithServiceResponseAsync(appId, versionId, clEntityId, subListId, wordListBaseUpdateObject).toBlocking().single().body(); }
java
public static int getEndWeekOfMonth (@Nonnull final LocalDateTime aDT, @Nonnull final Locale aLocale) { return getWeekOfWeekBasedYear (aDT.plusMonths (1).withDayOfMonth (1).minusDays (1), aLocale); }
java
public void getKey(int keyIndex, Quaternionf q) { int index = keyIndex * mFloatsPerKey; q.x = mKeys[index + 1]; q.y = mKeys[index + 2]; q.z = mKeys[index + 3]; q.w = mKeys[index + 4]; }
java
public static BasicAuthorizationDetectionMethod loadMethodFromSession(Session session, int contextId) throws DatabaseException { int statusCode = NO_STATUS_CODE; try { List<String> statusCodeL = session.getContextDataStrings(contextId, RecordContext.TYPE_AUTHORIZATION_METHOD_FIELD_1); statusCode = In...
python
def create(name: str, *, validate: bool=None) -> snug.Query[Channel]: """create a new channel""" return {'name': name, 'validate': validate}
python
def shift(self, x): """ Return a new segment whose bounds are given by adding x to the segment's upper and lower bounds. """ return tuple.__new__(self.__class__, (self[0] + x, self[1] + x))
java
public void indent() throws IOException { for (int i=0; i<indent; i++) writeRawString(" "); } /** * Method to increase the indent depth of the output writer. * @throws IOException Thrown if an error occurs during write. */ public void indentPush() { indent++; } ...
java
@Pure @Inline(value = "AssertMessages.tooSmallArrayParameter(0, $1, $2)", imported = {AssertMessages.class}) public static String tooSmallArrayParameter(int currentSize, int expectedSize) { return tooSmallArrayParameter(0, currentSize, expectedSize); }
python
def summarise(self): """ extrapolate a human readable summary of the contexts """ res = '' if self.user == 'Developer': if self.host == 'Home PC': res += 'At Home' else: res += 'Away from PC' elif self.user == 'Us...
python
def train_position(self, layers, x_scale, y_scale): """ Create all the required x & y panel_scales y_scales and set the ranges for each scale according to the data. Notes ----- The number of x or y scales depends on the facetting, particularly the scales paramete...
java
@Override public void send(PayloadData payloadData) throws Exception { if (logger.isDebugEnabled()) { logger.debug(String.format("Tx : Ass=%s %s", this.getName(), payloadData)); } NettySctpChannelInboundHandlerAdapter handler = checkSocketIsOpen(); final ByteBuf byteBuf...
python
def unicode_convert(obj): """Converts unicode objects to anscii. Args: obj (object): The object to convert. Returns: The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained. """ try: if isinstance(obj, dict): return ...
java
protected void onTextChanged(String s) { if (!isFloatOnFocusEnabled()) { if (s.length() == 0) { anchorLabel(); } else { floatLabel(); } } if (editTextListener != null) editTextListener.onTextChanged(this, s); }
java
public void displayUseCases() { System.out.println(); for (int i = 0; i < useCases.size(); i++) { System.out.println("[" + i + "] " + ((UseCase) useCases.get(i)).getDescription()); } }
java
public Response<Double> incrByFloat(final String key, final double increment) { return new PipelineOperation<Double>() { @Override Response<Double> execute(Pipeline jedisPipeline) throws DynoException { return jedisPipeline.incrByFloat(key, increment); } }.execute(key, OpName.INCRBYFLOAT); }
python
def pylxd_save_object(obj): ''' Saves an object (profile/image/container) and translate its execpetion on failure obj : The object to save This is an internal method, no CLI Example. ''' try: obj.save() except pylxd.exceptions.LXDAPIException as e: raise Command...
java
String rrToString() { StringBuffer sb = new StringBuffer(); sb.append(hashAlg); sb.append(' '); sb.append(flags); sb.append(' '); sb.append(iterations); sb.append(' '); if (salt == null) sb.append('-'); else sb.append(base16.toString(salt)); sb.append(' '); sb.append(b32.toString(next)); if (!types.emp...
java
@Override public String getResourcesParameter(HttpServletRequest request, String skinXml, String name) { final Resources skinResources = this.getResources(request, skinXml); if (skinResources == null) { logger.warn("Could not find skin file " + skinXml); return null; ...
python
def _chunk_iter(self): """Iterator over the blob file.""" for chunk_offset in self._chunk_offsets(): yield self._download_chunk(chunk_offset=chunk_offset, chunk_size=self._chunk_size)
python
def reset_cooldown(self, ctx): """Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) ...
python
def transformer_base_vq1_16_nb1_packed_dan_b01_scales(): """Set of hyperparameters.""" hparams = transformer_base_vq_ada_32ex_packed() hparams.use_scales = int(True) hparams.moe_num_experts = 16 hparams.moe_k = 1 hparams.beta = 0.1 hparams.ema = False return hparams
python
def get_or_create_in_transaction(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): ''' Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no existing re...
python
def construct_sls_str(self, node): ''' Build the SLSString. ''' # Ensure obj is str, not py2 unicode or py3 bytes obj = self.construct_scalar(node) if six.PY2: obj = obj.encode('utf-8') return SLSString(obj)
python
def detect(self, fstring, fname=None): """Have a stab at most files.""" if fname is not None and '.' in fname: extension = fname.rsplit('.', 1)[1] if extension in {'pdf', 'html', 'xml'}: return False return True
python
def _init_solc_binary(version): """Figure out solc binary and version. Only proper versions are supported. No nightlies, commits etc (such as available in remix). """ if not version: return os.environ.get("SOLC") or "solc" # tried converting input to semver, seemed...
python
def Message(message, title='FontParts', informativeText=""): """ An message dialog. Optionally a `message`, `title` and `informativeText` can be provided. :: from fontParts.ui import Message print(Message("This is a message")) """ return dispatcher["Message"](message=message, ...
java
private Node tryFoldStringSubstr(Node n, Node stringNode, Node arg1) { checkArgument(n.isCall()); checkArgument(stringNode.isString()); checkArgument(arg1 != null); int start; int length; String stringAsString = stringNode.getString(); Double maybeStart = NodeUtil.getNumberValue(arg1); ...
python
def get_drop_index_sql(self, index, table=None): """ Returns the SQL to drop an index from a table. :param index: The index :type index: Index or str :param table: The table :type table: Table or str or None :rtype: str """ if isinstance(index, ...
java
public ElementMenuItem registerMenu(String path, String action) { ElementMenuItem menu = getElement(path, getDesktop().getMenubar(), ElementMenuItem.class); menu.setAction(action); return menu; }
python
def retrieve(self, request, project, pk=None): """ GET method implementation for detail view Return a single job with log_references and artifact names and links to the artifact blobs. """ try: job = Job.objects.select_related( *self._default_...
java
public void setGrossRate(com.google.api.ads.admanager.axis.v201811.Money grossRate) { this.grossRate = grossRate; }
java
@SuppressWarnings({ "rawtypes", "unchecked", "null" }) public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException { ArrayList headers = new ArrayList(); String name = null; StringBuffer value = null; for (;;) { String line = Http...
python
def parse_parameters(self, parameters): """Parses and sets parameters in the model.""" self.parameters = [] for param_name, param_value in parameters.items(): p = Parameter(param_name, param_value) if p: self.parameters.append(p)
java
public static <T> java.util.concurrent.ScheduledFuture<T> delay(final Supplier<T> function, final int delayMilliseconds) { final java.util.concurrent.ScheduledExecutorService scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); final java.util.concurrent.Sch...
java
public static cachecontentgroup[] get(nitro_service service) throws Exception{ cachecontentgroup obj = new cachecontentgroup(); cachecontentgroup[] response = (cachecontentgroup[])obj.get_resources(service); return response; }
python
def loop(self, sleep_time=1, callback=None): """ Goes into a blocking IO loop. If polling is used, the sleep_time is the interval, in seconds, between polls. """ self.log("No supported libraries found: using polling-method.") self._running = True self.trigger_ini...
python
def get_qpimage_raw(self, idx=0): """Return QPImage without background correction""" # Load experimental data with SingleTifHolo._get_tif(self.path) as tf: holo = tf.pages[0].asarray() meta_data = copy.copy(self.meta_data) qpi = qpimage.QPImage(data=(holo), ...
java
public TypeName getTypeParameter() { if (typeName instanceof ParameterizedTypeName) { ParameterizedTypeName temp = (ParameterizedTypeName) typeName; return temp.typeArguments.get(0); } else if (typeName instanceof ArrayTypeName) { ArrayTypeName temp = (ArrayTypeName) typeName; return temp.componentType;...
python
def export(self, timestamp=None): """ Get the current notebook data and export. """ if self._timestamp is None: raise Exception("No timestamp set. Has the archive been initialized?") if self.skip_notebook_export: super(NotebookArchive, self).export(timesta...
java
public static final Mem word_ptr_abs(long target, long disp, SEGMENT segmentPrefix) { return _ptr_build_abs(target, disp, segmentPrefix, SIZE_WORD); }
python
def validate_token(self, token): '''retrieve a subject based on a token. Valid means we return a participant invalid means we return None ''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.token == token).first() if p is not None: if p.toke...
java
@Override protected LocalDate parse(final String string, final DateTimeFormatter formatter) { return LocalDate.parse(string, formatter); }
python
def number_of_unique_magnetic_sites(self, symprec=1e-3, angle_tolerance=5): """ :param symprec (float): same as in SpacegroupAnalyzer :param angle_tolerance (float): same as in SpacegroupAnalyzer :return (int): Number of symmetrically-distinct magnetic sites present in structure....
java
public String convertIfcTransportElementTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public void readFrom(final InputStream in) throws IOException { pointer = 0; size = 0; int n; do { n = in.read(buffer, size, buffer.length - size); if (n > 0) { size += n; } resizeIfNeeded(); } while (n >= 0); }
python
def show(self, command, delim=';'): """ Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor. :param command: Command to be executed :param delim: Custom delimiter. Default value: ';' :raise pyPluribus.exceptions.TimeoutError: when execution...
python
def breaks_from_bins(x_range, bins=30, center=None, boundary=None): """ Calculate breaks given binwidth Parameters ---------- x_range : array_like Range over with to calculate the breaks. Must be of size 2. bins : int Number of bins center : float The center ...
java
public void writeInitField() { Record recLogicFile = this.getRecord(LogicFile.LOGIC_FILE_FILE); try { String strClassName; Record recClassInfo = this.getMainRecord(); FieldData recFieldData = (FieldData)this.getRecord(FieldData.FIELD_DATA_FILE); strC...
java
public FutureData<DataSiftResult> deleteLimit(String identity, String service) { if (identity == null) { throw new IllegalArgumentException("An identity is required"); } if (service == null) { throw new IllegalArgumentException("A service is required"); } ...
java
public static DoubleStreamEx zip(double[] first, double[] second, DoubleBinaryOperator mapper) { return of(new RangeBasedSpliterator.ZipDouble(0, checkLength(first.length, second.length), mapper, first, second)); }
python
def organizations_create_or_update(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organizations#create-or-update-organization" api_path = "/api/v2/organizations/create_or_update.json" return self.call(api_path, method="POST", data=data, **kwargs)
java
protected Object resolveObject(Object objectToResolve) { final String methodName = "resolveObject"; if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, methodName, new Object[] { object...
java
public static Vector from (XY from, XY to) { return new Vector(to.x() - from.x(), to.y() - from.y()); }
java
public void updateShownOptions(boolean showModeSwitch, boolean showAddKeyOption) { if (showModeSwitch != m_showModeSwitch) { m_upperLeftComponent.removeAllComponents(); m_upperLeftComponent.addComponent(m_languageSwitch); if (showModeSwitch) { m_upperLeftComp...
java
public CloudJobSchedule getJobSchedule(String jobScheduleId, DetailLevel detailLevel) throws BatchErrorException, IOException { return getJobSchedule(jobScheduleId, detailLevel, null); }
java
public Relation<K,V> create(Relation<K,V> r) { // default implementation Relation<K,V> r2 = this.create(); for(K key : r.keys()) { r2.addAll(key, r.getValues(key)); } return r2; }
python
def render_to_response(self, obj, **response_kwargs): """ Returns an ``HttpResponse`` object instance with Content-Type: application/json. The response body will be the return value of ``self.serialize(obj)`` """ return HttpResponse(self.serialize(obj), content_type='app...
java
public Rectangle getContainingBlock() { if (cbox instanceof Viewport) //initial containing block { Rectangle visible = ((Viewport) cbox).getVisibleRect(); return new Rectangle(0, 0, visible.width, visible.height); } else //static or relative position ...
java
public static XContentBuilder marshall(ApiDefinitionBean bean) throws StorageException { try (XContentBuilder builder = XContentFactory.jsonBuilder()) { preMarshall(bean); builder .startObject() .field("data", bean.getData()) .endObject...
python
def eject_virtual_media(self, device): """Ejects the Virtual Media image if one is inserted. :param device: virual media device :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the device is not valid. """ self._validate_virtual_media(device) ...
python
def _condition_as_text(lambda_inspection: icontract._represent.ConditionLambdaInspection) -> str: """Format condition lambda function as reST.""" lambda_ast_node = lambda_inspection.node assert isinstance(lambda_ast_node, ast.Lambda) body_node = lambda_ast_node.body text = None # type: Optional[s...
java
public ItemRequest<Section> createInProject(String project) { String path = String.format("/projects/%s/sections", project); return new ItemRequest<Section>(this, Section.class, path, "POST"); }
python
def log_startup_info(): """Log info about the current environment.""" LOG.always("Starting mongo-connector version: %s", __version__) if "dev" in __version__: LOG.warning( "This is a development version (%s) of mongo-connector", __version__ ) LOG.always("Python version: %s", ...
python
def filter(self, criteria, applyto='measurement', ID=None): """ Filter measurements according to given criteria. Retain only Measurements for which criteria returns True. TODO: add support for multiple criteria Parameters ---------- criteria : callable ...
java
public void setAndroidPaths(java.util.Collection<String> androidPaths) { if (androidPaths == null) { this.androidPaths = null; return; } this.androidPaths = new java.util.ArrayList<String>(androidPaths); }
java
public void setGroupByFields(String... groupByFields) throws TupleMRException { failIfEmpty(groupByFields, "GroupBy fields can't be null or empty"); failIfEmpty(schemas, "No schemas defined"); failIfNotNull(this.groupByFields, "GroupBy fields already set : " + Arrays.toString(groupByFields)); for (Strin...
python
def plot_sfs_scaled(*args, **kwargs): """Plot a scaled site frequency spectrum. Parameters ---------- s : array_like, int, shape (n_chromosomes,) Site frequency spectrum. yscale : string, optional Y axis scale. bins : int or array_like, int, optional Allele count bins. ...
java
public static CmsImageScaler getDownScaler(CmsObject cms, String rootPath) { if (m_downScaler == null) { // downscaling is not configured at all return null; } // try to read the image.size property from the parent folder String parentFolder = CmsResource.getPare...
python
def ConfigureEmails(config): """Guides the user through email setup.""" print("\n\n-=GRR Emails=-\n" "GRR needs to be able to send emails for various logging and\n" "alerting functions. The email domain will be appended to GRR\n" "usernames when sending emails to users.\n") existing_log_d...
java
public static <K, V, E extends Exception> boolean removeIf(final Map<K, V> map, final Try.Predicate<? super Map.Entry<K, V>, E> filter) throws E { List<K> keysToRemove = null; for (Map.Entry<K, V> entry : map.entrySet()) { if (filter.test(entry)) { if (keysToRemove == n...
java
public Observable<ServiceResponseWithHeaders<AutoScaleRun, PoolEvaluateAutoScaleHeaders>> evaluateAutoScaleWithServiceResponseAsync(String poolId, String autoScaleFormula) { if (this.client.batchUrl() == null) { throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and can...
java
public static void initTLSv11orUpper() throws NoSuchAlgorithmException, KeyManagementException, IOException { final SSLSocket socket = (SSLSocket) SSLContext.getDefault().getSocketFactory().createSocket(); if (isTLSv11orUpperEnabled(socket)) { return; } final String[] support...
java
public void broadcast(String name, Tree payload) { eventbus.broadcast(name, payload, null, false); }
python
def _filter_if(self, node): """ Check if the node is a condtional node where there is an external call checked Heuristic: - The call is a IF node - It contains a, external call - The condition is the negation (!) Th...
java
public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() { if (bounds == null) { bounds = new ReadOnlyObjectWrapper<>(getBounds()); addStateEventHandler(MapStateEventType.idle, () -> { bounds.set(getBounds()); }); } return bounds.get...
java
public static long parseOctal(byte[] header, int offset, int length) throws InvalidHeaderException { long result = 0; boolean stillPadding = true; int end = offset + length; for (int i = offset; i < end; ++i) { if (header[i] == 0) { break; ...
python
def body_blocks(soup): """ Note: for some reason this works and few other attempted methods work Search for certain node types, find the first nodes siblings of the same type Add the first sibling and the other siblings to a list and return them """ nodenames = body_block_nodenames() body_b...
python
def plan_branches(self, plan_key, expand=None, favourite=False, clover_enabled=False, max_results=25): """api/1.0/plan/{projectKey}-{buildKey}/branch""" resource = 'plan/{}/branch'.format(plan_key) return self.base_list_call(resource, expand, favourite, clover_enabled, max_results, ...
java
public static <T, K> JacksonDBCollection<T, K> wrap(DBCollection dbCollection, Class<T> type, Class<K> keyType, Class<?> view) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withView(view)); MongoJacksonMapperModule.con...
java
@Override public byte[] createSignedAndZippedPkPassArchive(PKPass pass, IPKPassTemplate passTemplate, PKSigningInformation signingInformation) throws PKSigningException { return this.createSignedAndZippedPersonalizedPkPassArchive(pass, null, passTemplate, signingInformation); }
java
public void addFieldReferences(TableDefinition tableDef, Collection<String> fieldNames) { for (String fieldName : fieldNames) { addColumn(SpiderService.termsStoreName(tableDef), FIELD_REGISTRY_ROW_KEY, fieldName); } }
python
def condor_stop(external_id): """ Stop running condor job and return a failure_message if this fails. """ failure_message = None try: check_call(('condor_rm', external_id)) except CalledProcessError: failure_message = "condor_rm failed" except Exception as e: "err...
python
def get_eidos_bayesian_scorer(prior_counts=None): """Return a BayesianScorer based on Eidos curation counts.""" table = load_eidos_curation_table() subtype_counts = {'eidos': {r: [c, i] for r, c, i in zip(table['RULE'], table['Num correct'], ta...
python
def create_project(self, project_path): """ Create Trionyx project in given path :param str path: path to create project in. :raises FileExistsError: """ shutil.copytree(self.project_path, project_path) self.update_file(project_path, 'requirements.txt', { ...
python
def mach60(msg): """Aircraft MACH number Args: msg (String): 28 bytes hexadecimal message (BDS60) string Returns: float: MACH number """ d = hex2bin(data(msg)) if d[23] == '0': return None mach = bin2int(d[24:34]) * 2.048 / 512.0 return round(mach, 3)
python
def createEditor(self, delegate, parent, option): """ Creates a IntCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return IntCtiEditor(self, delegate, parent=parent)
java
public double get(int row, int col) { checkIndices(row, col); int index = getIndex(row, col); return matrix[index]; }