language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def data_sanitise(self, inputstring, header=None): """ Format the data to be consistent with heatmaps :param inputstring: string containing data to be formatted :param header: class of the data - certain categories have specific formatting requirements :return: the formatted outp...
java
public LocalProperties filterBySemanticProperties(SemanticProperties props, int input) { if (props == null) { throw new NullPointerException("SemanticProperties may not be null."); } LocalProperties returnProps = new LocalProperties(); // check if sorting is preserved if (this.ordering != null) { Ord...
python
def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. """ if self.logger: self.logger.debug('Executing single request: %s', request) self.removeRequest(request) body = remoting.enco...
java
protected String getTargetUriOutOfScope(Target target, Object[] contextSpecificObjects) { List<StructuralNode> nodes = target.getStartNodes(); if (nodes != null) { for (StructuralNode node : nodes) { if (node == null) { continue; } if (node instanceof StructuralSiteNode) { SiteNode siteNode...
python
def archive(source, archive, path_in_arc=None, remove_source=False, compression=zipfile.ZIP_DEFLATED, compresslevel=-1): """Archives a MRIO database as zip file This function is a wrapper around zipfile.write, to ease the writing of an archive and removing the source data. Note ---- ...
python
def get(self, field, value=None): """Gets user input for given field and checks if it is valid. If input is invalid, it will ask the user to enter it again. Defaults values to empty or :value:. It does not check validity of parent index. It can only be tested further down the r...
python
def get_group_summary(self, group_id, **kwargs): # noqa: E501 """Get group information. # noqa: E501 An endpoint for getting general information about the group. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -H 'Authorization: Bearer API_KEY'` # noqa: E50...
python
def pretty_string(s, embedded, current_line, uni_lit=False, min_trip_str=20, max_line=100): """There are a lot of reasons why we might not want to or be able to return a triple-quoted string. We can always punt back to the default normal string. """ default = repr(s) #...
java
private void readTask(Task parentTask, net.sf.mpxj.planner.schema.Task plannerTask) throws MPXJException { Task mpxjTask; if (parentTask == null) { mpxjTask = m_projectFile.addTask(); mpxjTask.setOutlineLevel(Integer.valueOf(1)); } else { mpxjTask = par...
java
public EEnum getImageEncodingRECID() { if (imageEncodingRECIDEEnum == null) { imageEncodingRECIDEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(117); } return imageEncodingRECIDEEnum; }
java
public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != BluetoothService.STATE_CONNECTED) return; r = mConnectedThread; } // Perform the write un...
java
@Override public Entity set(String field, Object value) { return (Entity) super.set(field, value); }
python
def predict_normal_binding(job, binding_result, transgened_files, allele, peplen, univ_options, mhc_options): """ Predict the binding score for the normal counterparts of the peptides in mhc_dict and then return the results in a properly formatted structure. :param str bindin...
java
public AnnotationTypeFieldWriter getAnnotationTypeFieldWriter(AnnotationTypeWriter annotationTypeWriter) throws Exception { return new AnnotationTypeFieldWriterImpl( (SubWriterHolderWriter) annotationTypeWriter, annotationTypeWriter.getAnnotationTypeDoc()); }
python
def _query(self, action, qobj): """ returns WPToolsQuery string """ title = self.params.get('title') pageid = self.params.get('pageid') wikibase = self.params.get('wikibase') qstr = None if action == 'random': qstr = qobj.random() eli...
python
def _get_attribute_value_of(resource, attribute_name, default=None): """Gets the value of attribute_name from the resource It catches the exception, if any, while retrieving the value of attribute_name from resource and returns default. :param resource: The resource object :attribute_name: Propert...
java
public void debugv(String format, Object param1) { if (isEnabled(Level.DEBUG)) { doLog(Level.DEBUG, FQCN, format, new Object[] { param1 }, null); } }
python
def setDecoder(self, decoder): """ Sets the client's decoder ``decoder`` should be an instance of a ``json.JSONDecoder`` class """ if not decoder: self._decoder = json.JSONDecoder() else: self._decoder = decoder self._decode = self._decoder...
python
def printHelp(script): """Print Help Prints out the arguments needs to run the script Returns: None """ print 'Reconsider cli script copyright 2016 OuroborosCoding' print '' print script + ' --source=localhost:28015 --destination=somedomain.com:28015' print script + ' --destination=somedomain.com:28015 --d...
java
protected String getIndexName(String indexPrefix, long timestamp) { return new StringBuilder(indexPrefix).append('-') .append(fastDateFormat.format(timestamp)).toString(); }
java
public PagedList<PublicIPAddressInner> listVirtualMachineScaleSetPublicIPAddresses(final String resourceGroupName, final String virtualMachineScaleSetName) { ServiceResponse<Page<PublicIPAddressInner>> response = listVirtualMachineScaleSetPublicIPAddressesSinglePageAsync(resourceGroupName, virtualMachineScaleSe...
java
public static synchronized EntityClassReader getClassReaderFor(Class entityClass, String geometryPropertyName, String idPropertyName) { if (entityClass == null) { return null; } String entryKey = "" + geometryPropertyName + "|" + idPropertyName; Map<String, EntityClassReader>...
java
@Override public void update() { NamingEnumeration<? extends Attribute> attributesEnumeration = null; try { attributesEnumeration = updatedAttrs.getAll(); // find what to update while (attributesEnumeration.hasMore()) { Attribute a = attributesEnumeration.next(); // if it does not exist it shou...
java
public static Schema infer(List<Writable> record) { Schema.Builder builder = new Schema.Builder(); for (int i = 0; i < record.size(); i++) { if (record.get(i) instanceof DoubleWritable) builder.addColumnDouble(String.valueOf(i)); else if (record.get(i) instanceof ...
java
public static CommerceWishListItem findByCW_CPI_CP( long commerceWishListId, String CPInstanceUuid, long CProductId) throws com.liferay.commerce.wish.list.exception.NoSuchWishListItemException { return getPersistence() .findByCW_CPI_CP(commerceWishListId, CPInstanceUuid, CProductId); }
java
protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { Set<RuntimeCapability> capabilitySet = capabilities.isEmpty() ? context.getResourceRegistration().getCapabilities() : capabilities; for (RuntimeCapability...
python
def pverb(self, *args, **kwargs): """ Console verbose message to STDOUT """ if not self.verbose: return self.pstd(*args, **kwargs)
java
public static Set<ModificationFeature>[] getChangedModifications(PhysicalEntity before, PhysicalEntity after) { Set<Modification> set1 = collectFeatures(before); Set<Modification> set2 = collectFeatures(after); Set<Modification> temp = new HashSet<Modification>(set1); set1.removeAll(set2); set2.removeAll(...
python
def restoreDefaultWCS(imageObjectList, output_wcs): """ Restore WCS information to default values, and update imageObject accordingly. """ if not isinstance(imageObjectList,list): imageObjectList = [imageObjectList] output_wcs.restoreWCS() updateImageWCS(imageObjectList, output_wcs...
java
private void init(Context context, AttributeSet attrs, int defStyle) { // Initialize paint objects paint = new Paint(); paint.setAntiAlias(true); paintBorder = new Paint(); paintBorder.setAntiAlias(true); paintBorder.setStyle(Paint.Style.STROKE); paintSelectorBorder = new Paint(); paintSelectorBorder.se...
java
public ListRecordsResult withRecords(Record... records) { if (this.records == null) { setRecords(new com.amazonaws.internal.SdkInternalList<Record>(records.length)); } for (Record ele : records) { this.records.add(ele); } return this; }
java
public static void copyToWicketSession(final PageParameters source, final Session session) { final List<INamedParameters.NamedPair> namedPairs = source.getAllNamed(); for (final INamedParameters.NamedPair namedPair : namedPairs) { session.setAttribute(namedPair.getKey(), namedPair.getValue()); } }
python
def get_curent_module_classes(module): """ 获取制定模块的所有类 :param module: 模块 :return: 类的列表 """ classes = [] for name, obj in inspect.getmembers(module): if inspect.isclass(obj): classes.append(obj) return classes
python
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works. ''' # if the username and password were already found don't go through the # connection process again if 'username' in DETAILS and 'password' in DETAILS: return DETAILS['usern...
python
def initialize(cls) -> None: """Initializes the ``SIGCHLD`` handler. The signal handler is run on an `.IOLoop` to avoid locking issues. Note that the `.IOLoop` used for signal handling need not be the same one used by individual Subprocess objects (as long as the ``IOLoops`` are...
java
public static void setParameter(final Element elem, final PropertySetter propSetter, final Properties props) { String name = subst(elem.getAttribute("name"), props); String value = (elem.getAttribute("value")); value = subst...
java
public static String escapeAngleBracketsInJson(String json) { if (json == null) return null; return json.replaceAll("<", "\\\\<").replaceAll(">", "\\\\>"); }
python
def auto_connect(self): """ Make a connection between every member function to a GUI signal. Every member function whose name is in format: '_on_' + <widget_name> + '__' + <widget_signal_name> are connected to the signal of a GUI widget if it exists. Also, every funct...
python
def locate_blocks(self, codestr): """ Returns all code blocks between `{` and `}` and a proper key that can be multilined as long as it's joined by `,` or enclosed in `(` and `)`. Returns the "lose" code that's not part of the block as a third item. """ def _strip...
java
public Observable<Page<EncryptionProtectorInner>> listByServerAsync(final String resourceGroupName, final String serverName) { return listByServerWithServiceResponseAsync(resourceGroupName, serverName) .map(new Func1<ServiceResponse<Page<EncryptionProtectorInner>>, Page<EncryptionProtectorInner>>() ...
java
protected final PrcInvoiceGfe<IInvoice> lazyGetPrcInvoiceGfe( final Map<String, Object> pAddParam) throws Exception { @SuppressWarnings("unchecked") PrcInvoiceGfe<IInvoice> proc = (PrcInvoiceGfe<IInvoice>) this.processorsMap.get(PrcInvoiceGfe.class.getSimpleName()); if (proc == null) { proc ...
java
boolean run(String... argArray) { Queue<String> args = new ArrayDeque<>(Arrays.asList(argArray)); LoadMode loadMode = LoadMode.RELEASE; ScanMode scanMode = ScanMode.ARGS; String dir = null; String jar = null; String jdkHome = null; String release = "9"; Li...
python
def unassign_gradebook_column_from_gradebook(self, gradebook_column_id, gradebook_id): """Removes a ``GradebookColumn`` from a ``Gradebook``. arg: gradebook_column_id (osid.id.Id): the ``Id`` of the ``GradebookColumn`` arg: gradebook_id (osid.id.Id): the ``Id`` of the ...
java
public final EObject ruleRichStringLiteralInbetween() throws RecognitionException { EObject current = null; Token lv_value_1_0=null; Token lv_value_2_0=null; enterRule(); try { // InternalSARL.g:10915:2: ( ( () ( ( (lv_value_1_0= RULE_RICH_TEXT_INBETWEEN ) ) | ( ...
java
public void marshall(Expression expression, ProtocolMarshaller protocolMarshaller) { if (expression == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(expression.getOr(), OR_BINDING); prot...
java
public static void writeInterestingObject (ObjectInfo info, DataWriter writer) throws SAXException { AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "tileId", "", "", String.valueOf(info.tileId)); attrs.addAttribute("", "x", "", "", String.valueOf(info.x)); ...
java
public static double JensenShannonDivergence(SparseArray x, SparseArray y) { if (x.isEmpty()) { throw new IllegalArgumentException("List x is empty."); } if (y.isEmpty()) { throw new IllegalArgumentException("List y is empty."); } Iterator<SparseArray.En...
python
def popen(self, cmd): """Execute an external command and return (rc, output). """ process = Popen(cmd, shell=True, stdout=PIPE, env=self.env) stdoutdata, stderrdata = process.communicate() return process.returncode, stdoutdata
java
@Override public void setURL(int parameterIndex, URL x) throws SQLException { internalStmt.setURL(parameterIndex, x); }
java
public static <T> String join(Iterable<T> iterable, char separator, T... pieces) { StringBuilder sb = new StringBuilder(); for (T element: iterable) { sb.append(element != null ? element.toString() : "null").append(separator); } for (int i = 0; i < pieces.length; ++i) { ...
java
public static Matrix fromString(String string, Object... parameters) { string = string.replaceAll(StringUtil.BRACKETS, ""); String[] rows = string.split(StringUtil.SEMICOLONORNEWLINE); String[] cols = rows[0].split(StringUtil.COLONORSPACES); Object[][] values = new String[rows.length][cols.length]; for (int r...
python
def to_vcf(self, path, rename=None, number=None, description=None, fill=None, write_header=True): r"""Write to a variant call format (VCF) file. Parameters ---------- path : string File path. rename : dict, optional Rename these columns in ...
python
def fast_boolean(operandA, operandB, operation, precision=0.001, max_points=199, layer=0, datatype=0): """ Execute any boolean operation between 2 polygons or polygon sets. Parameters ---------- op...
java
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoInstance(@NonNull Context context) { isAutoSessionMode_ = true; customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; boolean isTest = BranchUtil.checkTestMode(context); getBranchInstance(con...
java
public static String quote(String data) { if (data == null) { return "\"\""; } try { JSONStringer stringer = new JSONStringer(); stringer.open(JSONStringer.Scope.NULL, ""); stringer.value(data); stringer.close(JSONStringer.Scope.NULL, JSONStringer.Scope.NULL, ""); return stringer.toString(); }...
python
def _build(argv, config, versions, current_name, is_root): """Build Sphinx docs via multiprocessing for isolation. :param tuple argv: Arguments to pass to Sphinx. :param sphinxcontrib.versioning.lib.Config config: Runtime configuration. :param sphinxcontrib.versioning.versions.Versions versions: Versio...
java
private CompletableFuture<Void> bootstrap(int attempt, CompletableFuture<Void> future) { Futures.allOf(membershipService.getMembers().stream() .filter(node -> !node.id().equals(membershipService.getLocalMember().id())) .map(node -> bootstrap(node)) .collect(Collectors.toList())) .whe...
python
def copy_current_websocket_context(func: Callable) -> Callable: """Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: p...
java
public void marshall(WorkerBlock workerBlock, ProtocolMarshaller protocolMarshaller) { if (workerBlock == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(workerBlock.getWorkerId(), WORKERID_BINDING); ...
java
private void sortByMetaData(List<MetaDataCol> sortColumns) { if (sortColumns == null || sortColumns.isEmpty()) { sort(new Object[] { PROP_DOC_NAME }, new boolean[] { true }); return; } Object[] sortByColumns = new Object[sortColumns.size()]; bo...
java
public CMAApiKey update(CMAApiKey key) { assertNotNull(key, "key"); final String keyId = getResourceIdOrThrow(key, "key"); final String spaceId = getSpaceIdOrThrow(key, "key"); final Integer version = getVersionOrThrow(key, "update"); final CMASystem system = key.getSystem(); key.setSystem(null...
java
protected void obtainProducerEndpoints(List<Node> nodes, List<EndpointInfo> endpoints, Map<String, EndpointInfo> map) { for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); if (node instanceof Producer) { String endpoint = En...
java
public JBBPTextWriter Short(final int value) throws IOException { ensureValueMode(); String convertedByExtras = null; for (final Extra e : this.extras) { convertedByExtras = e.doConvertShortToStr(this, value & 0xFFFF); if (convertedByExtras != null) { break; } } if (conver...
java
public AutoScaleRun evaluateAutoScale(String poolId, String autoScaleFormula) throws BatchErrorException, IOException { return evaluateAutoScale(poolId, autoScaleFormula, null); }
java
public static List<ExtractedSection> getSections(String text, String title, long revision) throws LinkTargetException, EngineException, FileNotFoundException, JAXBException{ return (List<ExtractedSection>) parsePage(new SectionExtractor(), text, title, revision); }
python
def _create_dns_list(self, dns): """ :param dns: :return: """ if not dns: return None dns_list = [] if isinstance(dns, six.string_types): if is_valid_ip(dns): dns_list.append(dns) else: raise Va...
java
public void marshall(Put put, ProtocolMarshaller protocolMarshaller) { if (put == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(put.getItem(), ITEM_BINDING); protocolMarshaller.marshall(...
java
public static String getProtocol(String url) { if(url == null) { return null; } int protocolSeparatorIndex = url.indexOf("://"); if(protocolSeparatorIndex == -1) { return null; } return url.substring(0, protocolSeparatorIndex).toLowerCase(); }
java
void handleRepeatableAnnotations(final Set<String> allRepeatableAnnotationNames, final ClassInfo containingClassInfo, final RelType forwardRelType, final RelType reverseRelType) { List<AnnotationInfo> repeatableAnnotations = null; for (int i = size() - 1; i >= 0; --i) { final Ann...
java
private int getSwipeDuration(MotionEvent ev, int velocity) { int sx = getScrollX(); int dx = (int)(ev.getX() - sx); final int width = mSwipeCurrentHorizontal.getMenuWidth(); final int halfWidth = width / 2; final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); ...
python
def statistical_distances(samples1, samples2, earth_mover_dist=True, energy_dist=True): """Compute measures of the statistical distance between samples. Parameters ---------- samples1: 1d array samples2: 1d array earth_mover_dist: bool, optional Whether or not ...
python
def fsdecode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None): ''' Decode given path. :param path: path will be decoded if using bytes :type path: bytes or str :param os_name: operative system name, defaults to os.name :type os_name: str :param fs_encoding: current filesystem en...
python
def get_user(self, username): """ Return a User object for this username. :param username: The name of the user we want more information about. """ url = self._base_url + "/3/account/{0}".format(username) json = self._send_request(url) return User(json, self)
python
def __check_valid(self, post_data): ''' To check if the user is succesfully created. Return the status code dict. ''' user_create_status = {'success': False, 'code': '00'} if not tools.check_username_valid(post_data['user_name']): user_create_status['code'] =...
java
public static <C extends Compound> Map<C, Double> getDistribution(Sequence<C> sequence) { Map<C, Double> results = new HashMap<C, Double>(); Map<C, Integer> composition = getComposition(sequence); double length = sequence.getLength(); for (Map.Entry<C, Integer> entry : composition.entrySet()) { double dist =...
java
public final EObject entryRuleXParenthesizedExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXParenthesizedExpression = null; try { // InternalSARL.g:14277:65: (iv_ruleXParenthesizedExpression= ruleXParenthesizedExpression EOF ) // Inte...
java
public static String getCallerMethodName( int offset ) { StackTraceElement[] stack = new Exception().getStackTrace(); return stack[offset+1].getMethodName(); }
java
private void setCalendarToOrdinalRelativeDay(Calendar calendar, int dayNumber) { int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int requiredDayOfWeek = getDayOfWeek().getValue(); int dayOfWeekOffset = 0; if (requiredDayOfWeek > currentDayOfWeek) { dayOfWeekOffset = ...
python
def _insert_layer_after(self, layer_idx, new_layer, new_keras_layer): """ Insert the new_layer after layer, whose position is layer_idx. The new layer's parameter is stored in a Keras layer called new_keras_layer """ # reminder: new_keras_layer is not part of the original Keras n...
java
public static UserInfo getUserInfo(final String userId) { if (userId == null) { throw new IllegalArgumentException("null userName"); } try { Class<?> accessor = Class.forName("com.sap.security.um.service.UserManagementAccessor"); if (accessor != null) { ...
java
public ServiceFuture<VirtualMachineInner> getByResourceGroupAsync(String resourceGroupName, String vmName, final ServiceCallback<VirtualMachineInner> serviceCallback) { return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, vmName), serviceCallback); }
java
private void remove(ThreadGroup g) { synchronized (this) { if (destroyed) { return; } for (int i = 0 ; i < ngroups ; i++) { if (groups[i] == g) { ngroups -= 1; System.arraycopy(groups, i + 1, groups, i, n...
java
@CanIgnoreReturnValue @Override public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X { try { return get(timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw mapException(e); } catch (CancellationException e) { throw m...
python
def XYZ_to_IPT(cobj, *args, **kwargs): """ Converts XYZ to IPT. NOTE: XYZ values need to be adapted to 2 degree D65 Reference: Fairchild, M. D. (2013). Color appearance models, 3rd Ed. (pp. 271-272). John Wiley & Sons. """ if cobj.illuminant != 'd65' or cobj.observer != '2': raise ...
java
public void marshall(CategoricalParameterRange categoricalParameterRange, ProtocolMarshaller protocolMarshaller) { if (categoricalParameterRange == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cate...
java
protected void updateClusterCenters() { // compute the new centers of each cluster for (int i = 0; i < clusters.size; i++) { double mc = memberCount.get(i); double[] w = workClusters.get(i); double[] c = clusters.get(i); for (int j = 0; j < w.length; j++) { c[j] = w[j] / mc; } } }
java
public static BoxCollaborationWhitelistExemptTarget.Info create(final BoxAPIConnection api, String userID) { URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.build(api.getBaseURL()); BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST); JsonObject requestJSO...
python
def get(self): """ Get a JSON-ready representation of this Attachment. :returns: This Attachment, ready for use in a request body. :rtype: dict """ attachment = {} if self.file_content is not None: attachment["content"] = self.file_content.get() ...
java
public void setVariables(com.google.api.ads.admanager.axis.v201805.CreativeTemplateVariable[] variables) { this.variables = variables; }
java
public static <T> T fromXml(File xmlPath, Class<T> type) { BufferedReader reader = null; StringBuilder sb = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(xmlPath), ENCODING)); String line = null; sb = new StringBuilder(); ...
java
public void setHeartbeatInterval(short heartbeatInterval) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setHeartbeatInterval"); properties.put(HEARTBEAT_INTERVAL, heartbeatInterval); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.e...
python
def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$",...
python
def add_key_val(keyname, keyval, keytype, filename, extnum): """Add/replace FITS key Add/replace the key keyname with value keyval of type keytype in filename. Parameters: ---------- keyname : str FITS Keyword name. keyval : str FITS keyword value. keytype: str FITS...
java
public String getDependencyString(int id) { ClientResource resource = new ClientResource(Route.DEPENDENCY_STRING.url(id)); try { Representation repr = resource.get(); return mapper.readValue(repr.getText(), DependencyString.class).getDependency(); } catch (IOException ex...
java
protected Pair<Gradient, INDArray> calcBackpropGradients(INDArray epsilon, boolean withOutputLayer, boolean tbptt, boolean returnInputActGrad) { if (flattenedGradients == null) { initGradientsView(); } String multiGradientK...
python
def get_param_type_indexes(self, data, name=None, prev=None): """Get from a docstring a parameter type indexes. In javadoc style it is after @type. :param data: string to parse :param name: the name of the parameter (Default value = None) :param prev: index after the previous el...
python
def collect_conflicts_between_fragments( context: ValidationContext, conflicts: List[Conflict], cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, fragment_name1: str, fragment_name2: str, ) -> None: """Collect conflicts between frag...
python
def with_resource_connection_as_argument(resource_name): """a class decorator for Crontabber Apps. This decorator will a class a _run_proxy method that passes a databsase connection as a context manager into the CronApp's run method. The connection will automatically be closed when the ConApp's run me...
python
def request_token(self): """ Gets OAuth request token """ client = OAuth1( client_key=self._server_cache[self.client.server].key, client_secret=self._server_cache[self.client.server].secret, callback_uri=self.callback, ) request = {"auth": client} ...
python
def mnist_tutorial_jsma(train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE): """ ...