language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services, AdWordsSession session, Long adGroupId) throws ApiException, RemoteException { // Get the AdGroupCriterionService. AdGroupCriterionServiceInterface criterionService = services.get(session, AdGroupCriterionServiceI...
python
def checkIfRemoteIsNewer(self, localfile, remote_size, remote_modify): """ Overrides checkIfRemoteIsNewer in Source class :param localfile: str file path :param remote_size: str bytes :param remote_modify: str last modify date in the form 20160705042714 :return: boolean ...
java
public void execute() throws ActivityException { EventWaitInstance received = registerWaitEvents(false, true); if (received!=null) { setReturnCodeAndExitStatus(received.getCompletionCode()); processMessage(getExternalEventInstanceDetails(received.getMessageDocumentId())); ...
python
def update(self, key, value): """ :param key: a string :value: a string """ if not is_string(key): raise Exception("Key must be string") # if len(key) > 32: # raise Exception("Max key length is 32") if not is_string(value): ra...
java
public int call(String sql, Object[] params) throws Exception { return call(sql, Arrays.asList(params)); }
python
def sync_in_records(self, force=False): """Synchronize from files to records""" self.log('---- Sync Files ----') for f in self.build_source_files: f.record_to_objects() # Only the metadata needs to be driven to the objects, since the other files are used as code, # ...
python
def IOWR(type, nr, size): """ An ioctl with both read an writes parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size))
python
def _loadf16(ins): """ Load a 32 bit (16.16) fixed point value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. """ output = _f16_oper(ins.quad[2]) output.append('push de') output.append('push hl') return output
java
protected ProgressUpdate newProgressUpdate(QueryBatch batch, long startTime, long totalForThisUpdate, double timeSoFar) { return new SimpleProgressUpdate(batch, startTime, totalForThisUpdate, timeSoFar); }
java
@Override public void execute(final ActionEvent event) { ExampleData data = (ExampleData) event.getActionObject(); WComponent source = (WComponent) event.getSource(); TreePicker picker = WebUtilities.getAncestorOfClass(TreePicker.class, source); picker.selectExample(data); MenuPanel panel = WebUtilities.ge...
python
def get_normalized_definition(self): """Please refer to the specification for details about normalized definitions.""" cast_mode = 'saturated' if self.cast_mode == PrimitiveType.CAST_MODE_SATURATED else 'truncated' primary_type = { PrimitiveType.KIND_BOOLEAN: 'bool', Prim...
java
public static <T> Optional<T> of(T value) { return value == null ? (Optional<T>) EMPTY : new Optional<>(value); }
python
def slice_for_qubits_equal_to(target_qubit_axes: Sequence[int], little_endian_qureg_value: int, *, # Forces keyword args. num_qubits: int = None ) -> Tuple[Union[slice, int, 'ellipsis'], ...]: ""...
python
def fetch_samples(proj, selector_attribute=None, selector_include=None, selector_exclude=None): """ Collect samples of particular protocol(s). Protocols can't be both positively selected for and negatively selected against. That is, it makes no sense and is not allowed to specify both selector_incl...
java
@Override public ImageSource apply(ImageSource input) { if (input.isGrayscale()) { return input; } if (!isAlgorithm) { double r, g, b, gray; for (int i = 0; i < EffectHelper.getSize(input); i++) { r = EffectHelper.getRed(i, input)...
python
def get_subclass(self): """ get_subclass """ strbldr = """ class IArguments(Arguments): \"\"\" IArguments \"\"\" def __init__(self, doc=None, validateschema=None, argvalue=None, yamlstr=None, yamlfile=None, parse...
python
def getOutputName(self,name): """ Return the name of the file or PyFITS object associated with that name, depending on the setting of self.inmemory. """ val = self.outputNames[name] if self.inmemory: # if inmemory was turned on... # return virtualOutput object saved w...
java
static void setCurrentScene(@NonNull View view, @Nullable Scene scene) { view.setTag(R.id.current_scene, scene); }
java
@Broadcast(writeEntity = false) @POST @Produces("application/json") public Response broadcast(Message message) { return new Response(message.getAuthor(), message.getMessage()); }
python
def parse_options(self, kwargs): """Validate the provided kwargs and return options as json string.""" kwargs = {camelize(key): value for key, value in kwargs.items()} for key in kwargs.keys(): assert key in self.valid_options, ( 'The option {} is not in the available...
java
public Token peek() { if (!splitTokens.isEmpty()) { return splitTokens.peek(); } final var value = stringIterator.peek(); if (argumentEscapeEncountered) { return new ArgumentToken(value); } if (Objects.equals(value, argumentTerminator)) { ...
python
def _clean(c): """ Nuke docs build target directory so next build is clean. """ if isdir(c.sphinx.target): rmtree(c.sphinx.target)
java
public PutItemResponse putItem(PutItemRequest request) { checkNotNull(request, "request should not be null."); InternalRequest httpRequest = createRequestUnderInstance(HttpMethodName.PUT, MolaDbConstants.URI_TABLE, request.getTableName(), MolaDbConstants.U...
java
@Override public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) { return commerceTierPriceEntryPersistence.findWithDynamicQuery(dynamicQuery); }
java
public EKBCommit addUpdate(Object update) { if (update != null) { checkIfModel(update); updates.add((OpenEngSBModel) update); } return this; }
java
public int commandToDocType(String strCommand) { if (MessageLog.MESSAGE_SCREEN.equalsIgnoreCase(strCommand)) return MessageLog.MESSAGE_SCREEN_MODE; if (MessageLog.SOURCE_SCREEN.equalsIgnoreCase(strCommand)) return MessageLog.SOURCE_SCREEN_MODE; return super.commandToD...
java
public static boolean isContainmentProxy(DatabindContext ctxt, EObject owner, EObject contained) { if (contained.eIsProxy()) return true; Resource ownerResource = EMFContext.getResource(ctxt, owner); Resource containedResource = EMFContext.getResource(ctxt, contained); return ownerResource != null && owner...
java
private byte[] doEncryptionOrDecryption(byte[] crypt, Key key, int mode) { Cipher rsaCipher; try { rsaCipher = Cipher.getInstance(CIPHER); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw SeedException.wrap(e, CryptoErrorCode.UNABLE_TO_GET_CIPHER) ...
python
def add_param_summary(*summary_lists, **kwargs): """ Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type...
python
def start_optimisation(self, rounds: int, max_angle: float, max_distance: float, temp: float=298.15, stop_when=None, verbose=None): """Starts the loop fitting protocol. Parameters ---------- rounds : int The number of Mon...
java
public static StringBuilder join(StringBuilder builder, String delim, Object... objects) { return join(builder, delim, Arrays.asList(objects)); }
python
def get_default_config(self): """ Returns the default collector settings """ config = super(NfsCollector, self).get_default_config() config.update({ 'path': 'nfs' }) return config
java
public static sslcrl_binding get(nitro_service service, String crlname) throws Exception{ sslcrl_binding obj = new sslcrl_binding(); obj.set_crlname(crlname); sslcrl_binding response = (sslcrl_binding) obj.get_resource(service); return response; }
java
public static <D extends CalendarVariant<D>> Factory<D> on( CalendarFamily<D> family, String variant ) { Class<D> chronoType = family.getChronoType(); TimeLine<D> timeLine = family.getTimeLine(variant); CalendarSystem<D> calsys = family.getCalendarSystem(variant); re...
java
public static String removeModifierSuffix(String fullName) { int indexOfFirstOpeningToken = fullName.indexOf(MODIFIER_OPENING_TOKEN); if (indexOfFirstOpeningToken == -1) { return fullName; } int indexOfSecondOpeningToken = fullName.lastIndexOf(MODIFIER_OPENING_TOKEN); ...
python
def write_out(self, message, verbosity_level=1): """ Convenient method for outputing. """ if self.verbosity and self.verbosity >= verbosity_level: sys.stdout.write(smart_str(message)) sys.stdout.flush()
python
def execute(self, arg_list): """Main function to parse and dispatch commands by given ``arg_list`` :param arg_list: all arguments provided by the command line :param type: list """ arg_map = self.parser.parse_args(arg_list).__dict__ command = arg_map.pop(self._COMMAND_F...
python
def get_chromosomes_summary(snps): """ Summary of the chromosomes of SNPs. Parameters ---------- snps : pandas.DataFrame Returns ------- str human-readable listing of chromosomes (e.g., '1-3, MT'), empty str if no chromosomes """ if isinstance(snps, pd.DataFrame): ...
python
def ray_spheres_intersection(origin, direction, centers, radii): """Calculate the intersection points between a ray and multiple spheres. **Returns** intersections distances Ordered by closest to farther """ b_v = 2.0 * ((origin - centers) * direction).sum(axis=1) c_v = (...
python
def get_dssp_annotations(self, representative_only=True, force_rerun=False): """Run DSSP on structures and store calculations. Annotations are stored in the protein structure's chain sequence at: ``<chain_prop>.seq_record.letter_annotations['*-dssp']`` Args: representative_...
python
def param_request_read_encode(self, target_system, target_component, param_id, param_index): ''' Request to read the onboard parameter with the param_id string id. Onboard parameters are stored as key[const char*] -> value[float]. This allows to send a par...
java
protected ObjectElement getObjectElement(IResource resource, SecurityEventObjectLifecycleEnum lifecycle, byte[] query) throws InstantiationException, IllegalAccessException { String resourceType = resource.getResourceName(); if (myAuditableResources.containsKey(resourceType)) { log.debug("Found auditable resour...
java
public static UploadAttachmentResponse postUploadAttachment( StringEntity input) { String pageToken = FbBotMillContext.getInstance().getPageToken(); // If the page token is invalid, returns. if (!validatePageToken(pageToken)) { return null; } String url = FbBotMillNetworkConstants.FACEBOOK_BASE_URL ...
java
public int decide(final LoggingEvent event) { calendar.setTimeInMillis(event.timeStamp); // // get apparent number of milliseconds since midnight // (ignores extra or missing hour on daylight time changes). // long apparentOffset = calendar.get(Calendar.HOUR_OF_DAY) * HOUR_MS + ca...
java
public void identify( final @Nullable String userId, final @Nullable Traits newTraits, final @Nullable Options options) { assertNotShutdown(); if (isNullOrEmpty(userId) && isNullOrEmpty(newTraits)) { throw new IllegalArgumentException("Either userId or some traits must be provided."); ...
java
public static String createSubsetPrefix() { StringBuilder sb = new StringBuilder(8); for (int k = 0; k < 6; ++k) { sb.append( (char)(Math.random() * 26 + 'A') ); } sb.append("+"); return sb.toString(); }
java
@Override public void authorizeEJB(EJBRequestData request, Subject subject) throws EJBAccessDeniedException { auditManager = new AuditManager(); Object req = auditManager.getHttpServletRequest(); Object webRequest = auditManager.getWebRequest(); String realm = auditManager.getRealm()...
java
@Override public Optional<T> findById(final ID id) { return arangoOperations.find(id, domainClass); }
java
public ServiceFuture<ComputePolicyInner> createOrUpdateAsync(String resourceGroupName, String accountName, String computePolicyName, CreateOrUpdateComputePolicyParameters parameters, final ServiceCallback<ComputePolicyInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseA...
java
private <T> InternalProviderImpl<? extends T> getUnBoundProvider(Class<T> clazz, String bindingName) { return getInternalProvider(clazz, bindingName, false); }
java
static Predicate<CtClass> createExcludePredicate(@Nullable final String[] classes) { final Set<PathMatcher> excludeSet; if (classes != null && classes.length != 0) { excludeSet = createPathMatcherSet(classes); } else { return ctClass -> false; } return cre...
python
def lazy_imap(data_processor, data_generator, n_cpus=1, stepsize=None): """A variant of multiprocessing.Pool.imap that supports lazy evaluation As with the regular multiprocessing.Pool.imap, the processes are spawned off asynchronously while the results are returned in order. In contrast to multiproces...
java
public static void transpose(DMatrixSparseCSC A , DMatrixSparseCSC C , @Nullable IGrowArray gw ) { int []work = adjust(gw,A.numRows,A.numRows); C.reshape(A.numCols,A.numRows,A.nz_length); // compute the histogram for each row in 'a' int idx0 = A.col_idx[0]; for (int j = 1; j <= ...
python
def process(self, batch): """Process a single, partitioned query or read. :type batch: mapping :param batch: one of the mappings returned from an earlier call to :meth:`generate_query_batches`. :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`...
python
def h(values): """ Function calculates entropy. values: list of integers """ ent = np.true_divide(values, np.sum(values)) return -np.sum(np.multiply(ent, np.log2(ent)))
java
public IFeatureAlphabet rebuildFeatureAlphabet(String name) { IFeatureAlphabet alphabet = null; if (maps.containsKey(name)) { alphabet = (IFeatureAlphabet) maps.get(name); alphabet.clear(); }else{ return buildFeatureAlphabet(name,defaultFeatureType); } return alphabet; }
python
def django_js(context, jquery=True, i18n=True, csrf=True, init=True): '''Include Django.js javascript library in the page''' return { 'js': { 'minified': not settings.DEBUG, 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), 'csrf': _boolean(csrf), ...
java
void handleFileItemClick(ItemClickEvent event) { if (isEditing()) { stopEdit(); } else if (!event.isCtrlKey() && !event.isShiftKey()) { // don't interfere with multi-selection using control key String itemId = (String)event.getItemId(); CmsUUID structure...
java
public CRestBuilder extractsEntityAuthParamsWith(String entityContentType, EntityParamExtractor entityParamExtractor){ this.httpEntityParamExtrators.put(entityContentType, entityParamExtractor); return this; }
java
public void getWvWMatchOverview(int worldID, Callback<WvWMatchOverview> callback) throws NullPointerException { gw2API.getWvWMatchOverviewUsingWorld(Integer.toString(worldID)).enqueue(callback); }
java
public Grammar register(@NonNull ParserTokenType type, @NonNull PrefixHandler handler) { prefixHandlers.put(type, handler); return this; }
java
@XmlElementDecl(namespace = "http://www.opengis.net/citygml/relief/1.0", name = "_GenericApplicationPropertyOfTinRelief") public JAXBElement<Object> create_GenericApplicationPropertyOfTinRelief(Object value) { return new JAXBElement<Object>(__GenericApplicationPropertyOfTinRelief_QNAME, Object.class, null, ...
java
public void add(MultidimensionalReward other) { for (Map.Entry<Integer, Float> entry : other.map.entrySet()) { Integer dimension = entry.getKey(); Float reward_value = entry.getValue(); this.add(dimension.intValue(), reward_value.floatValue()); } }
java
@Deprecated public java.util.List<Clip> getComposition() { if (composition == null) { composition = new com.amazonaws.internal.SdkInternalList<Clip>(); } return composition; }
java
private void checkNonNullParam(Location location, ConstantPoolGen cpg, TypeDataflow typeDataflow, InvokeInstruction invokeInstruction, BitSet nullArgSet, BitSet definitelyNullArgSet) { if (inExplicitCatchNullBlock(location)) { return; } boolean caught = inIndirectCatchNu...
python
def write_position(fp, position, value, fmt='I'): """ Writes a value to the specified position. :param fp: file-like object :param position: position of the value marker :param value: value to write :param fmt: format of the value :return: written byte size """ current_position = fp...
python
def sjuncChunk(key, chunk): """ Parse Super Junction (SJUNC) Chunk Method """ schunk = chunk[0].strip().split() result = {'sjuncNumber': schunk[1], 'groundSurfaceElev': schunk[2], 'invertElev': schunk[3], 'manholeSA': schunk[4], 'inletCode': s...
java
@Override public T findOne(final I id) { return inTransaction(new Callable<T>() { @Override public T call() throws Exception { return entityManager.find(entity, id); } }); }
java
private boolean isImplementationOf(@SlashedClassName String clsName, JavaClass inf) { try { if (clsName.startsWith("java/lang/")) { return false; } JavaClass cls = Repository.lookupClass(clsName); return isImplementationOf(cls, inf); } ca...
java
protected void abortPublishJob(CmsUUID userId, CmsPublishJobEnqueued publishJob, boolean removeJob) throws CmsException, CmsPublishException { // abort event should be raised before the job is removed implicitly m_listeners.fireAbort(userId, publishJob); if ((m_currentPublishThread == null...
java
private void initializeColAndRowComponentLists() { colComponents = new List[getColumnCount()]; for (int i = 0; i < getColumnCount(); i++) { colComponents[i] = new ArrayList<Component>(); } rowComponents = new List[getRowCount()]; for (int i = 0; i < getRowCount(); i+...
python
def delete(self, cascade=False, delete_shares=False): """ Deletes the video. """ if self.id: self.connection.post('delete_video', video_id=self.id, cascade=cascade, delete_shares=delete_shares) self.id = None
python
def get_sdc_by_ip(self, ip): """ Get ScaleIO SDC object by its ip :param name: IP address of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified IP found :rtype: SDC object """ if self.conn.is_ip_addr(ip): for sdc in self.sdc...
python
def _checkAndConvertIndex(self, index): """Check integer index, convert from less than zero notation """ if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
java
public final Mono<ByteBuffer> asByteBuffer() { return handle((bb, sink) -> { try { sink.next(bb.nioBuffer()); } catch (IllegalReferenceCountException e) { sink.complete(); } }); }
java
public void refreshCredentials() { if (this.credsProvider == null) return; try { AlibabaCloudCredentials creds = this.credsProvider.getCredentials(); this.accessKeyID = creds.getAccessKeyId(); this.accessKeySecret = creds.getAccessKeySecret(); ...
java
@Override public com.liferay.commerce.model.CommerceOrderItem getCommerceOrderItem( long commerceOrderItemId) throws com.liferay.portal.kernel.exception.PortalException { return _commerceOrderItemLocalService.getCommerceOrderItem(commerceOrderItemId); }
python
def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None): """The VAN decoder. Args: x: The analogy information to decode. skip_connections: The encoder layers which can be used as skip connections. output_shape: The shape of the desired output image. first_depth: The depth of th...
python
def comparator_eval(comparator_params): """Gets BUFF score for interaction between two AMPAL objects """ top1, top2, params1, params2, seq1, seq2, movements = comparator_params xrot, yrot, zrot, xtrans, ytrans, ztrans = movements obj1 = top1(*params1) obj2 = top2(*params2) obj2.rotate(xrot, ...
python
def dale_chall(self, diff_count, words, sentences): """Calculate Dale-Chall readability score.""" pdw = diff_count / words * 100 asl = words / sentences raw = 0.1579 * (pdw) + 0.0496 * asl if pdw > 5: return raw + 3.6365 return raw
python
def local_position_ned_cov_encode(self, time_boot_ms, time_utc, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (ae...
python
def do_reconfig(self, params): """ \x1b[1mNAME\x1b[0m reconfig - Reconfigures a ZooKeeper cluster (adds/removes members) \x1b[1mSYNOPSIS\x1b[0m reconfig <add|remove> <arg> [from_config] \x1b[1mDESCRIPTION\x1b[0m reconfig add <members> [from_config] adds the given members (i...
python
def _get_prop_from_modelclass(modelclass, name): """Helper for FQL parsing to turn a property name into a property object. Args: modelclass: The model class specified in the query. name: The property name. This may contain dots which indicate sub-properties of structured properties. Returns: ...
python
def line_cross(x1, y1, x2, y2, x3, y3, x4, y4): """ 判断两条线段是否交叉 """ # out of the rect if min(x1, x2) > max(x3, x4) or max(x1, x2) < min(x3, x4) or \ min(y1, y2) > max(y3, y4) or max(y1, y2) < min(y3, y4): return False # same slope rate if ((y1 - y2) * (x3 - x4) == (x1 - x2) * (y3 - y4...
python
def get_value(self, row, column): """Return the value of the DataFrame.""" # To increase the performance iat is used but that requires error # handling, so fallback uses iloc try: value = self.df.iat[row, column] except OutOfBoundsDatetime: value = ...
java
public OvhBackendHttp serviceName_http_farm_POST(String serviceName, OvhBalanceHTTPEnum balance, String displayName, Long port, OvhBackendProbe probe, OvhStickinessHTTPEnum stickiness, Long vrackNetworkId, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/http/farm"; StringBuilder sb ...
python
def save_image(self, outname): """ Save the image data. This is probably only useful if the image data has been blanked. Parameters ---------- outname : str Name for the output file. """ hdu = self.global_data.img.hdu hdu.data = self.g...
python
def find_divisors(n): """ Find all the positive divisors of the given integer n. Args: n (int): strictly positive integer Returns: A generator of all the positive divisors of n Raises: TypeError: if n is not an integer ValueError: if n is negative """ if not...
python
def imgAverage(images, copy=True): ''' returns an image average works on many, also unloaded images minimises RAM usage ''' i0 = images[0] out = imread(i0, dtype='float') if copy and id(i0) == id(out): out = out.copy() for i in images[1:]: out += imread...
python
def _validate_config(config_path): ''' Validate that the configuration file exists and is readable. :param str config_path: The path to the configuration file for the aptly instance. :return: None :rtype: None ''' log.debug('Checking configuration file: %s', config_path) if not os.pat...
java
public void addHandler(Handler handler, Stage stage) { if (!startStopLock.tryLock()) { throw new ISE("Cannot add a handler in the process of Lifecycle starting or stopping"); } try { if (!state.get().equals(State.NOT_STARTED)) { throw new ISE("Cannot add a handler after the Lifecycle h...
java
public String decode(byte[] encodedString, int offset, int length) throws IOException { return new String(encodedString, offset, length, encoding); }
python
def project(self, term_doc_mat, x_dim=0, y_dim=1): ''' Returns a projection of the categories :param term_doc_mat: a TermDocMatrix :return: CategoryProjection ''' return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat), ...
java
private void populateStep2() { this.insertRoadmapItem(1, true, I18nLabelsLoader.REPORT_STEP_FALSE_ERRORS, 2); // Bad intervention int y = 6; this.insertFixedTextBold(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, I18nLabelsLoader.REPORT_STEP_FALSE_ERRORS); y += 1...
python
def build_options(self): """The package build options. :returns: :func:`set` of build options strings. """ if self.version.build_metadata: return set(self.version.build_metadata.split('.')) else: return set()
python
def get_all(self, key, fallback=None): """returns all header values for given key""" if key in self.headers: value = self.headers[key] else: value = fallback or [] return value
java
public void put(String name, String value) { List<String> list = new ArrayList<>(); list.add(value); getMap().put(name, list); }
python
async def create_key(wallet_handle: int, key_json: str) -> str: """ Creates keys pair and stores in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param key_json: Key information as json. Example: { "seed": string, (optional) Seed that a...
java
public Date getTime() { if (utc == null) { return null; } Date date = null; try { date = XmppDateTime.parseDate(utc); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error getting local time", e); } return date; }
java
private static List<String> readLines(Option option) { String optionStr = GsonUtil.format(option); InputStream is = null; InputStreamReader iReader = null; BufferedReader bufferedReader = null; List<String> lines = new ArrayList<String>(); String line; try { ...