language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def calculate_mean(samples, weights): r'''Calculate the mean of weighted samples (like the output of an importance-sampling run). :param samples: Matrix-like numpy array; the samples to be used. :param weights: Vector-like numpy array; the (unnormalized) importance weights. ''' ...
python
def make_format(self, fmt, width): """ Make subreport text in a specified format """ if not self.report_data: return for data_item in self.report_data: if data_item.results: if fmt is None or fmt == 'text': ...
java
public void init(Cluster cluster, Map<String, Node> nodeIdToNode) { _cluster = cluster; _nodeIdToNode = nodeIdToNode; }
java
public Map<String, NailStats> getNailStats() { Map<String, NailStats> result = new TreeMap(); synchronized (allNailStats) { for (Map.Entry<String, NailStats> entry : allNailStats.entrySet()) { result.put(entry.getKey(), (NailStats) entry.getValue().clone()); } } return result; }
java
public void applyAsSystemProperties (@Nullable final String... aPropertyNames) { if (isRead () && aPropertyNames != null) for (final String sProperty : aPropertyNames) { final String sConfigFileValue = getAsString (sProperty); if (sConfigFileValue != null) { SystemPro...
java
public void stop() { this.logger.info( "Agent '" + getAgentId() + "' is about to be stopped." ); // Stop the timer if( this.heartBeatTimer != null ) { this.heartBeatTimer.cancel(); this.heartBeatTimer = null; } // Prevent NPE for successive calls to #stop() if( this.messagingClient == null ) ret...
python
def _copytoscratch(self, maps): """Copies the data in maps to the scratch space. If the maps contain arrays that are not the same shape as the scratch space, a new scratch space will be created. """ try: for p in self.inputs: self._scratch[p][:] = map...
python
def minimize(self, bAsync = True): """ Minimize the window. @see: L{maximize}, L{restore} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """ if bAsync: ...
python
def interevent_time(records): """ The interevent time between two records of the user. """ inter_events = pairwise(r.datetime for r in records) inter = [(new - old).total_seconds() for old, new in inter_events] return summary_stats(inter)
java
public LongStream longs(long streamSize) { if (streamSize < 0L) throw new IllegalArgumentException(BAD_SIZE); return StreamSupport.longStream (new RandomLongsSpliterator (0L, streamSize, Long.MAX_VALUE, 0L), false); }
python
def find_compiled_files(self): """Find compiled Python files recursively in the root path :return: list of absolute file paths """ files = self._find_files() self.announce( "found '{}' compiled python files in '{}'".format( len(files), self.root ...
java
public void addTransition(String localName, ElementSelector<T> target) { addTransition(new QName(localName), target); }
java
public static Class classForName(String type) throws ClassNotFoundException { //we now assign the array to safekeep the reference on // the local variable stack, that way //we can avoid synchronisation calls ClassLoaderExtension [] loaderPlugins = classLoadingExtensions; ...
java
public void write(ResultSet resultSet, CellProcessor[] writeProcessors) throws SQLException, IOException { if( resultSet == null ) { throw new NullPointerException("ResultSet cannot be null"); } if( writeProcessors == null ) { throw new NullPointerException("CellProcessor[] cannot be null"); } writeH...
python
def import_surf_mesh(file_name): """ Generates a NURBS surface object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS surface :rtype: NURBS.Surface """ raw_content = read_file(file_name) raw_content = raw_content.split("\n") content = [] ...
java
public boolean distributeForget() throws SystemException { if (tc.isEntryEnabled()) Tr.entry(tc, "distributeForget", this); boolean retryRequired = false; // indicates whether retry necessary final int resourceCount = _resourceObjects.size(); // Browse through the participa...
java
public Object getProperty(Object object, String name) { if (hasOverrideGetProperty(name) && getJavaClass().isInstance(object)) { return getPropertyMethod.invoke(object, new Object[]{name}); } return super.getProperty(object, name); }
java
public static Builder builder(ServiceMetadata serviceMetadata) { checkNotNull(serviceMetadata, "serviceMetadata: null"); ServerDto server = ServerDto.builder() .setHostName(serviceMetadata.getHostName()) .setStartupDateTime(serviceMetadata.getStartupTime()) .build(); BuildDto build =...
java
public int frameSize() { switch (layerDescription) { case 3: // Layer 1 return (12 * getBitRate() / getSampleRate() + (paddingBit ? 1 : 0)) * 4; case 2: case 1: // Layer 2 and 3 if (audioVersionId == 3) {...
java
public static String getDirName(Props props) { String dirSuffix = props.get(CommonJobProperties.NESTED_FLOW_PATH); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { dirSuffix = props.get(CommonJobProperties.JOB_ID); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { throw new Run...
python
def filter_ascii(lst): ''' removes words with accent chars etc. (most accented words in the english lookup exist in the same table unaccented.) ''' return [word for word in lst if all(ord(c) < 128 for c in word)]
java
final public void addOffset(Integer start, Integer end) { if (tokenOffset == null) { setOffset(start, end); } else if ((start == null) || (end == null)) { // do nothing } else if (start > end) { throw new IllegalArgumentException("Start offset after end offset"); } else { tokenOf...
java
private byte encodeTargetDiscriminator() { byte result = 0; if (Positions.isReadable(targetPosition)) { result |= 1; } if (Positions.isWritable(targetPosition)) { result |= 2; } return result; }
java
static <T extends Gene<?, T>, C extends Comparable<? super C>> CompositeAlterer<T, C> join( final Alterer<T, C> a1, final Alterer<T, C> a2 ) { return CompositeAlterer.of(a1, a2); }
python
def ae_latent_softmax(latents_pred, latents_discrete, hparams): """Latent prediction and loss.""" vocab_size = 2 ** hparams.z_size if hparams.num_decode_blocks < 2: latents_logits = tf.layers.dense(latents_pred, vocab_size, name="extra_logits") if hparams.logit_normali...
python
def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affi...
python
def random_pairs_with_replacement(n, shape, random_state=None): """make random record pairs""" if not isinstance(random_state, np.random.RandomState): random_state = np.random.RandomState(random_state) n_max = max_pairs(shape) if n_max <= 0: raise ValueError('n_max must be larger than...
python
def parity_even_p(state, marked_qubits): """ Calculates the parity of elements at indexes in marked_qubits Parity is relative to the binary representation of the integer state. :param state: The wavefunction index that corresponds to this state. :param marked_qubits: The indexes to be considered i...
python
def scrape_file(self, file, encoding=None, base_url=None): '''Scrape a file for links. See :meth:`scrape` for the return value. ''' elements = self.iter_elements(file, encoding=encoding) link_contexts = set() link_infos = self._element_walker.iter_links(elements) ...
java
public boolean moveTo (int placeId) { // make sure the placeId is valid if (placeId < 0) { log.warning("Refusing moveTo(): invalid placeId " + placeId + "."); return false; } // first check to see if our observers are happy with this move request if (...
python
def get_subdomain_ops_at_txid(txid, proxy=None, hostport=None): """ Get the list of subdomain operations added by a txid Returns the list of operations ([{...}]) on success Returns {'error': ...} on failure """ assert proxy or hostport, 'Need proxy or hostport' if proxy is None: prox...
python
def parametrize_grid(self, debug=False): """ Performs Parametrization of grid equipment: i) Sets voltage level of MV grid, ii) Operation voltage level and transformer of HV/MV station, iii) Default branch types (normal, aggregated, settlement) Args ...
java
public synchronized void enableGestureDetector() { final GVRTouchPadGestureListener gestureListener = new GVRTouchPadGestureListener() { @Override public boolean onSwipe(MotionEvent e, Action action, float vx, float vy) { if (null != mGVRMain) { mGVRMa...
python
def untranslateName(s): """Undo Python conversion of CL parameter or variable name.""" s = s.replace('DOT', '.') s = s.replace('DOLLAR', '$') # delete 'PY' at start of name components if s[:2] == 'PY': s = s[2:] s = s.replace('.PY', '.') return s
java
public static AmazonSQS getClient() { if (sqsClient != null) { return sqsClient; } if (Config.IN_PRODUCTION) { sqsClient = AmazonSQSClientBuilder.standard().build(); } else { sqsClient = AmazonSQSClientBuilder.standard(). withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x"...
java
public static URI newUri(final String url, final boolean strict) throws URISyntaxException { /* * Java's parsing thinks that the host is the scheme if there isn't a scheme. Add the default if there is * no scheme yet */ checkNotNull(Strings.emptyToNull(url), "Cannot create U...
python
def init(venv_name): """Initializez a virtualenv""" inenv = InenvManager() inenv.get_prepped_venv(venv_name, skip_cached=False) if not os.getenv(INENV_ENV_VAR): activator_warn(inenv) click.secho("Your venv is ready. Enjoy!", fg='green')
java
public final Latency withMedian(double value) { double newValue = value; return new Latency( newValue, this.percentile98th, this.percentile99th, this.percentile999th, this.mean, this.min, this.max); }
java
public static void setProperties(Object obj, Properties props) throws Exception { for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); if (props.containsKey(field.getName())) { set(field, obj, props.getProperty(field.getName())); ...
java
public static final double pwrLawNextDouble(final int ppo, final double curPoint, final boolean roundToInt, final double logBase) { final double cur = (curPoint < 1.0) ? 1.0 : curPoint; double gi = round((logB(logBase, cur) * ppo) ); //current generating index double next; do { final double ...
java
public void removeConnectionEventListener( final ConnectionEventListener listener) { if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, "removeConnectionEventListener", listener); } _eventListeners.remove(listener); i...
java
static boolean objectHasDirectoryPath(String objectName) { return !Strings.isNullOrEmpty(objectName) && objectName.endsWith(GoogleCloudStorage.PATH_DELIMITER); }
java
public static Symmetry010Date now(Clock clock) { LocalDate now = LocalDate.now(clock); return Symmetry010Date.ofEpochDay(now.toEpochDay()); }
java
public static IAuditManager getInstance() { IAuditManager result = auditManager; if(result == null) { synchronized (AuditManager.class) { result = auditManager; if(result == null) { Context.init(); auditManager = result ...
java
public static ResultSet close(ResultSet rs, Logger logExceptionTo, Object name) { if(rs == null) return null; try { rs.close(); } catch(SQLException e) { (logExceptionTo==null ? logger : logExceptionTo).warn("SQLException closing " + (name == null ? rs.toString() : name) + " ignored.", e); } r...
python
def slice_to(self, s): ''' Copy the slice into the supplied StringBuffer @type s: string ''' result = '' if self.slice_check(): result = self.current[self.bra:self.ket] return result
python
def _URange(s): """Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range. """ a = s.split("..") if len(a) == 1: return [_UInt(a[0])] if len(a) =...
python
def component_on_date(self, date: datetime.date) -> Optional["Interval"]: """ Returns the part of this interval that falls on the date given, or ``None`` if the interval doesn't have any part during that date. """ return self.intersection(Interval.wholeday(date))
python
def rename_with_num(self, prefix="", new_path=None, remove_desc=True): """Rename every sequence based on a prefix and a number.""" # Temporary path # if new_path is None: numbered = self.__class__(new_temp_path()) else: numbered = self.__class__(new_path) # Generat...
java
public void setEndRule(int endMonth, int endDay, int endDayOfWeek, int endTime, boolean after) { if (after) { setEndRule(endMonth, endDay, -endDayOfWeek, endTime); } else { setEndRule(endMonth, -endDay, -endDayOfWeek, endTime); } }
python
def delete(self, client=None): """API call: delete a metric via a DELETE request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/delete :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param clien...
java
public void putNextEntry(TarEntry entry) throws IOException { StringBuffer name = entry.getHeader().name; // NOTE // This check is not adequate, because the maximum file length that // can be placed into a POSIX (ustar) header depends on the precise // locations of the path elem...
python
def measurementReport(): """MEASUREMENT REPORT Section 9.1.21""" a = TpPd(pd=0x6) b = MessageType(mesType=0x15) # 00010101 c = MeasurementResults() packet = a / b / c return packet
python
def fetch_metadata(self): """Fetches the metadata for the table and merges it in""" try: table = self.get_sqla_table_object() except Exception as e: logging.exception(e) raise Exception(_( "Table [{}] doesn't seem to exist in the specified data...
java
private List<Member> getNonLocalReplicaAddresses() { final Collection<Member> dataMembers = nodeEngine.getClusterService().getMembers(DATA_MEMBER_SELECTOR); final ArrayList<Member> nonLocalDataMembers = new ArrayList<Member>(dataMembers); nonLocalDataMembers.remove(nodeEngine.getLocalMember()); ...
java
public static <K, V> void putIntoValueArrayList(Map<K, List<V>> map, K key, V value) { CollectionFactory<V> factory = CollectionFactory.arrayListFactory(); putIntoValueCollection(map, key, value, factory); }
python
def _dist(self, x1, x2): """Raw distance between two elements.""" return self.tspace._dist(x1.tensor, x2.tensor)
java
public static boolean isSupportedFormat(String format) { for (int i=0;i<MSExcelWriter.VALID_FORMAT.length;i++) { if (VALID_FORMAT[i].equals(format)) { return true; } } return false; }
python
def get_mac_address_table_input_request_type_get_interface_based_request_forwarding_interface_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_address_table = ET.Element("get_mac_address_table") config = get_mac_address_table ...
python
def mode(self, mode): """Set the operation mode.""" _LOGGER.debug("Setting new mode: %s", mode) if self.mode == Mode.Boost and mode != Mode.Boost: self.boost = False if mode == Mode.Boost: self.boost = True return elif mode == Mode.Away: ...
java
public static Date stringToDate(String source, String format) throws ParseException { if (StringUtils.isEmpty(source)) return null; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); return simpleDateFormat.parse(source); }
python
def start(self): """ instanciate request session with authent :return: """ LOGGER.debug("rest.Driver.start") self.session = requests.Session() self.session.auth = (self.user, self.password)
python
def Parse(self, filename, feed): """ Reads the kml file, parses it and updated the Google transit feed object with the extracted information. Args: filename - kml file name feed - an instance of Schedule class to be updated """ dom = minidom.parse(filename) self.ParseDom(dom, fe...
java
public Future<ScanResult> scanAsync(final ScanRequest scanRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ScanResult>() { public ScanResult call() throws Exception { return scan(scanRequest); } }); }
java
public Map<String, String> getHeadersToMap(Map<String, String> map) { if (map == null) map = new LinkedHashMap<>(); final Map<String, String> map0 = map; header.forEach((k, v) -> map0.put(k, v)); return map0; }
java
private boolean isClear(float x1, float y1, float x2, float y2, float step) { float dx = (x2 - x1); float dy = (y2 - y1); float len = (float) Math.sqrt((dx*dx)+(dy*dy)); dx *= step; dx /= len; dy *= step; dy /= len; int steps = (int) (len / step); for (int i=0;i<steps;i++) { float x = x1 + (dx*i...
java
@Override public void onPut(byte[] key, TypePut type) { //_watchKey.init(key); WatchKey watchKey = new WatchKey(key); switch (type) { case LOCAL: ArrayList<WatchEntry> listLocal = _entryMapLocal.get(watchKey); onPut(listLocal, key); break; case REMOTE: { in...
java
public Point3d[] get3DCoordinatesForSP2Ligands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords, IAtom atomC, double length, double angle) { //logger.debug(" SP2 Ligands start"); Point3d newPoints[] = new Point3d[1]; if (angle < 0) { angle = SP2_ANGLE; ...
java
public boolean addAll(int index, Collection<? extends E> c) { removeNulls(c); c.removeAll(this); return super.addAll(index, c); }
java
private void addResponsiveExample() { add(new WHeading(HeadingLevel.H2, "Default responsive design")); add(new ExplanatoryText("This example applies the theme's default responsive design rules for ColumnLayout.\n " + "The columns have width and alignment and there is also a hgap and a vgap.")); WPanel panel...
java
@SuppressWarnings("resource") protected XMLStreamReader2 createSR(javax.xml.transform.Source src, boolean forER) throws XMLStreamException { ReaderConfig cfg = createPrivateConfig(); Reader r = null; InputStream in = null; String pubId = null; String sysId =...
python
def tag_details(tag, nodenames): """ Used in media and graphics to extract data from their parent tags """ details = {} details['type'] = tag.name details['ordinal'] = tag_ordinal(tag) # Ordinal value if tag_details_sibling_ordinal(tag): details['sibling_ordinal'] = tag_details...
python
def decrypt(self, ciphertext): 'Decrypt a block of cipher text using the AES block cipher.' if len(ciphertext) != 16: raise ValueError('wrong block length') rounds = len(self._Kd) - 1 (s1, s2, s3) = [3, 2, 1] a = [0, 0, 0, 0] # Convert ciphertext to (ints ^...
python
def lease(self, items): """Add the given messages to lease management. Args: items(Sequence[LeaseRequest]): The items to lease. """ self._manager.leaser.add(items) self._manager.maybe_pause_consumer()
java
public static CholeskyDecomposition_F64<DMatrixRMaj> chol(int matrixSize , boolean lower ) { if( matrixSize < EjmlParameters.SWITCH_BLOCK64_CHOLESKY ) { return new CholeskyDecompositionInner_DDRM(lower); } else if( EjmlParameters.MEMORY == EjmlParameters.MemoryUsage.FASTER ){ ...
python
def metric_coherence_gensim(measure, topic_word_distrib=None, gensim_model=None, vocab=None, dtm=None, gensim_corpus=None, texts=None, top_n=20, return_coh_model=False, return_mean=False, **kwargs): """ Calculate model coherence using Gensim's `CoherenceMo...
python
def init_dirs(main_dir: Path, logfilepath: Path): """ Initialize the main directories. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfilepath: log file :type logfilepath: ~pathlib.Path """ global MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR, LOGFILE_PATH ...
java
@Override public DescribeModelResult describeModel(DescribeModelRequest request) { request = beforeClientExecution(request); return executeDescribeModel(request); }
python
def get_rate_limits(): """Retrieve status (and optionally) version from the API.""" client = get_rates_api() with catch_raise_api_exception(): data, _, headers = client.rates_limits_list_with_http_info() ratelimits.maybe_rate_limit(client, headers) return { k: RateLimitsInfo.from_...
java
private StreamGraph generateInternal(List<StreamTransformation<?>> transformations) { for (StreamTransformation<?> transformation: transformations) { transform(transformation); } return streamGraph; }
python
def bytes_hack(buf): """ Hacky workaround for old installs of the library on systems without python-future that were keeping the 2to3 update from working after auto-update. """ ub = None if sys.version_info > (3,): ub = buf else: ub = bytes(buf) return ub
java
boolean isAttribute(String name) { if (attributes.containsKey(name)) return true; return noStroke.containsKey(name); }
java
public void addEvent(String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) { addEvent(null, eventCollection, event, keenProperties, null); }
java
private void handleNotationDecl() throws XMLStreamException { char c = skipObligatoryDtdWs(); String id = readDTDName(c); c = skipObligatoryDtdWs(); boolean isPublic = checkPublicSystemKeyword(c); String pubId, sysId; c = skipObligatoryDtdWs(); // ...
python
def replace_ext(filename, new_ext): """Replace the file extention.""" filename_base = os.path.splitext(filename)[0] new_filename = '{}.{}'.format(filename_base, new_ext) return new_filename
java
public boolean completeExceptionally(final Throwable throwable) { synchronized (lock) { if (isDone()) { return false; } this.throwable = throwable; lock.notifyAll(); return true; } }
java
protected void set(double values[]) { this.nRows = values.length; this.nCols = 1; this.values = new double[nRows][1]; for (int r = 0; r < nRows; ++r) { this.values[r][0] = values[r]; } }
python
def process_mod(self, data, name): """ Processing one modulus per line :param data: :param name: :return: """ ret = [] try: lines = [x.strip() for x in data.split(bytes(b'\n'))] for idx, line in enumerate(lines): sub...
python
def delete_credit_card(self, *, customer_id, credit_card_id): """ Delete a credit card (Token) associated with a user. Args: customer_id: Identifier of the client of whom you are going to delete the token. credit_card_id: Identifier of the token to be deleted. R...
python
def list_fonts(self, pattern, max_names): """Return a list of font names matching pattern. No more than max_names will be returned.""" r = request.ListFonts(display = self.display, max_names = max_names, pattern = pattern) retur...
python
def image_linear_solve(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_else, inv_bool=False): """ computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalizat...
python
def newKernel(self, nb): """ generate a new kernel """ manager, kernel = utils.start_new_kernel( kernel_name=nb.metadata.kernelspec.name ) return kernel
python
def item_handle(loc, tokens): """Process trailers.""" out = tokens.pop(0) for i, trailer in enumerate(tokens): if isinstance(trailer, str): out += trailer elif len(trailer) == 1: if trailer[0] == "$[]": out = "_coconut.functools.partial(_coconut_igetit...
java
public void longForEach(final LongLongConsumer consumer) { final long[] entries = this.entries; for (int i = 0; i < entries.length; i += 2) { final long key = entries[i]; if (key != missingValue) { consumer.accept(entries[i], entries[i + 1]); } ...
python
def fraction_done(self, start=0.0, finish=1.0, stack=None): ''' :return float: The estimated fraction of the overall task hierarchy that has been finished. A number in the range [0.0, 1.0]. ''' if stack is None: stack = self.task_stack if len(stack) == 0:...
python
async def send_from_directory( directory: FilePath, file_name: str, *, mimetype: Optional[str]=None, as_attachment: bool=False, attachment_filename: Optional[str]=None, add_etags: bool=True, cache_timeout: Optional[int]=None, conditional: bool=True...
java
public ServiceFuture<List<MetricInner>> listMetricsAsync(String resourceGroupName, String accountName, String databaseRid, String collectionRid, String filter, final ServiceCallback<List<MetricInner>> serviceCallback) { return ServiceFuture.fromResponse(listMetricsWithServiceResponseAsync(resourceGroupName, acc...
python
def clear(self, objtype=[]): r""" Clears objects from the project entirely or selectively, depdening on the received arguments. Parameters ---------- objtype : list of strings A list containing the object type(s) to be removed. If no types are sp...
java
@Override public List<CommerceShippingFixedOption> findByCommerceShippingMethodId( long commerceShippingMethodId, int start, int end) { return findByCommerceShippingMethodId(commerceShippingMethodId, start, end, null); }
java
public boolean readNextHeaderBlock() throws IOException, TarMalformatException { // We read a-byte-at-a-time because there should only be 2 empty blocks // between each Tar Entry. try { while (readStream.available() > 0) { readBlock(); if (readBu...