language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static String format(final LocalTime self, FormatStyle timeStyle) { return self.format(DateTimeFormatter.ofLocalizedTime(timeStyle)); }
java
public void makeAllRepeatUnlimited(int profileId, String client_uuid) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_REQUEST_RESPONSE + ...
python
def setActivities(self, *args, **kwargs): """Adds the activities for this group to a 'activities' field. Activities are MambuActivity objects. Activities get sorted by activity timestamp. Returns the number of requests done to Mambu. """ def activityDate(activity): ...
python
def send_exit_status(self, status): """ Send the exit status of an executed command to the client. (This really only makes sense in server mode.) Many clients expect to get some sort of status code back from an executed command after it completes. @param status...
java
public static void renderDOT(Reader r, boolean modal) { final DOTComponent cmp = createDOTComponent(r); if (cmp == null) { return; } final JDialog frame = new JDialog((Dialog) null, modal); JScrollPane scrollPane = new JScrollPane(cmp); frame.setContentPane(s...
python
def ConsultarLocalidades(self, cod_provincia, sep="||"): "Consulta las localidades habilitadas" ret = self.client.consultarLocalidadesPorProvincia( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, ...
python
def set_desktop_for_window(self, window, desktop): """ Move a window to another desktop Uses _NET_WM_DESKTOP of the EWMH spec. :param wid: the window to move :param desktop: the desktop destination for the window """ _libxdo.xdo_set_desktop_for_window(self._xdo, ...
java
public GalleryInfo create(String title, String description, String primaryPhotoId, boolean fullResult) throws JinxException { JinxUtils.validateParams(title, description); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.galleries.create"); params.put("title", title); param...
java
@Override public void removeByUuid(String uuid) { for (CommercePriceList commercePriceList : findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commercePriceList); } }
java
public LineString toLineString(Polyline polyline, boolean hasZ, boolean hasM) { return toLineString(polyline.getPoints(), hasZ, hasM); }
java
@Reference(name = REFERENCE_ENDPOINT_ACTIVATION_SERVICES, service = EndpointActivationService.class, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE) protected synchronized void addEndPointActivationService(ServiceReference<EndpointActivatio...
java
public static CPRuleUserSegmentRel[] findByCPRuleId_PrevAndNext( long CPRuleUserSegmentRelId, long CPRuleId, OrderByComparator<CPRuleUserSegmentRel> orderByComparator) throws com.liferay.commerce.product.exception.NoSuchCPRuleUserSegmentRelException { return getPersistence() .findByCPRuleId_PrevAndNext(C...
java
public static @Nonnull ClusterConfig from(@Nonnull HttpReplica local, HttpReplica... remotes) { return new HttpClusterConfig(local, remotes); }
java
public static Properties mergeAndSkipExisting(Properties props1, Properties props2) { Properties properties = new Properties(); properties.putAll(props1); for (String key : props2.stringPropertyNames()) { if (!props1.containsKey(key) && !Strings.isNullOrEmpty(props2.getProperty(key))...
python
def scaleBy(self, value, origin=None): """ Scale the object. >>> obj.transformBy(2.0) >>> obj.transformBy((0.5, 2.0), origin=(500, 500)) **value** must be an iterable containing two :ref:`type-int-float` values defining the x and y values to scale the ob...
python
def render_to_string(self, template, context=None, def_name=None, subdir='templates'): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_template(template) return getattr...
java
private int[] rows() { int[] rowIndexes = new int[rowCount()]; for (int i = 0; i < rowCount(); i++) { rowIndexes[i] = i; } return rowIndexes; }
java
void enclose(TaskRequest req) { parent = req; if (this.parent != null) { final HashMap<String, Object> mergedAttributes = new HashMap<String, Object>(this.parent.getAttributes()); mergedAttributes.putAll(this.attributes); this.mergedAttributes = mergedAttributes; } else { this.mergedAttr...
java
public boolean needsRefresh() { boolean needsRefresh; this.refreshLock.readLock().lock(); long now = System.currentTimeMillis(); long tokenDuration = (now - this.lastRefresh); needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON); this.refreshLock.readLock().u...
java
public static RpcInternalContext getContext() { RpcInternalContext context = LOCAL.get(); if (context == null) { context = new RpcInternalContext(); LOCAL.set(context); } return context; }
java
public static InterleavedF32 nv21ToInterleaved( byte[] data , int width , int height , InterleavedF32 output ) { if( output == null ) { output = new InterleavedF32(width,height,3); } else { output.reshape(width, height, 3); } if(BoofConcurrency.USE_CONCURRENT ) { ImplConvertNV21_MT.n...
python
def update_metadata_from_rmd_options(name, value, metadata): """ Update metadata using the _BOOLEAN_OPTIONS_DICTIONARY mapping :param name: option name :param value: option value :param metadata: :return: """ for jupyter_option, rmd_option, rev in _BOOLEAN_OPTIONS_DICTIONARY: if ...
java
@Override public void remove(String oid) throws IndexerException { log.debug("Deleting " + oid + " from index"); try { solr.deleteByQuery("storage_id:\"" + oid + "\""); solr.commit(); } catch (SolrServerException sse) { throw new IndexerException(sse); } catch (IOException ioe) { throw new IndexerE...
java
public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String localPath =...
python
def transform_annotation(self, ann, duration): '''Apply the vector transformation. Parameters ---------- ann : jams.Annotation The input annotation duration : number > 0 The duration of the track Returns ------- data : dict ...
python
def logging_syslog_server_secure(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras") syslog_server = ET.SubElement(logging, "syslog-server") syslogip_key = ET.SubEle...
python
def title(self, value=None): """Get or set the document's title from/in the metadata No arguments: Get the document's title from metadata Argument: Set the document's title in metadata """ if not (value is None): if (self.metadatatype == "native"): ...
java
public synchronized AbstractCompactionTask getNextBackgroundTask(int gcBefore) { if (!isEnabled()) return null; Collection<AbstractCompactionTask> tasks = getMaximalTask(gcBefore); if (tasks == null || tasks.size() == 0) return null; return tasks.iterator().ne...
python
def within_duration(events, time, limits): """Check whether event is within time limits. Parameters ---------- events : ndarray (dtype='int') N x M matrix with start sample first and end samples last on M time : ndarray (dtype='float') vector with time points limits : tuple of f...
java
public void load(File mean, File std) throws IOException { this.mean = Nd4j.readBinary(mean); this.std = Nd4j.readBinary(std); }
python
def register_factory(self, bundle_context, factory): # type: (BundleContext, type) -> bool """ Registers a manually created factory, using decorators programmatically :param bundle_context: The factory bundle context :param factory: A manipulated class :return: True if t...
java
public static DoubleStreamEx of(java.nio.DoubleBuffer buf) { return IntStreamEx.range(buf.position(), buf.limit()).mapToDouble(buf::get); }
java
public static INDArray pinvert(INDArray arr, boolean inPlace) { // TODO : do it natively instead of relying on commons-maths RealMatrix realMatrix = CheckUtil.convertToApacheMatrix(arr); QRDecomposition decomposition = new QRDecomposition(realMatrix, 0); DecompositionSolver solver = de...
python
def _get_nr_bins(count): """depending on the number of data points, compute a best guess for an optimal number of bins https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width """ if count <= 30: # use the square-root choice, used by Excel and Co k = np.ceil(np.sqrt(count)) ...
java
public Observable<RunCommandResultInner> beginRunCommandAsync(String resourceGroupName, String vmName, RunCommandInput parameters) { return beginRunCommandWithServiceResponseAsync(resourceGroupName, vmName, parameters).map(new Func1<ServiceResponse<RunCommandResultInner>, RunCommandResultInner>() { ...
java
public String getDateTime(Date date) { return CmsDateTimeUtil.getDateTime(date, CmsDateTimeUtil.Format.SHORT); }
python
def partition(f, xs): """ Works similar to filter, except it returns a two-item tuple where the first item is the sequence of items that passed the filter and the second is a sequence of items that didn't pass the filter """ t = type(xs) true = filter(f, xs) false = [x for x in x...
java
@Override public final String getName() { String name = getProperty(AbstractNode.name); if (name == null) { name = getUuid(); } return name; }
java
public Report compare(Xml a, Xml b) { return compare(a, b, null, null); }
java
public static <K, V> Map<K, V> zip(Collection<K> keys, Collection<V> values) { if (isEmpty(keys) || isEmpty(values)) { return null; } final List<K> keyList = new ArrayList<K>(keys); final List<V> valueList = new ArrayList<V>(values); final int size = Math.min(keys.size(), values.size()); final...
java
public void execute() throws ActivityException{ isSynchronized = checkIfSynchronized(); if (!isSynchronized) { EventWaitInstance received = registerWaitEvents(false, true); if (received!=null) resume(getExternalEventInstanceDetails(received.getMessageDocumentId(...
python
def get_dynamodb_type(self, val): """ Take a scalar Python value and return a string representing the corresponding Amazon DynamoDB type. If the value passed in is not a supported type, raise a TypeError. """ dynamodb_type = None if is_num(val): dynam...
python
def get(self, name=None): """ Returns commands, which can be filtered by name. :param name: name of the command :type name: str :return: None, single command or dict of commands """ return self.app.commands.get(name, self.plugin)
python
def read_tmy3(filename=None, coerce_year=None, recolumn=True): ''' Read a TMY3 file in to a pandas dataframe. Note that values contained in the metadata dictionary are unchanged from the TMY3 file (i.e. units are retained). In the case of any discrepencies between this documentation and the TMY3 Us...
java
public Result removeEntry(Object dependency, Object entry) { Result result = this.htod.getFromResultPool(); ValueSet valueSet = (ValueSet) dependencyToEntryTable.get(dependency); if (valueSet == null) { return result; } result.bExist = HTODDynacache.EXIST; va...
python
def __update_molar_mass(self, compound='', element=''): """Re-calculate the molar mass of the element given due to stoichiometric changes Parameters: ========== compound: string (default is '') name of compound element: string (default is '') name of element """ ...
java
@Override protected Observable construct() { Observable result; try { Observable observable = toObservable(commandActions.getCommandAction().execute(executionType)); result = observable .onErrorResumeNext(new Func1<Throwable, Observable>() { ...
java
public RepositoryType getTypeByName(String repositoryTypeName) { final Criteria crit = sessionService.getSession().createCriteria(RepositoryType.class); crit.add(Property.forName("name").eq(repositoryTypeName)); RepositoryType repositoryType = (RepositoryType) crit.uniqueResult(); Hibernat...
java
void performPostExecute() throws SQLException { resultOut.clearLobResults(); generatedResult = null; if (resultIn == null) { return; } Result current = resultIn; while (current.getChainedResult() != null) { current = current.getUnlinkChainedRe...
python
def _delete_account(self, account, username): """ Called when account is deleted. With username override. """ # account deleted ds_user = self.get_user(username) if ds_user is not None: self._call(["grmuser", "-u", username], ignore_errors=[8]) return
java
public static void notifyAboutCloudSize(InetAddress ip, int port, InetAddress leaderIp, int leaderPort, int size) { if (ARGS.notify_local != null && !ARGS.notify_local.trim().isEmpty()) { final File notifyFile = new File(ARGS.notify_local); final File parentDir = notifyFile.getParentFile(); if (pa...
java
public static double convertExcelNumber(final Date value, final boolean startDate1904) { ArgUtils.notNull(value, "value"); /* * Excelの時間の表現に直す。 * ・Excelの日付の形式の場合小数部が時間を示すため、24時間分のミリ秒を考慮する。 */ long utcDay = value.getTime(); BigDecimal ...
python
def cmd(send, msg, args): """Summons a user Syntax: {command} <nick> """ if args['type'] == 'privmsg': send("Note-passing should be done in public.") return arguments = msg.split() if len(arguments) > 1: send("Sorry, I can only perform the summoning ritual for one person ...
java
@Override protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception { if (msg.getOpcode() == SASL_LIST_MECHS_OPCODE) { handleListMechsResponse(ctx, msg); } else if (msg.getOpcode() == SASL_AUTH_OPCODE) { handleAuthResponse(ctx, ms...
java
void finishConnection() { NioSocketConnector conn = this.connector; if (conn != null) { this.connector = null; conn.dispose(); for (ConnectionListener listener : this.connectionListeners) { listener.connectionEnded(this); } } ExecutorFilter execs = this.executors; if ...
java
protected void verifyAuthenticationContextSignature(final Pair<? extends SignableSAMLObject, MessageContext> authenticationContext, final HttpServletRequest request, final RequestAbstractType authnRequest, fi...
java
private static int getAnnotationDepth(final Method m, final Class<? extends Annotation> annotationClass) { // if we have invalid data the result is -1 if (m == null || annotationClass == null) { return -1; } if (m.isAnnotationPresent(annotationClass)) { return 1;...
python
def load(self, path: str) -> ClassFile: """Load the class at `path` and return it. Load will attempt to load the file at `path` and `path` + .class before failing. :param path: Fully-qualified path to a ClassFile. """ # Try to refresh the class from the cache, loading i...
python
def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None: """ Raise :exc:`NotImplementedError` in relation to a dialect for which a function hasn't been implemented (with a helpful error message). """ raise NotImplementedError( "Don't know how to {task} on dialect {dialect!r}. " ...
java
private static MQProperties buildMQProperties(Properties properties) { MQProperties mqProperties = new MQProperties(); String servers = CanalController.getProperty(properties, CanalConstants.CANAL_MQ_SERVERS); if (!StringUtils.isEmpty(servers)) { mqProperties.setServers(servers); ...
java
@Override public void setCenter(double cx, double cy, double cz) { this.center.set(cx, cy, cz); }
java
public static String readlineFromStdIn() throws IOException { StringBuilder ret = new StringBuilder(); int c; while ((c = System.in.read()) != '\n' && c != -1) { if (c != '\r') ret.append((char) c); } return ret.toString(); }
python
def enable_debug(self): """If the cli arg for foreground is set, set the configuration option for debug. """ if self.args.foreground: self.config.application[config.DEBUG] = True
java
public void set(final int row, final int col, final Object o) { if (o == null) cellValues[row][col] = new IcedWrapper(null); else if (o instanceof Double && Double.isNaN((double)o)) cellValues[row][col] = new IcedWrapper(Double.NaN); else if (o instanceof int[]) cellValues[row][col] = new ...
java
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { if (children == null) { children = new HashMap(); } PropertyChangeSupport child = (PropertyChangeSupport) children.get(propertyName); if (child == null) { child = new PropertyChangeSupport(source); children.pu...
java
public void setDataType(com.google.api.ads.admanager.axis.v201902.CustomFieldDataType dataType) { this.dataType = dataType; }
java
public static String quote(final String string) { int last = 0; final StringBuilder sb = new StringBuilder(); for (int i = 0; i < string.length(); i++) { if (needsQuoting(string.charAt(i))) { sb.append(string, last, i); last = i = quote(sb, strin...
python
def get_all_sizes_checksums(): """Returns dict associating URL to (size, sha256).""" sizes_checksums = {} for path in _checksum_paths().values(): data = _get_sizes_checksums(path) for url, size_checksum in data.items(): if (url in sizes_checksums and sizes_checksums[url] != size_checksum):...
python
def create_shot(self, sequence): """Create and return a new shot :param sequence: the sequence for the shot :type sequence: :class:`jukeboxcore.djadapter.models.Sequence` :returns: The created shot or None :rtype: None | :class:`jukeboxcore.djadapter.models.Shot` :raises...
python
def sum(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None): """Combine arrays by addition, with masks and offsets. Arrays and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an ar...
java
public static String render(String path, String templateFileName, Map<String, Object> bindingMap) { if (FileUtil.isAbsolutePath(path)) { return render(getFileTemplate(path, templateFileName), bindingMap); } else { return render(getClassPathTemplate(path, templateFileName), bindingMap); } }
python
def pypi_link(pkg_filename): """ Given the filename, including md5 fragment, construct the dependency link for PyPI. """ root = 'https://files.pythonhosted.org/packages/source' name, sep, rest = pkg_filename.partition('-') parts = root, name[0], name, pkg_filename return '/'.join(parts)
python
def queuify_logger(logger, queue_handler, queue_listener): """Replace logger's handlers with a queue handler while adding existing handlers to a queue listener. This is useful when you want to use a default logging config but then optionally add a logger's handlers to a queue during runtime. Args:...
java
@Override public boolean moveToTrash(Path path) throws IOException { Path fullyResolvedPath = path.isAbsolute() ? path : new Path(this.fs.getWorkingDirectory(), path); Path targetPathInTrash = PathUtils.mergePaths(this.trashLocation, fullyResolvedPath); if (!this.fs.exists(targetPathInTrash.getParent()))...
python
def sort_segment_points(Aps, Bps): """Takes two line segments and sorts all their points, so that they form a continuous path Args: Aps: Array of tracktotrip.Point Bps: Array of tracktotrip.Point Returns: Array with points ordered """ mid = [] j = 0 mid.append(Ap...
java
public ZonedDateTime minusNanos(long nanos) { return (nanos == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanos)); }
python
def kinetic(alpha1,lmn1,A,alpha2,lmn2,B): """ The full form of the kinetic energy integral >>> isclose(kinetic(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d')),2.953052) True """ l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 term0 = alpha2*(2*(l2+m2+n2)+3)*\ overlap(alpha1,(l1,m1...
java
public void addItemDetails(CmsListItemDetails itemDetail) { itemDetail.setListId(getListId()); m_itemDetails.addIdentifiableObject(itemDetail.getId(), itemDetail); }
python
def post_register_hook(self, verbosity=1): """Pull Docker images needed by processes after registering.""" if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False): call_command('list_docker_images', pull=True, verbosity=verbosity)
python
def showMenu(self, point): """ Displays the menu for this filter widget. """ menu = QMenu(self) acts = {} acts['edit'] = menu.addAction('Edit quick filter...') trigger = menu.exec_(self.mapToGlobal(point)) if trigger == acts['ed...
java
public void marshall(CreateCampaignRequest createCampaignRequest, ProtocolMarshaller protocolMarshaller) { if (createCampaignRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createCampaignRe...
java
@Unstable protected MetaData getNonGeneratedContentMetaData(String parameterName) { MetaData metaData = new MetaData(); Type contentType; if (this.macroDescriptor != null && this.macroDescriptor.getParameterDescriptorMap() != null && this.macroDescriptor.getParam...
java
protected void validate(String operationType) throws Exception { super.validate(operationType); MPSString image_name_validator = new MPSString(); image_name_validator.setConstraintIsReq(MPSConstants.GENERIC_CONSTRAINT, true); image_name_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 1...
java
public void marshall(DetachSecurityProfileRequest detachSecurityProfileRequest, ProtocolMarshaller protocolMarshaller) { if (detachSecurityProfileRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
python
def _command(self, event, command, *args, **kwargs): """ Context state controller. Check whether the transition is possible or not, it executes it and triggers the Hooks with the pre_* and post_* events. @param event: (str) event generated by the command. @param command...
java
public List<LabelledTriple> getTriples() { return triples.stream().map(this::labelTriple) .sorted(sortSubjects.thenComparing(sortPredicates).thenComparing(sortObjects)).collect(toList()); }
python
def watch_one_event(event_filter, callback, timeout_callback, timeout, args, start_time=None): """ Start to watch one event. :param event_filter: :param callback: :param timeout_callback: :param timeout: :param args: :param start_t...
python
def GetMACBRepresentationFromDescriptions(self, timestamp_descriptions): """Determines the MACB representation from the timestamp descriptions. MACB representation is a shorthand for representing one or more of modification, access, change, birth timestamp descriptions as the letters "MACB" or a "." if...
java
@Override public int compareTo(final RDFItem o) { if (id != null && o != null && o.id != null) { return id.compareTo(o.id); } return -1; }
python
def apply_transformation(self, structure, return_ranked_list=False): """ Args: structure (Structure): Input structure to dope Returns: [{"structure": Structure, "energy": float}] """ comp = structure.composition logger.info("Composition: %s" % com...
python
def after(self, time, function, args = []): """Call `function` after `time` milliseconds.""" callback_id = self.tk.after(time, self._call_wrapper, time, function, *args) self._callback[function] = [callback_id, False]
java
@Override public MailSendResult send(MailMessage message) { Assert.notNull(message, "Missing mail message!"); Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); Session session = getSession(prop...
java
@Override public Object find(Class entityClass, Object key) { HttpResponse response = null; EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamo...
java
private void addAllNamesIntoTrie() { for (Map.Entry<String, ZNames> entry : _tzNamesMap.entrySet()) { entry.getValue().addAsTimeZoneIntoTrie(entry.getKey(), _namesTrie); } for (Map.Entry<String, ZNames> entry : _mzNamesMap.entrySet()) { entry.getValue().addAsMetaZoneIntoT...
python
def fetch_api_key_from_uname(username, password, server_url): """ Retrieves an API key from the One Codex webpage given the username and password """ # TODO: Hit programmatic endpoint to fetch JWT key, not API key with requests.Session() as session: # get the login page normally text...
java
@SuppressWarnings("unchecked") private SimpleOrderedMap<Object> createSpan(ComponentSpan span, Boolean encode) throws IOException { // System.out.println("Create stats span " + span.dataType + " " // + span.statsType + " " + span.statsItems + " --- " + encode); SimpleOrderedMap<Object> mtasSpanRespo...
python
def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Produce a list of files corresponding to format_str located at data_path. This routine is invoked by pysat and is not intended for direct use by the end user. Multiple data levels may be supported via the 'tag' and 'sat_id' inp...
java
public EmbeddedMongoDB withVersion(Version.Main version) { Objects.requireNonNull(version, "version can not be null"); this.version = version; return this; }
java
public static DateTime offsetDay(Date date, int offset) { return offset(date, DateField.DAY_OF_YEAR, offset); }
java
public DirectoryEntry mkdir( DirectoryEntry parent, String name ) { if ( readOnly ) { throw new UnsupportedOperationException(); } File file = new File( toFile( parent ), name ); file.mkdirs(); return new DefaultDirectoryEntry( this, parent, name ); }