language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public int size() { int result = 0; for (O o : multiplicities.keySet()) { result += multiplicity(o); } return result; }
python
def append(self, result): """ Append a new Result to the list. :param result: Result to append :return: Nothing :raises: TypeError if result is not Result or ResultList """ if isinstance(result, Result): self.data.append(result) elif isinstanc...
python
def tensor_index(self, datapoint_index): """ Returns the index of the tensor containing the referenced datapoint. """ if datapoint_index >= self._num_datapoints: raise ValueError('Datapoint index %d is greater than the number of datapoints (%d)' %(datapoint_index, self._num_datapoints)) ...
python
def as_dict(self, absolute=False): """ Return the dependencies as a dictionary. Returns: dict: dictionary of dependencies. """ return { 'name': self.absolute_name() if absolute else self.name, 'path': self.path, 'dependencies': [{ ...
java
public static AnnotatorCache getInstance() { if (INSTANCE == null) { synchronized (AnnotatorCache.class) { if (INSTANCE == null) { INSTANCE = new AnnotatorCache(); } } } return INSTANCE; }
java
private void refreshItemViewHolder(@NonNull ViewHolder holder, boolean isRowDragging, boolean isColumnDragging) { int left = getEmptySpace() + mManager.getColumnsWidth(0, Math.max(0, holder.getColumnIndex())); int top = mManager.getRowsHeight(0, Math.max(0, holde...
java
public void setMemberServices(MemberServices memberServices) { this.memberServices = memberServices; if (memberServices instanceof MemberServicesImpl) { this.cryptoPrimitives = ((MemberServicesImpl) memberServices).getCrypto(); } }
python
def get_logging_file(maximum_logging_files=10, retries=2 ^ 16): """ Returns the logging file path. :param maximum_logging_files: Maximum allowed logging files in the logging directory. :type maximum_logging_files: int :param retries: Number of retries to generate a unique logging file name. :ty...
java
public void marshall(GitSubmodulesConfig gitSubmodulesConfig, ProtocolMarshaller protocolMarshaller) { if (gitSubmodulesConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gitSubmodulesConfig.ge...
java
private void processDumpFileContentsRecovery(InputStream inputStream) throws IOException { JsonDumpFileProcessor.logger .warn("Entering recovery mode to parse rest of file. This might be slightly slower."); BufferedReader br = new BufferedReader(new InputStreamReader( inputStream)); String line = br....
java
void appendHex( int value, int digits ) { if( digits > 1 ) { appendHex( value >>> 4, digits-1 ); } output.append( DIGITS[ value & 0xF ] ); }
python
def pythonise(id, encoding='ascii'): """Return a Python-friendly id""" replace = {'-': '_', ':': '_', '/': '_'} func = lambda id, pair: id.replace(pair[0], pair[1]) id = reduce(func, replace.iteritems(), id) id = '_%s' % id if id[0] in string.digits else id return id.encode(encoding)
java
public static Icon getAvatar(DiscordApi api, String avatarHash, String discriminator, long userId) { StringBuilder url = new StringBuilder("https://cdn.discordapp.com/"); if (avatarHash == null) { url.append("embed/avatars/") .append(Integer.parseInt(discriminator) % 5) ...
python
def print_summary(self) -> None: """ Prints the tasks' timing summary. """ print("Tasks execution time summary:") for mon_task in self._monitor_tasks: print("%s:\t%.4f (sec)" % (mon_task.task_name, mon_task.total_time))
python
def set_url (self, url): """Set the URL referring to a robots.txt file.""" self.url = url self.host, self.path = urlparse.urlparse(url)[1:3]
java
private List<String> getValues(UserCoreResult<?, ?, ?> results) { List<String> values = null; if (results != null) { try { if (results.getCount() > 0) { int columnIndex = results.getColumnIndex(COLUMN_VALUE); values = getColumnResults(columnIndex, results); } else { values = new ArrayList...
python
def get_angle_degrees(self, indices): """Return the angles between given atoms. Calculates the angle in degrees between the atoms with indices ``i, b, a``. The indices can be given in three ways: * As simple list ``[i, b, a]`` * As list of lists: ``[[i1, b1, a1], [i2, b...
python
def list(self, request, *args, **kwargs): """ To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can only see connected customers: - customers that the user owns - customers that have a project where user has a role Sta...
java
public Point<Object> getValues(Point<Integer> locations) { Point<Object> result; Object[] values; int i; if (locations.dimensions() != dimensions()) throw new IllegalArgumentException( "Dimension mismatch: space=" + dimensions() + ", locations=" + locations.dimensions()); ...
java
private void setWidth(int width) { contentParams.width = options.fullScreenPeek() ? screenWidth : width; content.setLayoutParams(contentParams); }
java
public boolean isSpecTopicInLevel(final SpecTopic topic) { final SpecTopic foundTopic = getClosestTopic(topic, false); return foundTopic != null; }
java
public void note(DiagnosticPosition pos, String key, Object ... args) { note(pos, diags.noteKey(key, args)); }
python
def extract_sequences(self, ids, new_path=None): """Will take all the sequences from the current file who's id appears in the ids given and place them in the new file path given.""" # Temporary path # if new_path is None: new_fasta = self.__class__(new_temp_path()) elif isinstanc...
python
def tick(self): """Return the time cost string as expect.""" string = self.passed if self.rounding: string = round(string) if self.readable: string = self.readable(string) return string
python
def get_absolute_tool_path(command): """ Given an invocation command, return the absolute path to the command. This works even if commnad has not path element and is present in PATH. """ assert isinstance(command, basestring) if os.path.dirname(command): return os.path.di...
java
public void forEach(final IntIntConsumer consumer) { final int[] entries = this.entries; final int initialValue = this.initialValue; @DoNotSub final int length = entries.length; for (@DoNotSub int i = 0; i < length; i += 2) { if (entries[i + 1] != initialValue) /...
java
public org.tensorflow.framework.OptimizerOptions getOptimizerOptions() { return optimizerOptions_ == null ? org.tensorflow.framework.OptimizerOptions.getDefaultInstance() : optimizerOptions_; }
java
public static Function<Object,BigInteger> methodForBigInteger(final String methodName, final Object... optionalParameters) { return new Call<Object,BigInteger>(Types.BIG_INTEGER, methodName, VarArgsUtil.asOptionalObjectArray(Object.class,optionalParameters)); }
python
def checkout(self, revision, options): """ Checkout a specific revision. :param revision: The revision identifier. :type revision: :class:`Revision` :param options: Any additional options. :type options: ``dict`` """ rev = revision.key self.rep...
java
@Nonnull public static EChange setUseSSL (final boolean bUseSSL) { return s_aRWLock.writeLocked ( () -> { if (s_bUseSSL == bUseSSL) return EChange.UNCHANGED; s_bUseSSL = bUseSSL; return EChange.CHANGED; }); }
python
def jwt_optional(fn): """ If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authenticat...
java
public JBBPDslBuilder Custom(final String type, final String name) { return this.Custom(type, name, null); }
python
def reduce_logsumexp(x, reduced_dim, extra_logit=None, name=None): """Numerically stable version of log(reduce_sum(exp(x))). Unlike other reductions, the output has the same shape as the input. Note: with a minor change, we could allow multiple reduced dimensions. Args: x: a Tensor reduced_dim: a dime...
python
def set_(package, question, type, value, *extra): ''' Set answers to debconf questions for a package. CLI Example: .. code-block:: bash salt '*' debconf.set <package> <question> <type> <value> [<value> ...] ''' if extra: value = ' '.join((value,) + tuple(extra)) fd_, fna...
python
def __start_timer(self, delay): """ Starts the reconnection timer :param delay: Delay (in seconds) before calling the reconnection method """ self.__timer = threading.Timer(delay, self.__reconnect) self.__timer.daemon = True self.__timer.start()
python
def get_hierarchy_traversal_session_for_hierarchy(self, hierarchy_id, proxy): """Gets the ``OsidSession`` associated with the hierarchy traversal service for the given hierarchy. arg: hierarchy_id (osid.id.Id): the ``Id`` of the hierarchy arg: proxy (osid.proxy.Proxy): a proxy ret...
java
public static Message DecodeFromBytes(byte[] rgbData, MessageTag defaultTag) throws CoseException { CBORObject messageObject = CBORObject.DecodeFromBytes(rgbData); if (messageObject.getType() != CBORType.Array) throw new CoseException("Message is not a COSE security Message"); ...
java
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map<?, ?> map) { buffer.append(map); }
java
private void calcPrincipalRotationVector() { // AxisAngle4d axisAngle = helixLayers.getByLowestAngle().getAxisAngle(); AxisAngle4d axisAngle = helixLayers.getByLargestContacts().getAxisAngle(); principalRotationVector = new Vector3d(axisAngle.x, axisAngle.y, axisAngle.z); }
python
def equals(self, actual_seq): """Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool """ try: expected = dict([(element, None) for element in self._expected_seq]) actual = dict([(element, None) for element in actual_s...
java
public Set<OIdentifiable> getOutEdgesHavingProperties(final OIdentifiable iVertex, Iterable<String> iProperties) { final ODocument vertex = iVertex.getRecord(); checkVertexClass(vertex); return filterEdgesByProperties((OMVRBTreeRIDSet) vertex.field(VERTEX_FIELD_OUT), iProperties); }
java
public void addBroadcastConnection(String name, DagConnection broadcastConnection) { this.broadcastConnectionNames.add(name); this.broadcastConnections.add(broadcastConnection); }
python
def query_by_assignment(self, assignment_id, end_time=None, start_time=None): """ Query by assignment. List grade change events for a given assignment. """ path = {} data = {} params = {} # REQUIRED - PATH - assignment_id """ID""" ...
python
def check_types(srctype, sinktype, linkMerge, valueFrom): # type: (Any, Any, Optional[Text], Optional[Text]) -> Text """Check if the source and sink types are "pass", "warning", or "exception". """ if valueFrom is not None: return "pass" if linkMerge is None: if can_assign_src_to_si...
python
def default_styles(): """Generate default ODF styles.""" styles = {} def _add_style(name, **kwargs): styles[name] = _create_style(name, **kwargs) _add_style('heading-1', family='paragraph', fontsize='24pt', fontweight='bold', ) _...
java
@Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { int high = highIndexOf(toElement, inclusive); return new BinarySet(comparator, list.subList(0, high+1), false); }
java
public Response serveFile( String uri, Properties header, File homeDir, boolean allowDirectoryListing ) { Response res = null; // Make sure we won't die of an exception later if ( !homeDir.isDirectory()) res = new Response( HTTP_INTERNALERROR, MIME...
java
protected static void main(String[] args, CliTool command) { JCommander jc = new JCommander(command); jc.addConverterFactory(new CustomParameterConverters()); jc.setProgramName(command.getClass().getAnnotation(Parameters.class).commandNames()[0]); ExitStatus exitStatus = ExitStatus.SUCCESS; t...
python
def register(self, context, stream): """ Register a newly constructed context and its associated stream, and add the stream's receive side to the I/O multiplexer. This method remains public while the design has not yet settled. """ _v and LOG.debug('register(%r, %r)', con...
java
@Override public ListCoreDefinitionsResult listCoreDefinitions(ListCoreDefinitionsRequest request) { request = beforeClientExecution(request); return executeListCoreDefinitions(request); }
python
async def apply_json(self, data): """Apply a JSON data object for a service """ if not isinstance(data, list): data = [data] result = [] for entry in data: if not isinstance(entry, dict): raise KongError('dictionary required') e...
python
def getDescriptor(self, dir): """ Detects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory """ try: return self.getProjectDescriptor(dir) except: try: return self.getPluginDescriptor(dir) except: raise UnrealManagerException('could not detect an ...
java
SoyExpression compile(ExprNode node, Label reattachPoint) { return asBasicCompiler(reattachPoint).compile(node); }
python
def findkey(d, *keys): """ Get a value from a dictionary based on a list of keys and/or list indexes. Parameters ---------- d: dict A Python dictionary keys: list A list of key names, or list indexes Returns ------- dict The composite dictionary object at ...
python
def hash_value(self, value, salt=''): '''Hashes the specified value combined with the specified salt. The hash is done HASHING_ROUNDS times as specified by the application configuration. An example usage of :class:``hash_value`` would be:: val_hash = hashing.hash_value('mys...
java
public void init(CalendarModel model, ProductTypeInfo productType, Date startTime, Date endTime, String description, String[] rgstrMeals, int iStatus) { m_model = (CachedCalendarModel)model; m_cachedInfo = new CachedInfo(productType, startTime, endTime, description, rgstrMeals, iStatus); }
java
public static <T> T unmarshal(JAXBContext self, String xml, Class<T> declaredType) throws JAXBException { return unmarshal(self.createUnmarshaller(), xml, declaredType); }
java
private ByteBuffer readBuffer(final byte[] content) throws IOException { final int startPos = getCheckBytesFrom(); if (startPos > content.length) { return null; } ByteBuffer buf; switch (getType()) { case MagicMimeEntry.STRING_TYPE: { final int len = getContent().length(); buf = ByteBuffer.allocat...
java
@Override public void bindJavaApp(String name, EJBBinding bindingObject) { String bindingName = buildJavaAppName(name); ejbJavaColonHelper.addAppBinding(moduleMetaData, bindingName, bindingObject); }
java
public Coding addSubType() { //3 Coding t = new Coding(); if (this.subType == null) this.subType = new ArrayList<Coding>(); this.subType.add(t); return t; }
java
@Contract(pure = true) @NotNull public static <T> Promise<T> schedule(@NotNull Promise<T> promise, long timestamp) { MaterializedPromise<T> materializedPromise = promise.materialize(); return Promise.ofCallback(cb -> getCurrentEventloop().schedule(timestamp, () -> materializedPromise.whenComplete(cb))); }
python
def get(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[_T]: """Remove and return an item from the queue. Returns an awaitable which resolves once an item is available, or raises `tornado.util.TimeoutError` after a timeout. ``timeout`` may be a number denoting a ti...
python
def _open_debug_interface(self, conn_id, callback, connection_string=None): """Enable debug interface for this IOTile device Args: conn_id (int): the unique identifier for the connection callback (callback): Callback to be called when this command finishes callba...
java
public static String constructUniqueName(String[] RDNs, String[] RDNValues, String parentDN) throws InvalidUniqueNameException { int length; if (RDNs != null) { length = RDNs.length; } else { return null; } if (length != RDNValues.length || length == 0) ...
java
private static JSONArray _fromArray( Object[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ...
python
def find_one_and_replace(self, filter, replacement, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace """ self._arctic_lib.check_quota() return self._collection.find_one_and_replace(filter, repl...
java
static public byte[] byteSubstring(byte[] bytes, int start, int end) { byte[] rc = null; if (0 > start || start > bytes.length || start > end) { // invalid start position if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Invalid st...
java
public static String getPermissionsVerbose(int permissions) { StringBuffer buf = new StringBuffer("Allowed:"); if ((PdfWriter.ALLOW_PRINTING & permissions) == PdfWriter.ALLOW_PRINTING) buf.append(" Printing"); if ((PdfWriter.ALLOW_MODIFY_CONTENTS & permissions) == PdfWriter.ALLOW_MODIFY_CONTENTS) buf....
java
protected boolean containWildcard(Object value) { if (!(value instanceof String)) { return false; } String casted = (String) value; return casted.contains(LIKE_WILDCARD.toString()); }
java
@Override public Object parse(String value) throws ParseException { if(value == null || value.isEmpty()) { return null; } dateFormat = createDateFormat(locale); dateFormat.setTimeZone(timeZone); return dateFormat.parse(value); }
python
def addValue(self, type_uri, value): """Add a single value for the given attribute type to the message. If there are already values specified for this type, this value will be sent in addition to the values already specified. @param type_uri: The URI for the attribute @...
java
public void marshall(CreateDocumentClassifierRequest createDocumentClassifierRequest, ProtocolMarshaller protocolMarshaller) { if (createDocumentClassifierRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarsha...
java
Element getElement(Node node) { if (node == null) { return null; } // element instance is cached as node user defined data and reused Object value = node.getUserData(BACK_REF); if (value != null) { return (Element) value; } Element el = new ElementImpl(this, node); node.setUserData(BACK_...
python
def protorpc_to_endpoints_error(self, status, body): """Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from ...
java
public void addSoftClause(int weight, final LNGIntVector lits) { final LNGIntVector rVars = new LNGIntVector(); this.softClauses.push(new MSSoftClause(lits, weight, LIT_UNDEF, rVars)); this.nbSoft++; }
java
public static ServerSocketBar create(InetAddress host, int port, int listenBacklog, boolean isEnableJni) throws IOException { return currentFactory().create(host, port, listenBacklog, isEnableJni); }
python
def get_media_url(self, context): """ Checks to see whether to use the normal or the secure media source, depending on whether the current page view is being sent over SSL. The USE_SSL setting can be used to force HTTPS (True) or HTTP (False). NOTE: Not all backends impl...
java
public static <T> T getLast(Iterable<T> iterable) { if (iterable instanceof RichIterable) { return ((RichIterable<T>) iterable).getLast(); } if (iterable instanceof RandomAccess) { return RandomAccessListIterate.getLast((List<T>) iterable); } ...
python
def _init_polling(self): """ Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll. """ with self.lock: if not self.running: return r = random.Random() ...
python
def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): """Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path...
python
def indication(self, pdu): """Direct this PDU to the appropriate server.""" if _debug: TCPServerDirector._debug("indication %r", pdu) # get the destination addr = pdu.pduDestination # get the server server = self.servers.get(addr, None) if not server: ...
python
def parse_buffer_to_ppm(data): """ Parse PPM file bytes to Pillow Image """ images = [] index = 0 while index < len(data): code, size, rgb = tuple(data[index:index + 40].split(b'\n')[0:3]) size_x, size_y = tuple(size.split(b' ')) file_size = len(code) + len(size) +...
python
def _nbinom_ztrunc_p(mu, k_agg): """ Calculates p parameter for truncated negative binomial Function given in Sampford 1955, equation 4 Note that omega = 1 / 1 + p in Sampford """ p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu # The upper bound n...
python
def visit_assert(self, node, parent): """visit a Assert node by returning a fresh instance of it""" newnode = nodes.Assert(node.lineno, node.col_offset, parent) if node.msg: msg = self.visit(node.msg, newnode) else: msg = None newnode.postinit(self.visit(n...
python
def methods(self, methods): """Setter method; for a description see the getter method.""" # We make sure that the dictionary is a NocaseDict object, and that the # property values are CIMMethod objects: # pylint: disable=attribute-defined-outside-init self._methods = NocaseDict()...
python
def make_dist_mat(xy1, xy2, longlat=True): """ Return a distance matrix between two set of coordinates. Use geometric distance (default) or haversine distance (if longlat=True). Parameters ---------- xy1 : numpy.array The first set of coordinates as [(x, y), (x, y), (x, y)]. xy2 : n...
python
def login(self): """ Return True if we successfully logged into this Koji hub. We support GSSAPI and SSL Client authentication (not the old-style krb-over-xmlrpc krbLogin method). :returns: deferred that when fired returns True """ authtype = self.lookup(self.pr...
java
public static CommerceWishList findByUUID_G(String uuid, long groupId) throws com.liferay.commerce.wish.list.exception.NoSuchWishListException { return getPersistence().findByUUID_G(uuid, groupId); }
java
ScheduledExecutorService createSchedulerExecutor(final String prefix) { ThreadFactory threadFactory = new ThreadFactory() { private int counter = 0; @Override public Thread newThread(Runnable runnable) { return new Thread(runnable, prefix + ++counter); } }; ScheduledExecutorService executor = java...
python
def bam2fastq(job, bamfile, univ_options): """ split an input bam to paired fastqs. ARGUMENTS 1. bamfile: Path to a bam file 2. univ_options: Dict of universal arguments used by almost all tools univ_options |- 'dockerhub': <dockerhub to use> +- 'java_Xmx': ...
java
public String confusionMatrix(){ int nClasses = numClasses(); if(confusion == null){ return "Confusion matrix: <no data>"; } //First: work out the maximum count List<Integer> classes = confusion.getClasses(); int maxCount = 1; for (Integer i : classe...
java
public void addOrUpdate(long[] indexes, double value) { long[] physicalIndexes = isView() ? translateToPhysical(indexes) : indexes; for (int i = 0; i < length; i++) { long[] idx = getUnderlyingIndicesOf(i).asLong(); if (Arrays.equals(idx, physicalIndexes)) { // ...
python
def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080, interval=1, reloader=False, **kargs): """ Runs bottle as a web server. """ app = app if app else default_app() quiet = bool(kargs.get('quiet', False)) # Instantiate server, if it is a class instead of an instance if isinsta...
java
public static UUID generateTxnId(int epoch, int msb, long lsb) { long msb64Bit = (long) epoch << 32 | msb & 0xFFFFFFFFL; return new UUID(msb64Bit, lsb); }
python
def luhn_checksum(number, chars=DIGITS): ''' Calculates the Luhn checksum for `number` :param number: string or int :param chars: string >>> luhn_checksum(1234) 4 ''' length = len(chars) number = [chars.index(n) for n in reversed(str(number))] return ( sum(number[::2])...
python
def deprecated(new_name: str): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. """ def decorator(func): @wraps(func) def new_func(*args, **kwargs): warnings.simplefilter('a...
python
def create_attr_filter(request, mapped_class): """Create an ``and_`` SQLAlchemy filter (a ClauseList object) based on the request params (``queryable``, ``eq``, ``ne``, ...). Arguments: request the request. mapped_class the SQLAlchemy mapped class. """ mapping = { ...
java
public static final Function<String,Float> toFloat(final int scale, final RoundingMode roundingMode) { return new ToFloat(scale, roundingMode); }
java
public final String getCommaSeparatedArgumentNames(final int less) { final List<SgArgument> args = getArguments(less); return commaSeparated(args); }
python
def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self err.args = (err.message,) raise