language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
static List<IDataModel> toDataModels(final Workbook book, final String function) { if (book == null || function == null) { return emptyList(); } List<IDataModel> list = new LinkedList<>(); final FormulaParsingWorkbook parsingBook = create((XSSFWorkbook) book); Sheet s = b...
java
@Override public boolean shouldRetry(int retryCount, Response response) { int code = response.code(); //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES return retryCount < this.retryCount && (code == 408 || (code >= 500 && code != 501 && code != 505)); }
java
protected Disjunct toDisjunctiveNormalForm(SemanticType type) { switch (type.getOpcode()) { case TYPE_null: case TYPE_bool: case TYPE_byte: case TYPE_int: return toDisjunctiveNormalForm((Type.Primitive) type); case TYPE_function: case TYPE_method: case TYPE_property: return toDisjunctiveNormalForm...
java
private static void forceClearCompilerCache() { if (CLEAR_COMPILER_CACHE != null && SHARED_ZIP_FILE_INDEX_CACHE != null) { try { CLEAR_COMPILER_CACHE.invoke(SHARED_ZIP_FILE_INDEX_CACHE); } catch (IllegalAccessException | InvocationTargetException e) { LOG....
python
def set_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an it...
java
public static <T> List<T> unmodifiableList(Collection<? extends T> elements) { return Collections.unmodifiableList(new ArrayList<>(elements)); }
python
def lrelu_sq(x): """ Concatenates lrelu and square """ dim = len(x.get_shape()) - 1 return tf.concat(dim, [lrelu(x), tf.minimum(tf.abs(x), tf.square(x))])
java
public static boolean hasSelector(@NotNull SlingHttpServletRequest request, @NotNull String expectedSelector) { String[] selectors = request.getRequestPathInfo().getSelectors(); return ArrayUtils.contains(selectors, expectedSelector); }
java
protected static Map<String, String> convertProperties( CmsObject cms, Map<String, String> props, Map<String, CmsXmlContentProperty> propConfig, boolean toClient) { Map<String, String> result = new HashMap<String, String>(); for (Map.Entry<String, String> entry : props.e...
java
public static <T> T instantiateLowlevel(Class<? extends T> clz) { Exception last = null; for(Class<?> c : ELKIServiceRegistry.findAllImplementations(clz)) { try { return clz.cast(c.newInstance()); } catch(Exception e) { last = e; } } throw new AbortException("Cann...
python
def restore(self): """ restore the saved game score and data """ size = self.board.SIZE try: with open(self.store_file, 'r') as f: lines = f.readlines() score_str = lines[0] self.score = int(lines[1]) except: ...
java
@Override public String obfuscate() { final String obfuscated = SimpleObfuscatorExtensions.obfuscateWith(rules, this.key); return obfuscated; }
java
private String performPadOperation(String source, Integer length, Character padChar, String direction) { if (direction.equals("Start")) { return Strings.padStart(source, length, padChar); } else { return Strings.padEnd(source, length, padChar); } }
java
@Override public java.util.concurrent.Future<ListTaskDefinitionsResult> listTaskDefinitionsAsync( com.amazonaws.handlers.AsyncHandler<ListTaskDefinitionsRequest, ListTaskDefinitionsResult> asyncHandler) { return listTaskDefinitionsAsync(new ListTaskDefinitionsRequest(), asyncHandler); }
python
def remove_outs(self, ignore_remove=False, force=False): """Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.""" for out in self.outs: if out.persist and not force: out.unprotect() else: logger.debug( "Removing ou...
java
@SuppressWarnings("unchecked") @NonNull public static Set<String> nonNullSet(@NonNull String firstItem, @Nullable String[] otherItems) { final HashSet<String> set = new HashSet<String>(); set.add(firstItem); if (otherItems != null) { set.addAll(asList(otherItems)); } ...
java
@Override public String getModuleName() { String moduleName = moduleNameFromModuleDescriptor; if (moduleName == null || moduleName.isEmpty()) { moduleName = moduleNameFromManifestFile; } if (moduleName == null || moduleName.isEmpty()) { if (derivedAutomaticMod...
python
def get_grade_system_id(self): """Gets the ``GradeSystem Id`` in which this grade belongs. return: (osid.id.Id) - the grade system ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id ...
python
def update(cls, id, params): """Update an existing vlan.""" cls.echo('Updating your vlan.') result = cls.call('hosting.vlan.update', cls.usable_id(id), params) return result
python
def discard_connection_filename(filename, working_filename, verbose = False): """ Like put_connection_filename(), but the working copy is simply deleted instead of being copied back to its original location. This is a useful performance boost if it is known that no modifications were made to the file, for example ...
python
def pack(self, remaining_size): """Pack data of part into binary format""" arguments_count, payload = self.pack_data(remaining_size - self.header_size) payload_length = len(payload) # align payload length to multiple of 8 if payload_length % 8 != 0: payload += b"\x00...
python
def classification_report(y_true, y_pred, digits=2, suffix=False): """Build a text report showing the main classification metrics. Args: y_true : 2d array. Ground truth (correct) target values. y_pred : 2d array. Estimated targets as returned by a classifier. digits : int. Number of dig...
python
def installed(name, version=None, defaults=False, force=False, preferred_state='stable'): ''' .. versionadded:: 0.17.0 Make sure that a pecl extension is installed. name The pecl extension name to install version The pecl ext...
java
private AccessControlEntry pick( AccessControlList acl, String principal ) throws RepositoryException { for (AccessControlEntry entry : acl.getAccessControlEntries()) { if (entry.getPrincipal().getName().equals(principal)) { return entry; ...
python
def compile_string(self, mof, ns, filename=None): """ Compile a string of MOF statements into a namespace of the associated CIM repository. Parameters: mof (:term:`string`): The string of MOF statements to be compiled. ns (:term:`string`): T...
python
def repr_part(self): """String usable in a space's ``__repr__`` method.""" optargs = [('weighting', array_str(self.array, nprint=10), ''), ('exponent', self.exponent, 2.0)] return signature_string([], optargs, sep=',\n', mod=[[], ['!s', ':.4']])
java
@Override public RuntimeEngine getRuntimeEngine(Context<?> context) { KnowledgeRuntimeEngine runtimeEngine; if (context == null || _type != KnowledgeRuntimeManagerType.PER_PROCESS_INSTANCE) { context = EmptyContext.get(); } final ClassLoader origTCCL = Classes.setTCCL(_cl...
python
def vocab_windows_pebinary_type(instance): """Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebinary-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: ...
python
def cleanup_outdir (outdir, archive): """Cleanup outdir after extraction and return target file name and result string.""" make_user_readable(outdir) # move single directory or file in outdir (success, msg) = move_outdir_orphan(outdir) if success: # msg is a single directory or filename ...
java
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case AfplibPackage.MCF1__RG: return ((InternalEList<?>)getRG()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); }
python
def main(argv): """Main """ parameters = process_arguments(argv) file_list = sed_eval.io.load_file_pair_list(parameters['file_list']) path = os.path.dirname(parameters['file_list']) data = [] all_data = dcase_util.containers.MetaDataContainer() for file_pair in file_list: refer...
java
public Whitelist removeTags(String... tags) { Validate.notNull(tags); for(String tag: tags) { Validate.notEmpty(tag); TagName tagName = TagName.valueOf(tag); if(tagNames.remove(tagName)) { // Only look in sub-maps if tag was allowed attributes.remove...
java
public NetworkInterfaceInner updateTags(String resourceGroupName, String networkInterfaceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, networkInterfaceName).toBlocking().last().body(); }
java
public void setFallThrough(boolean newFallThrough) { boolean oldFallThrough = fallThrough; fallThrough = newFallThrough; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, XbasePackage.XCASE_PART__FALL_THROUGH, oldFallThrough, fallThrough)); }
python
def auth_token(cls, token): """ Callback method for OAuth 2.0 bearer token middleware """ store = goldman.sess.store login = store.find(cls.RTYPE, 'token', token) if not login: msg = 'No login found with that token. It may have been revoked.' raise AuthRejected(...
python
def parse_c_serialized(f): """ Reads in a binary file created by a C++ serializer (prob. MFC?) and returns tuples of (header name, data following the header). These are used by Thermo for *.CF and *.DXF files and by Agilent for new-style *.REG files. """ # TODO: rewrite to use re library ...
python
def money_flow(close_data, high_data, low_data, volume): """ Money Flow. Formula: MF = VOLUME * TYPICAL PRICE """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) mf = volume * tp(close_data, high_data, low_data) return mf
java
public static double calculateGroundResolution(double latitude, long mapSize) { return Math.cos(latitude * (Math.PI / 180)) * EARTH_CIRCUMFERENCE / mapSize; }
java
public void removeServletModel(final ServletModel model) { servletLock.writeLock().lock(); try { deassociateBundle(model.getContextModel().getVirtualHosts(), model.getContextModel().getBundle()); for (String virtualHost:resolveVirtualHosts(model)) { if (model.getAlias() ...
java
public com.google.privacy.dlp.v2.PrivacyMetric.NumericalStatsConfig getNumericalStatsConfig() { if (typeCase_ == 1) { return (com.google.privacy.dlp.v2.PrivacyMetric.NumericalStatsConfig) type_; } return com.google.privacy.dlp.v2.PrivacyMetric.NumericalStatsConfig.getDefaultInstance(); }
java
public void getResources(Vector<URL> resources, String name) { Path path; path = getPath(name); if (path != null && path.canRead()) { try { resources.add(path.getNetURL()); } catch (Exception e) { } } }
python
def wait(self, timeout): """Calling thread waits for a given number of milliseconds or until notified.""" self.condition.acquire() self.condition.wait(timeout // 1000) self.condition.release()
java
private void configureConnector(String proto, Connector connector) { connector.setRequestHeaderSize(getSysPropInt(proto+".requestHeaderSize", 32*1024)); connector.setRequestBufferSize(getSysPropInt(proto+".requestBufferSize", 32*1024)); connector.setResponseHeaderSize(getSysPropInt(proto+".responseHeaderSiz...
java
private void initialize(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { obtainStyledAttributes(attributeSet, defaultStyle, defaultStyleResource); }
python
def postOptions(self): """ Display details about the ports which already exist. """ store = self.parent.parent.getStore() port = None factories = {} for portType in [TCPPort, SSLPort, StringEndpointPort]: for port in store.query(portType): ...
python
def same_types(self, index1, index2): """Returns True if both symbol table elements are of the same type""" try: same = self.table[index1].type == self.table[index2].type != SharedData.TYPES.NO_TYPE except Exception: self.error() return same
python
def set_base_headers(self, hdr): """Set metadata in FITS headers.""" hdr = super(StareImageBaseRecipe, self).set_base_headers(hdr) # Update EXP to 0 hdr['EXP'] = 0 return hdr
python
def execstr_funckw(func): """ for doctests kwargs SeeAlso: ut.exec_func_src ut.argparse_funckw """ import utool as ut funckw = ut.get_func_kwargs(func) return ut.execstr_dict(funckw, explicit=True)
java
public static void copyUnsetAnnotations(CoreMap src, CoreMap dest) { Set<Class<?>> otherKeys = src.keySet(); for (Class key : otherKeys) { if (!dest.has(key)) { dest.set(key, src.get(key)); } } }
java
@Override public ListVPCEConfigurationsResult listVPCEConfigurations(ListVPCEConfigurationsRequest request) { request = beforeClientExecution(request); return executeListVPCEConfigurations(request); }
java
private static void validateSeedBrokers(String[] seedBrokers, Exception exception) { if (!(exception instanceof ClosedChannelException)) { return; } int unknownHosts = 0; for (String broker : seedBrokers) { URL brokerUrl = NetUtils.getCorrectHostnamePort(broker.trim()); try { InetAddress.getByName(...
java
protected ConversionDirectionType getCatalysisDirection(Control cont) { if (cont instanceof Catalysis) { CatalysisDirectionType catDir = ((Catalysis) cont).getCatalysisDirection(); if (catDir == CatalysisDirectionType.LEFT_TO_RIGHT) { return ConversionDirectionType.LEFT_TO_RIGHT; } else if (cat...
java
public synchronized void initialize(InputStream fsr) throws IOException { if (fsr == null) { throw new IOException("PropertiesSynonymProvider requires a path configuration"); } try { config = fsr; synonyms = getSynonyms(config); lastCheck = System.cur...
python
def get_default_config(self): """ Return the default config for the handler """ config = super(SentryHandler, self).get_default_config() config.update({ 'dsn': '', }) return config
java
public void fillWithText(TextView view, FakerTextComponent component) { validateNotNullableView(view); validateIfIsATextView(view); validateNotNullableFakerComponent(component); view.setText(component.randomText()); }
python
def ChunksExist(self, chunk_numbers): """Do we have this chunk in the index?""" index_urns = { self.urn.Add(self.CHUNK_ID_TEMPLATE % chunk_number): chunk_number for chunk_number in chunk_numbers } res = {chunk_number: False for chunk_number in chunk_numbers} for metadata in aff4.FA...
java
public JsCodeBuilder append(CodeChunk codeChunk) { codeChunk.collectRequires(requireCollector); return append(codeChunk.getStatementsForInsertingIntoForeignCodeAtIndent(indent.length())); }
python
def angular_momentum_matrix(J, ind="z"): ur"""Return the angular momentum operator matrix (divided by hbar) for a\ given J angular momentum. INPUT: - ``ind`` - A string ("x", "y", "z", "all") indicating which direction \ to calculate, or to return them all as :math:`(J_x, J_y, J_z)`. OUTPUT:...
java
public DistributionPoint[] getDistributionPoints() { DistributionPoint[] dp = new DistributionPoint[seq.size()]; for (int i = 0; i != seq.size(); i++) { dp[i] = DistributionPoint.getInstance(seq.getObjectAt(i)); } return dp; }
java
private void shareLink(ShareLinkBuilder builder) { //Cancel any existing sharing in progress. if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(true); } shareLinkManager_ = new ShareLinkManager(); shareLinkManager_.shareLink(builder); }
python
def os_change(self, subid, osid, params=None): ''' /v1/server/os_change POST - account Changes the operating system of a virtual machine. All data will be permanently lost. Link: https://www.vultr.com/api/#server_os_change ''' params = update_params(params, { ...
java
public void parse(String... args) { try { parse(true /* validate */, args); } catch(ParameterException ex) { ex.setJCommander(this); throw ex; } }
java
public void showProgress(final int id, final int sofar, final int total) { final T notification = get(id); if (notification == null) { return; } notification.updateStatus(FileDownloadStatus.progress); notification.update(sofar, total); }
python
def similarity_graph(self, k=5, radius=None, include_self_edges=False, output_type='SGraph', verbose=True): """ Construct the similarity graph on the reference dataset, which is already stored in the model. This is conceptually very similar to running `query` wit...
java
public PaymillList<Payment> list( Payment.Filter filter, Payment.Order order ) { return this.list( filter, order, null, null ); }
java
private int bits(int need) throws IOException { int val; /* bit accumulator */ /* load at least need bits into val */ val = m_bitbuf; while (m_bitcnt < need) { if (m_left == 0) { m_in = m_input.read(); m_left = m_in == -1 ? 0 : 1; i...
python
def update_box(self, box): '''Updates a box with the provided attributes. Args: box StreakBox object with updated info return (status code, box in dict form) ''' #req sanity check payload = None if type(box) is not StreakBox: return requests.codes.bad_request, None payload = box.to_dict(rw = T...
python
def bootstrap(name, user=None): ''' Bootstraps a frontend distribution. Will execute 'bower install' on the specified directory. user The user to run Bower with ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if __opts__['test']: ret['result'] = Non...
python
def eq_or_parent(self, other): """Check whether ``other`` is an ancestor. Returns: (bool) True IFF ``other`` is an ancestor or equal to ``self``, else False. """ return self.parts[: len(other.parts)] == other.parts[: len(self.parts)]
python
def serialize(self, datas): """ Serialize datas to manifest structure with metas and references. Only references are returned, metas are assigned to attribute ``ManifestSerializer._metas``. Arguments: datas (dict): Data where to search for reference declarations. Th...
java
public static Util instance() { if (_instance == null) { System.err.println("Util is not initialised !!!"); System.err.println("Exiting"); System.exit(-1); } return _instance; }
python
def _set_traffic_class_exp(self, v, load=False): """ Setter method for traffic_class_exp, mapped from YANG variable /qos_mpls/map/traffic_class_exp (list) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_class_exp is considered as a private method. Backends lo...
python
def _clean_css(self): """ Returns the cleaned CSS :param stylesheet: The Stylesheet object to parse :type stylesheet: tinycss.css21.Stylesheet """ # Init the cleaned CSS rules and contents string css_rules = [] # For every rule in the CSS for rul...
python
def close_room(self, room, namespace=None): """Close a room.""" return self.socketio.close_room(room=room, namespace=namespace or self.namespace)
python
def get_schema(self, table_name, database=None): """ Return a Schema object for the indicated table and database Parameters ---------- table_name : string May be fully qualified database : string, default None Returns ------- schema : i...
java
public final NotificationChannelDescriptor getNotificationChannelDescriptor(String name) { GetNotificationChannelDescriptorRequest request = GetNotificationChannelDescriptorRequest.newBuilder().setName(name).build(); return getNotificationChannelDescriptor(request); }
java
public static <K, VV, EV> Graph<K, VV, EV> fromCollection(Collection<Edge<K, EV>> edges, final MapFunction<K, VV> vertexValueInitializer, ExecutionEnvironment context) { return fromDataSet(context.fromCollection(edges), vertexValueInitializer, context); }
java
private <J, T extends Proxy<J>> T marshalConstructor(final int opcode, final J implementation, final int version, final Class<T> newProxyCls, ...
python
def _stdout_list_split(retcode, stdout='', splitstring='\n'): ''' Evaulates Open vSwitch command`s retcode value. Args: retcode: Value of retcode field from response, should be 0, 1 or 2. stdout: Value of stdout filed from response. splitstring: String used to split the stdout defau...
java
public java.util.List<String> getPatchGroups() { if (patchGroups == null) { patchGroups = new com.amazonaws.internal.SdkInternalList<String>(); } return patchGroups; }
java
public static void logErrorScene(Map<String, Object> rt, AlipayResponse tRsp, String appSecret) { if (!needEnableLogger) { return; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone(AlipayCon...
java
public synchronized void addAdditionalInfo(int infoType, byte[] info) { if (infoType < 0 || infoType >= ADDINFO_ESC) throw new KNXIllegalArgumentException("info type out of range [0..254]"); if (!checkAddInfoLength(infoType, info.length)) throw new KNXIllegalArgumentException("wrong info data length, ex...
java
@Nullable public Document getDocument (final int nDocID) throws IOException { _checkClosing (); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("getDocument(" + nDocID + ")"); final IndexReader aReader = getReader (); if (aReader == null) return null; return aReader.document (nDocID); ...
python
def requestAvatar(self, avatarId, mind, *interfaces): """ Create Adder avatars for any IBoxReceiver request. """ if IBoxReceiver in interfaces: return (IBoxReceiver, Adder(avatarId), lambda: None) raise NotImplementedError()
python
def _object_client(self, *, not_found=None): """(Re-)initialize object client if required, handle 404 errors gracefully and reset the client on server errors. Server errors have been shown to be caused by invalid state in the client and do not seem to be resolved without resetting.""" i...
java
public CmsResource createNewElement(CmsObject userCms, CmsResource modelResource, String pageFolderRootPath) throws CmsException { checkOffline(userCms); checkInitialized(); CmsObject rootCms = rootCms(userCms); String folderPath = getFolderPath(userCms, pageFolderRootPath); ...
java
private Map getUsers() throws NamingException { String filter = "(" + roleNameRDN + "=*)"; HashMap users = new HashMap(); NamingEnumeration results = this.search(roleBase, filter, new String[]{roleMemberRDN}); while (results != null && results.hasMore()) { SearchResult ro...
java
public final GedObject create(final GedObject parent, final String xref, final String tag, final String tail) { return getFactory(tag).create(parent, new ObjectId(xref), fullstring(tag), tail); }
java
public void setCommandGenerator ( String bureauType, final CommandGenerator cmdGenerator, int timeout) { setLauncher(bureauType, new Launcher() { public void launchBureau (String bureauId, String token) throws IOException { ProcessBuilder builder = new Pro...
python
def dkron(A,dA,B,dB, operation='prod'): """ Function computes the derivative of Kronecker product A*B (or Kronecker sum A+B). Input: ----------------------- A: 2D matrix Some matrix dA: 3D (or 2D matrix) Derivarives of A B: 2D matrix Some matrix dB: 3D (or 2...
java
public StringBuffer getRootURL() { StringBuffer url = new StringBuffer(48); synchronized (url) { String scheme = getScheme(); int port = getPort(); url.append(scheme); url.append("://"); if (_hostPort != null) url.a...
python
def download_dataset( dataset_name, file_path, task=None, dataset_attributes=None, **kwargs): """Downloads the given dataset from dataset store. Parameters ---------- dataset_name : str The name of the dataset to upload. file_path : str The full path to the file to upload ...
java
public String getDefinition_12_063(long srsId) { String definition = null; if (hasDefinition_12_063()) { definition = crsWktExtension.getDefinition(srsId); } return definition; }
java
private void convertDefineParameters(CompilerOptions options) { for (Parameter p : defineParams) { String key = p.getName(); Object value = p.getValue(); if (!setDefine(options, key, value)) { log("Unexpected @define value for name=" + key + "; value=" + value); } } }
java
@Override public Long fromString(Class targetClass, String s) { try { if (s == null) { if (log.isWarnEnabled()) { log.warn("String s is null."); } return null; } ...
java
public Observable<ServiceResponse<Page<AvailableServiceSkuInner>>> listSkusWithServiceResponseAsync(final String groupName, final String serviceName) { return listSkusSinglePageAsync(groupName, serviceName) .concatMap(new Func1<ServiceResponse<Page<AvailableServiceSkuInner>>, Observable<ServiceRespo...
python
def getlist(self, name): """ Retrieve given property from class/instance, ensuring it is a list. Also determine whether the list contains simple text/numeric values or nested dictionaries (a "complex" list) """ value = self.getvalue(name) complex = {} def...
java
void wakeOut() { OnAvailable outFlow = _outFlow; if (outFlow == null) { return; } if (_creditsIn <= _queue.head()) { return; } StateOutPipe stateOld; StateOutPipe stateNew; do { stateOld = _stateOutRef.get(); if (! stateOld.isFull()) { ...
python
def clean_meta(self, meta): """Removes unwanted metadata Parameters ---------- meta : dict Notebook metadata. """ if not self.verbose_metadata: default_kernel_name = (self.default_kernel_name or self._km.kernel_...
java
private void setIssuerUniqueId(Object val) throws CertificateException { if (version.compare(CertificateVersion.V2) < 0) { throw new CertificateException("Invalid version"); } if (!(val instanceof UniqueIdentity)) { throw new CertificateException( ...