language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static double logcdf(double val, double loc, double scale) { val = (val - loc) / scale; if (val <= 18.) { return -FastMath.log1p(FastMath.exp(-val)); } else if (val > 33.3) { return val; } else { return val - FastMath.exp(val); } }
python
def _filter_options(self, aliases=True, comments=True, historical=True): """Converts a set of boolean-valued options into the relevant HTTP values.""" options = [] if not aliases: options.append('noaliases') if not comments: options.append('nocomments') if...
java
public static void plotCharts(List<Chart> charts){ int numRows =1; int numCols =1; if(charts.size()>1){ numRows = (int) Math.ceil(charts.size()/2.0); numCols = 2; } final JFrame frame = new JFrame(""); frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); frame.getContentPane().setLay...
java
@Trivial public static final String normalizeString(String str) { return (str == null || str.length() == 0) ? " " : str; }
python
def create_kernel_spec(self, is_cython=False, is_pylab=False, is_sympy=False): """Create a kernel spec for our own kernels""" # Before creating our kernel spec, we always need to # set this value in spyder.ini CONF.set('main', 'spyder_pythonpath', ...
java
@Override void throwInternalError(String message, Throwable cause) { String finalMessage = "INTERNAL COMPILER ERROR.\nPlease report this problem.\n\n" + message; RuntimeException e = new RuntimeException(finalMessage, cause); if (cause != null) { e.setStackTrace(cause.getStackTrace()); } th...
python
def top(self, **kwargs): """ Display the running processes of the container. Args: ps_args (str): An optional arguments passed to ps (e.g. ``aux``) Returns: (str): The output of the top Raises: :py:class:`docker.errors.APIError` ...
java
@Override final public void run() { try { if(args.length>0) handleCommand(args); else runImpl(); status="Done"; } catch(IOException exception) { this.err.println(getName()+": "+exception.getMessage()); status="IO Error: "+exception.getMessage(); this.err.flush(); } catch(SQLException exception)...
java
private void countCooccurringProperties( StatementDocument statementDocument, UsageRecord usageRecord, PropertyIdValue thisPropertyIdValue) { for (StatementGroup sg : statementDocument.getStatementGroups()) { if (!sg.getProperty().equals(thisPropertyIdValue)) { Integer propertyId = getNumId(sg.getPropert...
java
public void setCommerceNotificationTemplateUserSegmentRelService( com.liferay.commerce.notification.service.CommerceNotificationTemplateUserSegmentRelService commerceNotificationTemplateUserSegmentRelService) { this.commerceNotificationTemplateUserSegmentRelService = commerceNotificationTemplateUserSegmentRelServic...
java
static void mkdirp(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { boolean createPath = false; for (String path : pathParts(znode)) { if (!createPath) { Stat stat = zookeeper.exists(path, false); if (stat == null) { ...
java
public String createNewVariableOnSolver(final String prefix) { final int index = this.name2idx.size() + 1; final String varName = prefix + "_" + index; this.name2idx.put(varName, index); this.idx2name.put(index, varName); return varName; }
java
public DbxDownloadStyleBuilder<R> range(long start, long length) { if (start < 0) throw new IllegalArgumentException("start must be non-negative"); if (length < 1) throw new IllegalArgumentException("length must be positive"); this.start = start; this.length = length; return th...
python
def create_entity_type(self, parent, entity_type, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ...
java
private boolean isInputBalanced() { Stack<Character> stack = new Stack<>(); int length = input.length(); for (int i = 0; i < length; i++) { char currentChar = input.charAt(i); if (currentChar == BRACE_START) { stack.push(currentChar); } else if (currentChar == BRACE_END) { ...
java
public static void convert(SequenceRecordReader reader, SequenceRecordWriter writer) throws IOException { convert(reader, writer, true); }
python
def add_pagination_links(data, object_count, querystring, base_url): """Add pagination links to result :param dict data: the result of the view :param int object_count: number of objects in result :param QueryStringManager querystring: the managed querystring fields and values :param str base_url: ...
python
def is_scaled_full_image(self): """True if this request is for a scaled full image. To be used to determine whether this request should be used in the set of `sizes` specificed in the Image Information. """ return(self.region_full and self.size_wh[0] is not None a...
java
private Set<String> getTargetTechnologies() { WindupConfigurationModel wc = grCtx.getUnique(WindupConfigurationModel.class); Iterable<TechnologyReferenceModel> targetTechnologies = wc.getTargetTechnologies(); Set<String> techs = new HashSet<>(); for (TechnologyReferenceModel tech : t...
python
def set_mask(self, kind, mask): """Writes the specified filter mask. """ logger.debug("setting mask kind %s to %s" % (kind, mask)) return self.library.Srv_SetMask(self.pointer, kind, mask)
java
private void loadOffsetsFromFormat(File file, SSpaceFormat format) throws IOException { this.format = format; spaceName = file.getName(); // NOTE: Use a LinkedHashMap here because this will ensure that the // words are returned in the same row-order as the matrix. This ...
python
def parse_devices(self): """Creates an array of Device objects from the channel""" devices = [] for device in self._channel_dict["devices"]: devices.append(Device(device, self._is_sixteen_bit, self._ignore_list)) return devices
java
public ExpressionIterator parse(@NonNull String string) throws ParseException { return new ExpressionIterator(grammar, lexer.lex(string)); }
java
@Override public Trigger.TriggerState getTriggerState(TriggerKey triggerKey, JedisCluster jedis) { final String triggerHashKey = redisSchema.triggerHashKey(triggerKey); Map<RedisTriggerState, Double> scores = new HashMap<>(RedisTriggerState.values().length); for (RedisTriggerState redisTrigg...
java
public TLVElement readElement() throws IOException, TLVParserException { TlvHeader header = readHeader(); TLVElement element = new TLVElement(header.tlv16, header.nonCritical, header.forwarded, header.type); int count = countNestedTlvElements(header); if (count > 0) { readNes...
java
protected void showFlagsDidChange (int oldflags) { if ((oldflags & SHOW_TIPS) != (_showFlags & SHOW_TIPS)) { for (SceneObjectIndicator indic : _indicators.values()) { dirtyIndicator(indic); } } }
python
def normalize_set(self, items, **kwargs): """Utility to normalize a whole set of values and get unique values.""" values = set() for item in ensure_list(items): values.update(self.normalize(item, **kwargs)) return list(values)
python
def get_python_files(files): """Utility function to get .py files from a list""" python_files = [] for file_name in files: if file_name.endswith(".py"): python_files.append(file_name) return python_files
java
public void marshall(AttemptContainerDetail attemptContainerDetail, ProtocolMarshaller protocolMarshaller) { if (attemptContainerDetail == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(attemptContai...
java
void completeWork(long txnId) { if (m_shuttingDown) { return; } MpRoSiteContext site = m_busySites.remove(txnId); if (site == null) { throw new RuntimeException("No busy site for txnID: " + txnId + " found, shouldn't happen."); } // check the ...
python
def average_sphere(image, center, radius, weighted=True, ret_crop=False): """Compute the weighted average phase from a phase image of a sphere Parameters ---------- image: 2d ndarray Quantitative phase image of a sphere center: tuble (x,y) Center of the sphere in `image` in ndarray ...
java
private SegmentScoreEntry computeSegmentScore(String segment) { if(this.stopList.contains(segment) ) return SegmentScoreEntry.SCORE_ZERO; CompostIndexEntry closestEntry = compostIndex.getEntry(segment); double indexSimilarity = 0.0; if(closestEntry == null) { if(this.opt.getSegmentSimilarityThreshold()...
java
public static TimingInfo startTimingFullSupport() { return new TimingInfoFullSupport(Long.valueOf(System.currentTimeMillis()), System.nanoTime(), null); }
java
public Array createArrayOf(final String typeName, final Object[] elements) throws SQLException { final String jdbcClassName = Defaults.jdbcTypeNameClasses.get(typeName); if (jdbcClassName == null) { throw new SQLException("Unsupported type: " + typeName); ...
python
def name(self): """AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. The AppProfile name is of the form ``"projects/../instances/../app_profile/{app_profile_id}"`` ...
python
def thread_debug(self, *args, **kwargs): """ Wrap debug to include thread information """ if 'module' not in kwargs: kwargs['module'] = "Monitor" if kwargs['module'] != 'Monitor' and self.do_DEBUG(module='Monitor'): self.debug[kwargs['module']] = True ...
java
public ResultType updateGroup(Integer groupid, String name) { BeanUtil.requireNonNull(groupid, "groupid is null"); BeanUtil.requireNonNull(name, "name is null"); LOG.debug("修改分组信息....."); String url = BASE_API_URL + "cgi-bin/groups/update?access_token=#"; Map<String, Object> para...
python
def reboot(self): """reset and rejoin to Thread Network without any timeout Returns: True: successful to reset and rejoin the Thread Network False: fail to reset and rejoin the Thread Network """ print '%s call reboot' % self.port try: self._s...
java
private double bic(int n, int d, double distortion) { double variance = distortion / (n - 1); double p1 = -n * LOG2PI; double p2 = -n * d * Math.log(variance); double p3 = -(n - 1); double L = (p1 + p2 + p3) / 2; int numParameters = d + 1; return L - 0.5 * numPa...
python
def get_paths(path_tokens): """ Given a list of parser path tokens, return a list of path objects for them. """ if len(path_tokens) == 0: return [] token = path_tokens.pop() path = PathToken(token.alias, token.path) return [path] + get_paths(path_tokens)
python
def _file_num_records_cached(filename): """Return the number of TFRecords in a file.""" # Cache the result, as this is expensive to compute if filename in _file_num_records_cache: return _file_num_records_cache[filename] ret = 0 for _ in tf.python_io.tf_record_iterator(filename): ret += 1 _file_num_...
python
def from_json(self, data): """ Initialise an API message from a JSON representation. """ try: d = json.loads(data) except ValueError: raise InvalidMessageException() self.from_dict(d)
java
public ThumborUrlBuilder crop(int top, int left, int bottom, int right) { if (top < 0) { throw new IllegalArgumentException("Top must be greater or equal to zero."); } if (left < 0) { throw new IllegalArgumentException("Left must be greater or equal to zero."); } if (bottom < 1 || bottom...
python
def false_repr(self, value): """Validate and set the logical false representation.""" if isinstance(value, str): if not (value.lower().startswith('f') or value.lower().startswith('.f')): raise ValueError("Logical false representation must start " ...
python
def _run_markdownlint(matched_filenames, show_lint_files): """Run markdownlint on matched_filenames.""" from prospector.message import Message, Location for filename in matched_filenames: _debug_linter_status("mdl", filename, show_lint_files) try: proc = subprocess.Popen(["mdl"] + matc...
python
def upload_and_confirm(self, incoming, **kwargs): """Upload the file to okcupid and confirm, among other things, its thumbnail position. :param incoming: A filepath string, :class:`.Info` object or a file like object to upload to okcupid.com. If...
python
def import_string(import_name, silent=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax...
java
private void populateLocalCache() { try (CloseableIterator iterator = cache.keySet().iterator()) { while (iterator.hasNext()) { getFromCache(iterator.next(), null); } } }
python
def _create_container_for_process(pymux, window, arrangement_pane, zoom=False): """ Create a `Container` with a titlebar for a process. """ @Condition def clock_is_visible(): return arrangement_pane.clock_mode @Condition def pane_numbers_are_visible(): return pymux.display_p...
python
def check_extensions(module_name, module_path): """ This function checks for extensions to boto modules. It should be called in the __init__.py file of all boto modules. See: http://code.google.com/p/boto/wiki/ExtendModules for details. """ option_name = '%s_extend' % module_name vers...
java
public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException { LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)"); ArrayList<Header> headers = new ArrayList<Header>(); String name = null; StringBuffer value = null; for (; ;...
java
public OfflineSettings getOfflineSettings() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { OfflineSettings request = new OfflineSettings(); request.setType(IQ.Type.get); request.setTo(workgroupJID); return connection.createStanzaCollectorAn...
java
public void set(final Pad pad, final Color color) throws InvalidMidiDataException { receiver.send(new ShortMessage(pad.getCommand(), this.channel.channelForSystem(), pad.getCode(), color.getCode()), -1); }
java
@Override public String[] introspectSelf() { List<String> rc = new ArrayList<String>(); rc.add(Thread.currentThread().getName()); rc.add("quit: " + this.quit); rc.add("waitingToQuit: " + this.waitingToQuit); rc.add("# of keys=" + this.selector.keys().size()); try { ...
java
private Object newDeepStubMock(GenericMetadataSupport returnTypeGenericMetadata, Object parentMock) { MockCreationSettings parentMockSettings = MockUtil.getMockSettings(parentMock); return mockitoCore().mock( returnTypeGenericMetadata.rawType(), withSettingsUsing(returnTypeGeneri...
python
def send(self, stack: Layers): """ Intercept any potential "AnswerCallbackQuery" before adding the stack to the output buffer. """ if not isinstance(stack, Stack): stack = Stack(stack) if 'callback_query' in self._update and stack.has_layer(Update): ...
java
public List<Point> getPoints2() { verifyPropertyPresence(POINTS2); //noinspection unchecked return ((List<Map<String, Object>>) getCommandResult().get(POINTS2)).stream() .map(ComparisonResult::mapToPoint) .collect(Collectors.toList()); }
python
def _get_scripts_resource(pe): """Return the PYTHONSCRIPT resource entry.""" res = None for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries: if entry.name and entry.name.string == b"PYTHONSCRIPT": res = entry.directory.entries[0].directory.entries[0] break return res
java
@Pure protected Rectangle2d calcBounds() { final Rectangle2d bb = new Rectangle2d(); boolean first = true; Rectangle2afp<?, ?, ?, ?, ?, ?> b; // Child bounds N child; for (int i = 0; i < getChildCount(); ++i) { child = getChildAt(i); if (child != null) { b = child.getBounds(); if (b != null)...
java
@Override public Object getData() { Object data = super.getData(); if (isRichTextArea() && isSanitizeOnOutput() && data != null) { return sanitizeOutputText(data.toString()); } return data; }
python
def update(self, get_running_apps=True): """Get the state of the device, the current app, and the running apps. :param get_running_apps: whether or not to get the ``running_apps`` property :return state: the state of the device :return current_app: the current app :return runnin...
python
def part(self, *args, **kwargs): # type: (*Any, **Any) -> Part """Retrieve single KE-chain part. Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part` instance. If additional `keyword=value` arguments are provided, these ar...
java
@Override public Splittable getSerializedProxyId(final SimpleProxyId<?> stableId) { final AutoBean<IdMessage> bean = MessageFactoryHolder.FACTORY.id(); final IdMessage ref = bean.as(); ref.setServerId(stableId.getServerId()); ref.setTypeToken(this.getRequestFactory().getTypeToken(stableId.getProxyClas...
java
public static SimplifyVisitor create( IdGenerator idGenerator, ImmutableList<SoyFileNode> sourceFiles) { return new SimplifyVisitor( idGenerator, sourceFiles, new SimplifyExprVisitor(), new PreevalVisitorFactory()); }
java
public final String getDecodedString() throws TLVParserException { byte[] data = getContent(); if (!(data.length > 0 && data[data.length - 1] == '\0')) { throw new TLVParserException("String must be null terminated"); } try { return Util.decodeString(data, 0, data...
python
def highlight_channels(self, l, selected_chan): """Highlight channels in the list of channels. Parameters ---------- selected_chan : list of str channels to indicate as selected. """ for row in range(l.count()): item = l.item(row) if i...
python
def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke t...
java
public void freeClassificationReadLock() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "freeClassificationReadLock"); classificationReadLock.unlock(); if(TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "freeClassificati...
java
public static Rule parse(String rule, Engine engine) { Rule result = new Rule(); result.load(rule, engine); return result; }
python
def FromMicroseconds(self, micros): """Converts microseconds to Duration.""" self._NormalizeDuration( micros // _MICROS_PER_SECOND, (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND)
java
public UpdateItemRequest withExpressionAttributeNames(java.util.Map<String, String> expressionAttributeNames) { setExpressionAttributeNames(expressionAttributeNames); return this; }
python
def checkformat(self): """************************************************************************************************************************************************************ Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separat...
python
def get_model(self): """ Returns an instance of Bayesian Model or Markov Model. Varibles are in the pattern var_0, var_1, var_2 where var_0 is 0th index variable, var_1 is 1st index variable. Return ------ model: an instance of Bayesian or Markov Model. ...
java
public boolean addAll(int index, Collection<? extends E> c) { checkPositionIndex(index); Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) return false; Node<E> pred, succ; if (index == size) { succ = null; pred = last...
java
@Override public List<CommercePriceEntry> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def ping_directories(self, request, queryset, messages=True): """ Ping web directories for selected entries. """ for directory in settings.PING_DIRECTORIES: pinger = DirectoryPinger(directory, queryset) pinger.join() if messages: succes...
java
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) { try { KeyPair pair = newKeyPair(); X500Name userDN = buildDistinguishedName(client...
python
def _interchange_level_from_filename(fullname): # type: (bytes) -> int ''' A function to determine the ISO interchange level from the filename. In theory, there are 3 levels, but in practice we only deal with level 1 and level 3. Parameters: name - The name to use to determine the intercha...
java
protected static <T> T checkType(String view, String attribute, Object value, Class<T> type) { checkNotNull(value); if (type.isInstance(value)) { return type.cast(value); } throw invalidType(view, attribute, value, type); }
java
public static OSType getOperatingSystemType() { if (detectedOS == null) { String OS = System.getProperty("os.name", "generic").toLowerCase( Locale.ENGLISH); if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) { detectedOS = OSType.MacOS; } else if (OS.indexOf("win") >= 0) { detectedOS =...
python
def plot_lr(self, show_text=True, show_moms=True): """Plots the lr rate/momentum schedule""" phase_limits = [0] for nb_batch, phase in zip(self.nb_batches, self.phases): phase_limits.append(phase_limits[-1] + nb_batch * phase.epochs) if not in_ipynb(): plt.switch_...
python
def connect_with_password(self, ssh, username, password, address, port, sock, timeout=20): """ Create an ssh session to a remote host with a username and password :type username: str :param username: username used for ssh authentication :type passwo...
python
def getProperty(self, id=None, uri=None, match=None): """ get the saved-class with given ID or via other methods... Note: analogous to getClass method """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id ...
java
public static HistoricDate of( HistoricEra era, int yearOfEra, int month, int dom, YearDefinition yearDefinition, NewYearStrategy newYearStrategy ) { if (era == null) { throw new NullPointerException("Missing historic era."); } else if (do...
java
public final BELScriptWalker.record_return record() throws RecognitionException { BELScriptWalker.record_return retval = new BELScriptWalker.record_return(); retval.start = input.LT(1); CommonTree root_0 = null; CommonTree _first_0 = null; CommonTree _last = null; BELS...
java
@Override protected <T> Response<T> deserializeError(String response, Request<T> request) { Response<T> target = RequestUtil.getInstanceOfParameterizedType(request); target.setError(true); target.setContent(response); return target; }
java
public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode, @Nullable String referrer) { String installReferrerString = Defines.Jsonkey.IsFullAppConv.getKey() + "=true&" + referrer; return InstantAppUtil.doShowInstallPrompt(activity, requestCode, installReferrerString); }
java
public static <T> T find(Class<T> factoryClass, Descriptor descriptor) { Preconditions.checkNotNull(descriptor); return findInternal(factoryClass, descriptor.toProperties(), Optional.empty()); }
python
def standardize_tag(tag: {str, Language}, macro: bool=False) -> str: """ Standardize a language tag: - Replace deprecated values with their updated versions (if those exist) - Remove script tags that are redundant with the language - If *macro* is True, use a macrolanguage to represent the most com...
python
def removeKeyButtonEvent(self, buttons= [] ): """! \~english Remove key button event callbacks @param buttons: an array of button Ids. eg. [ 12,13,15, ...] \~chinese 移除按键事件回调 @param buttons: 按钮ID数组。 例如: [12,13,15,...] """ for i in range( 0, len(bu...
java
public static int commonOverlap(String text1, String text2) { // Cache the text lengths to prevent multiple calls. int text1_length = text1.length(); int text2_length = text2.length(); // Eliminate the null case. if (text1_length == 0 || text2_length == 0) { return 0;...
java
public JdbcMapperFactory addCustomGetter(String key, Getter<ResultSet, ?> getter) { return addColumnDefinition(key, FieldMapperColumnDefinition.<JdbcColumnKey>customGetter(getter)); }
java
public Deferred<List<String>> suggestAsync(final String search, final int max_results) { return new SuggestCB(search, max_results).search(); }
python
def disqualified(self, num, natural=True, **kwargs): """Search for disqualified officers by officer ID. Searches for natural disqualifications by default. Specify natural=False to search for corporate disqualifications. Args: num (str): Company number to search on. ...
java
@Nonnull public static <T> List<T> filter( @Nonnull Iterable<?> base, @Nonnull Class<T> type ) { List<T> r = new ArrayList<>(); for (Object i : base) { if(type.isInstance(i)) r.add(type.cast(i)); } return r; }
java
public static <K extends Message> MessageListener<K> from(Integer channelIdentifier, Consumer<K> consumer) { return new ConsumerMessageListener<>(channelIdentifier, consumer); }
python
def get_values(): """ Get dictionary of values from the backend :return: """ # First load a mapping between config name and default value default_initial = ((name, options[0]) for name, options in settings.CONFIG.items()) # Then update the mapping with actually values...
java
public static <TARGET> Implementing<TARGET> implementing(Class<TARGET> targetType) { return new Implementing<>(TypeUtils.wrap(targetType)); }
python
def columns_dataset(self): """ Implement high level cache system for columns and dataset. """ cache = self.cache cache_key = 'columns_dataset' if cache_key not in cache: columns_dataset = super(CachedModelVectorBuilder, self ...
java
public Map<K,V> fillMap(Map<K,V> toFill){ return wrapper.fillMap(toFill); }