language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public SDVariable mmul(SDVariable x, SDVariable y) { return mmul(null, x, y); }
python
def addBeam(beamState, labeling): """ add beam if it does not yet exist """ if labeling not in beamState.entries: beamState.entries[labeling] = BeamEntry()
python
def insert(self, state, token): """change internal state, return action""" if token == EndSymbol(): return self[state][EndSymbol()] from pydsl.check import check symbol_list = [x for x in self[state] if isinstance(x, TerminalSymbol) and check(x.gd, [token])] if not sy...
java
protected final void putString(String s) { ensureCapacity(position + (s.length() * 2) + 1); System.arraycopy(s.getBytes(), 0, buffer, position, s.length()); position += s.length(); buffer[position++] = 0; }
python
def add_folder(self, dirname, watch=True): """Recursively add all files in a folder to the database By "all files" I mean, "all files that are resource files or library files". It will silently ignore files that don't look like they belong in the database. Pity the fool who uses...
java
@BetaApi public final ListHttpsHealthChecksPagedResponse listHttpsHealthChecks(ProjectName project) { ListHttpsHealthChecksHttpRequest request = ListHttpsHealthChecksHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .build(); return listHttpsHeal...
java
public EClass getIfcMechanicalFastenerType() { if (ifcMechanicalFastenerTypeEClass == null) { ifcMechanicalFastenerTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(317); } return ifcMechanicalFastenerTypeEClass; }
python
def get_file_clusters(self, this_date, timeout=None): """ File similarity clusters for a given time frame. VirusTotal has built its own in-house file similarity clustering functionality. At present, this clustering works only on PE, PDF, DOC and RTF files and is based on a very simple structura...
java
public static Project asProject( JsonObject json) { return ProjectBuilder.with( asSystemInputDef( json.get( INPUTDEF_KEY))) .systemInputRef( asSystemInputRef( json.get( INPUTDEF_KEY))) .generators( asGeneratorSet( json.get( GENERATORS_KEY))) .generatorsRef( asGeneratorSetRef( json.get...
python
def modules(self): """Returns an iterator of the actual modules, not just their names :returns: generator, each module under self.controller_prefix """ for modname in self.module_names: module = importlib.import_module(modname) yield module
java
private boolean valueEquals(V leftValue, V rightValue) { if (leftValue == rightValue) { return true; } if (leftValue == null || rightValue == null) { return false; } return leftValue.equals(rightValue); }
python
def debug_print_tree( self, spacing='' ): ''' *Debug only* method for outputting the tree. ''' print (spacing+" "+str(self.word_id)+" "+str(self.text)) if (self.children): spacing=spacing+" " for child in self.children: child.debug_print_tree(spacing)
python
def open_fp(self, fp): # type: (BinaryIO) -> None ''' Open up an existing ISO for inspection and modification. Note that the file object passed in here must stay open for the lifetime of this object, as the PyCdlib class uses it internally to do writing and reading opera...
java
@Override public @Nonnull ApplicationContextBuilder include(@Nullable String... configurations) { if (configurations != null) { this.configurationIncludes.addAll(Arrays.asList(configurations)); } return this; }
java
private Map<Integer, List<DelayedEntry>> doStoreUsingBatchSize(List<DelayedEntry> sortedDelayedEntries) { Map<Integer, List<DelayedEntry>> failsPerPartition = new HashMap<>(); int page = 0; List<DelayedEntry> delayedEntryList; while ((delayedEntryList = getBatchChunk(sortedDelayedEntries...
python
def load_external_data_for_tensor(tensor, base_dir): # type: (TensorProto, Text) -> None """ Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data. """ if tensor.HasField("raw_data"): # already loaded ...
python
def handler(self, handler_class): """Link to an API handler class (e.g. piston or DRF).""" self.handler_class = handler_class # we take the docstring from the handler class, not the methods if self.docs is None and handler_class.__doc__: self.docs = clean_docstring(handler_cl...
python
def data(self, data): """Store a copy of the data.""" self._data = {det: d.copy() for (det, d) in data.items()}
java
public ResponseResourceMetricKey withDimensions(java.util.Map<String, String> dimensions) { setDimensions(dimensions); return this; }
java
protected final void bufferFullMessage(StreamSourceFrameChannel messageChannel) { if (messageChannel.getType() == WebSocketFrameType.TEXT) { readBufferedText(messageChannel, new BufferedTextMessage(getMaxTextBufferSize(), true)); } else if (messageChannel.getType() == WebSocketFrameType.BINA...
java
private static String join(Collection<?> args, String delim) { StringBuilder buf = new StringBuilder(); for (Object arg : args) { if (buf.length()>0) buf.append(delim); buf.append(arg); } return buf.toString(); }
java
void startEngine() throws ServerStartException { // setting up the server final boolean isDaemon = true; final boolean isSilent = false; final HsqlProperties hsqlProp = new HsqlProperties(); // gives the chance to the descriptors to contribute to the server configuration. final AtomicInteger dbCounter = ...
python
def setOption(self, name, value): """ Set an AMPL option to a specified value. Args: name: Name of the option to be set (alphanumeric without spaces). value: The value the option must be set to. Raises: InvalidArgumet: if the option name is not vali...
java
public Symbol getSymbol(String name) { return symbolTable == null ? null : symbolTable.get(name); }
java
public static int e(String tag, String msg) { return e(SUBSYSTEM.MAIN, tag, msg); }
java
public static EncryptionUtil getInstance(String key, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { if (instance == null) { synchronized (EncryptionUtil.class) { if (instance == null) { instance = ...
python
def enable_service_freshness_checks(self): """Enable service freshness checks (globally) Format of the line that triggers function call:: ENABLE_SERVICE_FRESHNESS_CHECKS :return: None """ if not self.my_conf.check_service_freshness: self.my_conf.modified_att...
java
public DrawerView removeFixedItemById(long id) { for (DrawerItem item : mAdapterFixed.getItems()) { if (item.getId() == id) { mAdapterFixed.remove(item); updateFixedList(); return this; } } return this; }
java
private void configureExistingTaskScheduler(TaskScheduler taskScheduler, BugsnagScheduledTaskExceptionHandler errorHandler) { try { Field errorHandlerField = taskScheduler.getClass().getDeclaredField("errorHandler"); err...
python
def get_face_color(self, increment=1): """ Returns the current face, then increments the face by what's specified """ i = self.face_colors_index self.face_colors_index += increment if self.face_colors_index >= len(self.face_colors): self.face_colors_index = ...
java
public void writeByteBufferPart(byte[] buffer, int offset, int length) throws IOException { while (length > 0) { int sublen = length; if (0x8000 < sublen) sublen = 0x8000; os.write('b'); os.write(sublen >> 8); os.write(sub...
java
private Map<String, Integer> getAttemptsMap(String projectId, String eventCollection) throws IOException { Map<String, Integer> attempts = new HashMap<String, Integer>(); if (eventStore instanceof KeenAttemptCountingEventStore) { KeenAttemptCountingEventStore res = (KeenAttemptCountingEventS...
java
public String toStringAndClear(final Charset charset) { String str = toString(0, count, charset); clear(); return str; }
java
private Expr parseBitwiseOrExpression(EnclosingScope scope, boolean terminated) { int start = index; Expr lhs = parseBitwiseXorExpression(scope, terminated); if (tryAndMatch(terminated, VerticalBar) != null) { Expr rhs = parseExpression(scope, terminated); return annotateSourceLocation(new Expr.BitwiseOr(T...
python
def authDomainUser(self, realmname, username, password, environ): """Returns True if this username/password pair is valid for the realm, False otherwise. Used for basic authentication.""" try: apikey = self.user_manager.get_user_api_key(username, create=None) return apike...
java
int getElementID(int column) { if (cells[column] == null) return NULL; else if (Cell.class.isInstance(cells[column])) return CELL; else if (Table.class.isInstance(cells[column])) return TABLE; return -1; }
java
public static void checkConfigParameter(boolean condition, Object parameter, String name, String errorMessage) throws IllegalConfigurationException { if (!condition) { throw new IllegalConfigurationException("Invalid configuration value for " + name + " : " + parameter + " - " + errorMessage); } }
java
public EraPeriod getTargetPeriod(final Date date) { ArgUtils.notNull(date, "date"); for(EraPeriod period : periods) { if(period.contains(date)) { return period; } } return EraPeriod.UNKNOWN_PERIOD; }
java
public static void swapRows(DenseDoubleMatrix2D matrix, long row1, long row2) { double temp = 0; long cols = matrix.getColumnCount(); for (long col = 0; col < cols; col++) { temp = matrix.getDouble(row1, col); matrix.setDouble(matrix.getDouble(row2, col), row1, col); matrix.setDouble(temp, row2, col); ...
java
@Override protected boolean performExecution() throws MojoExecutionException, MojoFailureException { boolean updateStaleFileTimestamp = false; try { // Setup the Tool's execution environment ToolExecutionEnvironment environment = null; try { //...
java
@SuppressWarnings("unchecked") public <ContainingType extends MessageLite> GeneratedMessageLite.GeneratedExtension<ContainingType, ?> findLiteExtensionByNumber( final ContainingType containingTypeDefaultInstance, final int fieldNumber) { return (GeneratedMessageLite.GeneratedExte...
java
public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || notify.isEmpty()) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((...
java
public java.lang.String getTabindex() { return (java.lang.String) getStateHelper().eval(PropertyKeys.tabindex); }
java
protected void copy(final CacheEntry cacheEntry, final ServletOutputStream ostream, final Range range) throws IOException { IOException exception = null; final InputStream resourceInputStream = cacheEntry.getResource().streamContent(); final InputStream istream = new BufferedInputStream(resourceInputStream, getI...
python
def count_hom_alt(self, axis=None): """Count homozygous alternate genotypes. Parameters ---------- axis : int, optional Axis over which to count, or None to perform overall count. """ b = self.is_hom_alt() return np.sum(b, axis=axis)
java
public URL getBookmarkableURL(FacesContext context) throws MalformedURLException { ExternalContext extContext = context.getExternalContext(); return new URL(extContext.getRequestScheme(), extContext.getRequestServerName(), extContext.getRequestServerPort(), ...
java
public JsonValue get(String name) { if (name == null) { throw new NullPointerException("name is null"); } int index = indexOf(name); return index != -1 ? values.get(index) : null; }
python
def setItemStyle(self, itemStyle): """ Sets the item style that will be used for this widget. If you are trying to set a style on an item that has children, make sure to turn off the useGroupStyleWithChildren option, or it will always display as a group. ...
java
public Assignment model() { if (this.result == UNDEF) throw new IllegalStateException("Cannot get a model as long as the formula is not solved. Call 'solve' first."); return this.result != UNSATISFIABLE ? this.createAssignment(this.solver.model()) : null; }
java
public static final AlgorithmParameterSpec getMaxAllowedParameterSpec( String transformation) throws NoSuchAlgorithmException { // Android-changed: Remove references to CryptoPermission and throw early // if transformation == null or isn't valid. // // CryptoPermission cp = g...
java
@Override public final long count(final String filename) { final Query searchQuery = new Query(Criteria.where("filename").is(filename)); return mongoTemplate.count(searchQuery, FamilyDocumentMongo.class); }
python
def setProperty(self, name, value): ''' Sets one of the supported property values of the speech engine listed above. If a value is invalid, attempts to clip it / coerce so it is valid before giving up and firing an exception. @param name: Property name @type name: str ...
java
public void marshall(StartGameSessionPlacementRequest startGameSessionPlacementRequest, ProtocolMarshaller protocolMarshaller) { if (startGameSessionPlacementRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
python
def get_file_mode_for_reading(context): """Get file mode for reading from tar['format']. This should return r:*, r:gz, r:bz2 or r:xz. If user specified something wacky in tar.Format, that's their business. In theory r:* will auto-deduce the correct format. """ format = context['tar'].get('form...
java
public final void mSKIP() throws RecognitionException { try { int _type = SKIP; int _channel = DEFAULT_TOKEN_CHANNEL; // hql.g:60:6: ( 'skip' ) // hql.g:60:8: 'skip' { match("skip"); if (state.failed) return; } state.type = _type; state.channel = _channel; } finally { // do for sur...
python
def program_supports_compression (program, compression): """Decide if the given program supports the compression natively. @return: True iff the program supports the given compression format natively, else False. """ if program in ('tar', ): return compression in ('gzip', 'bzip2', 'xz', 'l...
python
def get_all_voronoi_polyhedra(self, structure): """Get the Voronoi polyhedra for all site in a simulation cell Args: structure (Structure): Structure to be evaluated Returns: A dict of sites sharing a common Voronoi facet with the site n mapped to a directory...
python
def to_text(self, tree, force_root=False): """ Extract text from tags. Skip any selectors specified and include attributes if specified. Ignored tags will not have their attributes scanned either. """ self.extract_tag_metadata(tree) text = [] attributes...
java
public boolean canEncode(final CharSequence cs) { if (cs == null) { return true; } final String cstring = Objects.toString(cs); final byte[] stringAsByte = this.charset.getBytes(cstring); return Objects.equals(cstring, String.valueOf( this.charset.decodeString(this.charset.getBytes(cst...
java
public void marshall(ActivitiesResponse activitiesResponse, ProtocolMarshaller protocolMarshaller) { if (activitiesResponse == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(activitiesResponse.getIte...
java
public void setDocid(String v) { if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_docid == null) jcasType.jcas.throwFeatMissing("docid", "de.julielab.jules.types.ace.Document"); jcasType.ll_cas.ll_setStringValue(addr, ((Document_Type)jcasType).casFeatCode_docid, v);}
java
@On(Orchid.Lifecycle.Shutdown.class) public void onEndSession(Orchid.Lifecycle.Shutdown event) { executor.shutdown(); }
python
def _load_object(self, obj): """Recursively load a PyPhi object. PyPhi models are recursively loaded, using the model metadata to recreate the original object relations. Lists are cast to tuples because most objects in PyPhi which are serialized to lists (eg. mechanisms and purv...
java
@Override public void revertFeatures(@NonNull INDArray[] features, INDArray[] maskArrays) { for (int i = 0; i < features.length; i++) { revertFeatures(features, maskArrays, i); } }
java
@Override public com.liferay.commerce.notification.model.CommerceNotificationTemplateUserSegmentRel createCommerceNotificationTemplateUserSegmentRel( long commerceNotificationTemplateUserSegmentRelId) { return _commerceNotificationTemplateUserSegmentRelLocalService.createCommerceNotificationTemplateUserSegmentRel(...
java
@Override public void setRefreshOn(boolean enabled) { boolean changed = enabled != refreshEnabled; refreshEnabled = enabled; if (changed) { updateRefreshTimer(); } }
java
private CodecFactory getCompressionCodec(Map<String, String> conf) { if (getBoolean(conf, CONF_COMPRESS, false)) { int deflateLevel = getInt(conf, CONF_DEFLATE_LEVEL, CodecFactory.DEFAULT_DEFLATE_LEVEL); int xzLevel = getInt(conf, CONF_XZ_LEVEL, CodecFactory.DEFAULT_XZ_LEVEL); String outputCodec = conf.get(...
java
public ServiceFuture<HybridRunbookWorkerGroupInner> updateAsync(String resourceGroupName, String automationAccountName, String hybridRunbookWorkerGroupName, RunAsCredentialAssociationProperty credential, final ServiceCallback<HybridRunbookWorkerGroupInner> serviceCallback) { return ServiceFuture.fromResponse(up...
java
public static List<IndexDefinition> get() throws EFapsException { final List<IndexDefinition> ret = new ArrayList<>(); final QueryBuilder queryBldr = new QueryBuilder(CIAdminIndex.IndexDefinition); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selUU...
java
private void fireSocketClosedEvent(final Exception listenerException) { synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { SocketNodeEventListener snel = (SocketNodeEventListener) iter.next(); if (snel != null) { ...
java
@Internal public void addOperator(StreamTransformation<?> transformation) { Preconditions.checkNotNull(transformation, "transformation must not be null."); this.transformations.add(transformation); }
python
def get_source(self, source, clean=False, callback=None): """ Download a file from a URL and return it wrapped in a row-generating acessor object. :param spec: A SourceSpec that describes the source to fetch. :param account_accessor: A callable to return the username and password to us...
java
public Helix getByLargestContactsNotLowestAngle() { double contacts = 0; Helix lowest = getByLowestAngle(); // TODO why are there helices with almost identical helix parameters?? double angle = lowest.getAngle() + 0.05; Helix largest = null; for (Helix helix: helices) { if (helix == lowest) { continu...
python
def p_ConstValue_null(p): """ConstValue : null""" p[0] = model.Value(type=model.Value.NULL, value=p[1])
python
def remove_unused_links(dirpath, required_links): """Recursively remove any links in dirpath which are not contained in required_links. :param str dirpath: Absolute path of directory to search. :param container required_links: Container of "in use" links which should not be removed, ...
python
def add(self, username, courseid, taskid, consumer_key, service_url, result_id): """ Add a job in the queue :param username: :param courseid: :param taskid: :param consumer_key: :param service_url: :param result_id: """ search = {"username": userna...
java
public static void checkInvariantV( final boolean condition, final String format, final Object... objects) { checkInvariantV("<unspecified>", condition, format, objects); }
java
public Attribute removeAttribute(String name) { for (int i = _attributes.size() - 1; i >= 0; i--) { Attribute attr = _attributes.get(i); if (attr.getName().equals(name)) { _attributes.remove(i); return attr; } } return null; }
python
def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): ...
java
public static void stream(final Readable readable, final VcfStreamListener listener) throws IOException { StreamingVcfParser.stream(readable, listener); }
java
private int parseDefaultOffsetFields(String text, int start, char separator, int[] parsedLen) { int max = text.length(); int idx = start; int[] len = {0}; int hour = 0, min = 0, sec = 0; do { hour = parseOffsetFieldWithLocalizedDigits(text, idx, 1, 2, 0, MAX_OFFSET_H...
python
def kegg_mapping_and_metadata_parallelize(self, sc, kegg_organism_code, custom_gene_mapping=None, outdir=None, set_as_representative=False, force_rerun=False): """Map all genes in the model to KEGG IDs using the KEGG service. Steps: 1. Download ...
python
def _get_movielens_path(): """ Get path to the movielens dataset file. """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'movielens.zip')
java
public Object set(int index, Object value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "set", new Object[]{Integer.valueOf(index), value}); try { // Need to validate the index and call getInternal here (rather than getValue) because // we don't want a Sch...
java
public static void log(Logger logger, Level level, String message, Object[] parameters) { if (logger.isLoggable(level)) { String msg = localize(logger, message); try { msg = MessageFormat.for...
python
def crps_gaussian(x, mu, sig, grad=False): """ Computes the CRPS of observations x relative to normally distributed forecasts with mean, mu, and standard deviation, sig. CRPS(N(mu, sig^2); x) Formula taken from Equation (5): Calibrated Probablistic Forecasting Using Ensemble Model Output ...
python
def galcencyl_to_XYZ(R,phi,Z,Xsun=1.,Zsun=0.,_extra_rot=True): """ NAME: galcencyl_to_XYZ PURPOSE: transform cylindrical Galactocentric coordinates to XYZ coordinates (wrt Sun) INPUT: R, phi, Z - Galactocentric cylindrical coordinates Xsun - cylindrical distance to the ...
python
def Run(self): """Event loop.""" if data_store.RelationalDBEnabled(): data_store.REL_DB.RegisterMessageHandler( self._ProcessMessageHandlerRequests, self.well_known_flow_lease_time, limit=100) data_store.REL_DB.RegisterFlowProcessingHandler(self.ProcessFlow) try: ...
python
def _generic_definefont_parser(self, obj): """A generic parser for several DefineFontX.""" obj.FontID = unpack_ui16(self._src) bc = BitConsumer(self._src) obj.FontFlagsHasLayout = bc.u_get(1) obj.FontFlagsShiftJIS = bc.u_get(1) obj.FontFlagsSmallText = bc.u_get(1) ...
java
public PlanNode findAtOrBelow( Traversal order, Set<Type> typesToFind ) { LinkedList<PlanNode> queue = new LinkedList<PlanNode>(); queue.add(this); while (!queue.isEmpty()) { PlanNode aNode = queue.poll(); switch (order) { ...
python
def update(self, sequence=None, **mapping): """Add multiple elements to the fact.""" if sequence is not None: if isinstance(sequence, dict): for slot in sequence: self[slot] = sequence[slot] else: for slot, value in sequence: ...
python
def add_gateway_router(self, router, body=None): """Adds an external network gateway to the specified router.""" return self.put((self.router_path % router), body={'router': {'external_gateway_info': body}})
java
private NodeList getByName(String name) { NodeList answer = new NodeList(); for (Object child : children()) { if (child instanceof Node) { Node childNode = (Node) child; Object childNodeName = childNode.name(); if (childNodeName instanceof QNam...
java
public void addTable(VoltTable other) { if (m_readOnly) { throw new IllegalStateException("Table is read-only. Make a copy before changing."); } checkHasExactSchema(other); // Allow the buffer to grow to max capacity m_buffer.limit(m_buffer.capacity()); Byt...
java
public base_response forcehafailover(Boolean force) throws Exception { hafailover resource = new hafailover(); resource.set_force(force); options option = new options(); option.set_action("force"); base_response result = resource.perform_operation(this,option); return result; }
java
@Deprecated public void text(Writer out, char c) throws InvalidXMLException, IOException { if (c >= 63 && c <= 127 || c >= 39 && c <= 59 || c >= 32 && c <= 37 || c == 38 || c > 127 && !_sevenBitEncoding || c == 10 || c == 13 || c == 61 || c == 9) { out.write(c); } else { if (...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case XtypePackage.XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER: setTypeProvider((IJvmTypeReferenceProvider)newValue); return; } super.eSet(featureID, newValue); }
java
public void registerCloseables(final Collection<Closeable> registry, Closeable... closeables) { registry.addAll(Arrays.asList(closeables)); addListener(resource -> { for (Closeable closeable : closeables) { if (closeable == RedisChannelHandler.this) { co...
python
def t_asm(t): r'\b[aA][sS][mM]\b' global ASM, ASMLINENO, IN_STATE t.lexer.begin('asm') ASM = '' ASMLINENO = t.lexer.lineno IN_STATE = True
python
def __connect(host, port, username, password, private_key): """ Establish remote connection :param host: Hostname or IP address to connect to :param port: Port number to use for SSH :param username: Username credentials for SSH access :param password: Password credential...