language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected Pair<String, Map<String, List<Object>>> convertPersonAttributesToPrincipal(final String extractedPrincipalId, final Map<String, List<Object>> attributes) { val convertedAttributes = new LinkedHashMap<String, List<...
python
def register(self, event, callback, selector=None): """ Resister an event that you want to monitor. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector...
python
def _sanity_check_no_nested_folds(ir_blocks): """Assert that there are no nested Fold contexts, and that every Fold has a matching Unfold.""" fold_seen = False for block in ir_blocks: if isinstance(block, Fold): if fold_seen: raise AssertionError(u'Found a nested Fold con...
python
def _open_browser(self, single_doc_html): """ Open a browser tab showing single """ url = os.path.join('file://', DOC_PATH, 'build', 'html', single_doc_html) webbrowser.open(url, new=2)
java
protected void adjustHomographSign( AssociatedPair p , DMatrixRMaj H ) { double val = GeometryMath_F64.innerProd(p.p2, H, p.p1); if( val < 0 ) CommonOps_DDRM.scale(-1, H); }
java
public void setEditable(final int row, final int col, final boolean enable) { final int actualIndex = getTableColumn(col).getIndex(); getRecord(row).setColumnEnabled(actualIndex, enable); }
java
@Override protected void init() { dataJoinNo = StringUtil.getMatchNo(labels, conf.get(SimpleJob.JOIN_DATA_COLUMN)); }
java
public void report(long arrivalTime) { checkArgument(arrivalTime >= 0, "arrivalTime must not be negative"); long latestHeartbeat = history.latestHeartbeatTime(); history.samples().addValue(arrivalTime - latestHeartbeat); history.setLatestHeartbeatTime(arrivalTime); }
java
public final EObject entryRuleJvmUpperBound() throws RecognitionException { EObject current = null; EObject iv_ruleJvmUpperBound = null; try { // InternalSARL.g:16394:54: (iv_ruleJvmUpperBound= ruleJvmUpperBound EOF ) // InternalSARL.g:16395:2: iv_ruleJvmUpperBound= ru...
java
private Properties loadConfig() throws IOException { String configUrl = String.format("%s/%s/%s", defaultRepositoryUrl, DIST_DIR, RESOLVE_CONFIG_FILE); log.info("Looking for repository-config at {}", configUrl); CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpget = new HttpGet(configUrl)...
python
def set_windows_permissions(filename): ''' At least on windows 7 if a file is created on an Admin account, Other users will not be given execute or full control. However if a user creates the file himself it will work... So just always change permissions after creating a file on windows Change ...
python
def input(msg="", default="", title="Lackey Input", hidden=False): """ Creates an input dialog with the specified message and default text. If `hidden`, creates a password dialog instead. Returns the entered value. """ root = tk.Tk() input_text = tk.StringVar() input_text.set(default) PopupInpu...
python
def update_field(self, name, value): """Changes the definition of a KV Store field. :param name: name of field to change :type name: ``string`` :param value: new field definition :type value: ``string`` :return: Result of POST request """ kwargs = {} ...
java
public DescribeTagsRequest withFilters(TagFilter... filters) { if (this.filters == null) { setFilters(new java.util.ArrayList<TagFilter>(filters.length)); } for (TagFilter ele : filters) { this.filters.add(ele); } return this; }
python
def lemma(self, verb, parse=True): """ Returns the infinitive form of the given verb, or None. """ if dict.__len__(self) == 0: self.load() if verb.lower() in self._inverse: return self._inverse[verb.lower()] if verb in self._inverse: return sel...
python
def valid_options(kwargs, allowed_options): """ Checks that kwargs are valid API options""" diff = set(kwargs) - set(allowed_options) if diff: print("Invalid option(s): ", ', '.join(diff)) return False return True
python
def _check_values(self, values): """Check values whenever they come through the values setter.""" assert isinstance(values, Iterable) and not \ isinstance(values, (str, dict, bytes, bytearray)), \ 'values should be a list or tuple. Got {}'.format(type(values)) assert len(...
python
def global_avgpooling(attrs, inputs, proto_obj): """Performs avg pooling on the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
python
def _EntriesGenerator(self): """Retrieves directory entries. Since a directory can contain a vast number of entries using a generator is more memory efficient. Yields: CPIOPathSpec: path specification. """ location = getattr(self.path_spec, 'location', None) if location and location...
java
public final Observable<Integer> averageInteger(Func1<? super T, Integer> valueExtractor) { return o.lift(new OperatorAverageInteger<T>(valueExtractor)); }
java
public static int lastWhitespaceIn(String source) { if (CmsStringUtil.isEmpty(source)) { return -1; } int pos = -1; for (int i = source.length() - 1; i >= 0; i--) { if (Character.isWhitespace(source.charAt(i))) { pos = i; break; ...
java
@Given("^I run '(.+?)' locally( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$") public void executeLocalCommand(String command, String foo, Integer exitStatus, String bar, String envVar) throws Exception { if (exitStatus == null) { exitStatus = 0; } ...
java
public void applyAndJournal(Supplier<JournalContext> context, MutableInode<?> inode) { try { applyCreateInode(inode); context.get().append(inode.toJournalEntry()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Failed to apply %s", inode); throw t; // fatalError will usually sy...
python
def plotBasis(self, filename=None): """ Plots the basis functions, reshaped in 2-dimensional arrays. This representation makes the most sense for visual input. :param: filename (string) Can be provided to save the figure """ if np.floor(np.sqrt(self.filterDim)) ** 2 != self.filterDim: ...
python
def reset_can(self, channel=Channel.CHANNEL_CH0, flags=ResetFlags.RESET_ALL): """ Resets a CAN channel of a device (hardware reset, empty buffer, and so on). :param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int flags: Flag...
java
public static Directory getDirectory() throws EFapsException { IDirectoryProvider provider = null; if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXDIRECTORYPROVCLASS)) { final String clazzname = EFapsSystemConfiguration.get().getAttributeValue( ...
java
public static HijriCalendar ofUmalqura( int hyear, int hmonth, int hdom ) { return HijriCalendar.of(VARIANT_UMALQURA, hyear, hmonth, hdom); }
python
def thermal_state(omega_level, T, return_diagonal=False): r"""Return a thermal state for a given set of levels. INPUT: - ``omega_level`` - The angular frequencies of each state. - ``T`` - The temperature of the ensemble (in Kelvin). - ``return_diagonal`` - Whether to return only the populations...
java
public byte[] getBytes() { byte b[] = new byte[getLength()]; int bytesCopied = 0; Iterator<V> it = this.values().iterator(); while (it.hasNext()) { ID3v2Frame frame = (ID3v2Frame) it.next(); System.arraycopy(frame.getFrameBytes(), 0, b, bytesCopied, frame.getFrameLength()); bytesCopied += frame.get...
python
def _rotate_vector(x, y, x2, y2, x1, y1): """ rotate x,y vector over x2-x1, y2-y1 angle """ angle = atan2(y2 - y1, x2 - x1) cos_rad = cos(angle) sin_rad = sin(angle) return cos_rad * x + sin_rad * y, -sin_rad * x + cos_rad * y
java
@SuppressWarnings("WeakerAccess") public static void setStatementResolver(StatementResolver statementResolver) { if (statementResolver == null) { throw new NullPointerException("The statement resolver must not be null."); } StatementResolverHolder.STATEMENT_RESOLVER.set(statement...
java
@Trivial protected void activate(ComponentContext context) throws Exception { Dictionary<String, ?> props = context.getProperties(); final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(this, tc, "activate", props); Strin...
java
@Override protected void addSummaryType(Element member, Content tdSummaryType) { ExecutableElement meth = (ExecutableElement)member; addModifierAndType(meth, utils.getReturnType(meth), tdSummaryType); }
java
public List<Boolean> exists(List<Value> keyValues) throws AerospikeException { List<Boolean> target = new ArrayList<Boolean>(); for (Object value : keyValues) { target.add(exists(Value.get(value))); } return target; }
python
def get_local_gb(iLOIP, snmp_credentials): """Gets the maximum disk size among all disks. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials in a dictionary having following mandatory keys. auth_user: SNMP user ...
python
def on_drag_data_get(self, widget, context, data, info, time): '''拖放开始''' tree_paths = self.iconview.get_selected_items() if not tree_paths: return filelist = [] for tree_path in tree_paths: filelist.append({ 'path': self.liststore[tree_pat...
python
def _set_up_figure(self, x_mins, x_maxs, y_mins, y_maxs): """ Prepare the matplotlib figure: make all the subplots; adjust their x and y range; plot the data; and plot an putative function. """ self.fig = plt.figure() # Make room for the sliders: bot = 0.1 + 0.05...
python
def viewer_has_liked(self) -> Optional[bool]: """Whether the viewer has liked the post, or None if not logged in.""" if not self._context.is_logged_in: return None if 'likes' in self._node and 'viewer_has_liked' in self._node['likes']: return self._node['likes']['viewer_h...
python
def compound_statements(logical_line): r"""Compound statements (on the same line) are generally discouraged. While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines! Always use a def statemen...
java
public void encodeAMO(final MiniSatStyleSolver s, final LNGIntVector lits) { switch (this.amoEncoding) { case LADDER: this.ladder.encode(s, lits); break; default: throw new IllegalStateException("Unknown AMO encoding: " + this.amoEncoding); } }
java
public static WindowOver<Double> regrSxx(Expression<? extends Number> arg1, Expression<? extends Number> arg2) { return new WindowOver<Double>(Double.class, SQLOps.REGR_SXX, arg1, arg2); }
python
def parser(scope, usage=''): """ Generates a default parser for the inputted scope. :param scope | <dict> || <module> usage | <str> callable | <str> :return <OptionParser> """ subcmds = [] for cmd in commands(scope): subcmds.ap...
python
def diff(self): """ shortcut to netdiff.diff """ latest = self.latest current = NetJsonParser(self.json()) return diff(current, latest)
java
public Map<String, FieldType> flatten() { if (fields == null || fields.length == 0) { return Collections.<String, FieldType> emptyMap(); } Map<String, FieldType> map = new LinkedHashMap<String, FieldType>(); for (Field nestedField : fields) { addSubFieldToMap(ma...
java
public static String removeSessionId(String sessionId, String page) { String regexp = ";?jsessionid=" + Pattern.quote(sessionId); return page.replaceAll(regexp, ""); }
python
def _sendReset(self, sequenceId=0): """ Sends a reset signal to the network. """ # Handle logging - this has to be done first if self.logCalls: frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) values.pop('frame') values.pop('self') (_, fil...
python
def garud_h(h): """Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures of soft sweeps, as defined in Garud et al. (2015). Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. Returns ------- h1 : float H1 stati...
java
@Nonnull public Word<I> longestCommonPrefix(Word<?> other) { int len = length(), otherLen = other.length(); int maxIdx = (len < otherLen) ? len : otherLen; int i = 0; while (i < maxIdx) { I sym1 = getSymbol(i); Object sym2 = other.getSymbol(i); i...
python
def get_source(self, environment, template): ''' Salt-specific loader to find imported jinja files. Jinja imports will be interpreted as originating from the top of each of the directories in the searchpath when the template name does not begin with './' or '../'. When a templa...
python
def get_xy_dataset_statistics_pandas(dataframe, x_series, y_series, fcorrect_x_cutoff = 1.0, fcorrect_y_cutoff = 1.0, x_fuzzy_range = 0.1, y_scalar = 1.0, ignore_null_values = False, bootstrap_data = False, expect_negative_correlation = False, STDe...
java
public NativeQuery withDMLResultsDisplaySize(int DMLResultsDisplaySize) { if (!getOperationType(boundStatement).isUpsert) { options.setDMLResultsDisplaySize(Optional.of(Integer.max(0,Integer.min(DMLResultsDisplaySize, CassandraOptions.MAX_RESULTS_DISPLAY_SIZE)))); } return this; ...
java
public static Marshaller createMarshaller(Class clazz, String encoding) { try { JAXBContext jaxbContext = getJaxbContext(clazz); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); if (StringUtils.isNotBlank(encoding)) { ma...
python
async def playback(dev: Device, cmd, target, value): """Get and set playback settings, e.g. repeat and shuffle..""" if target and value: dev.set_playback_settings(target, value) if cmd == "support": click.echo("Supported playback functions:") supported = await dev.get_supported_playb...
python
def locations(self): """ Available locations to be used when creating a new machine. :returns: A list of available locations. """ req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/locations') locations = req.get().json() return locations
java
public void setModel (PropertySheetModel pm) { if (pm instanceof org.apache.ojb.tools.mapping.reversedb.DBMeta) { this.aMeta = (org.apache.ojb.tools.mapping.reversedb.DBMeta)pm; this.readValuesFromMeta(); } else throw new IllegalArgumentException(); }
python
def get_user_by_userid(self, userid): ''' get user by user id ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, respons...
java
public static base_response enable(nitro_service client, Long clid) throws Exception { clusterinstance enableresource = new clusterinstance(); enableresource.clid = clid; return enableresource.perform_operation(client,"enable"); }
python
def lookup_command(cmdname, mode): """ returns commandclass, argparser and forced parameters used to construct a command for `cmdname` when called in `mode`. :param cmdname: name of the command to look up :type cmdname: str :param mode: mode identifier :type mode: str :rtype: (:class:`C...
python
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. ''' val = hexdecode(text) if self.pyclass is not None: return self.pyclass(val) return val
java
protected static PatchElement createPatchElement(final PatchEntry entry, String patchId, final List<ContentModification> modifications) { final PatchElement patchElement = entry.element; final PatchElementImpl element = new PatchElementImpl(patchId); element.setProvider(patchElement.getProvider(...
java
public static CommerceVirtualOrderItem fetchByUuid_C_First(String uuid, long companyId, OrderByComparator<CommerceVirtualOrderItem> orderByComparator) { return getPersistence() .fetchByUuid_C_First(uuid, companyId, orderByComparator); }
python
def title(self) -> str: """Get/Set title string of this document.""" title_element = _find_tag(self.head, 'title') if title_element: return title_element.textContent return ''
java
public synchronized void add(SocketBox sb) { int status = ((ManagedSocketBox) sb).getStatus(); if (allSockets.containsKey(sb)) { throw new IllegalArgumentException("This socket already exists in the socket pool."); } allSockets.put(sb, sb); if (status == ManagedSo...
java
public ServiceFuture<SignalRKeysInner> beginRegenerateKeyAsync(String resourceGroupName, String resourceName, final ServiceCallback<SignalRKeysInner> serviceCallback) { return ServiceFuture.fromResponse(beginRegenerateKeyWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback); }
java
protected Map<MarshallerType, AbstractType> getDefaultMarshallers(CfDef cfDef) throws IOException { Map<MarshallerType, AbstractType> marshallers = new EnumMap<MarshallerType, AbstractType>(MarshallerType.class); AbstractType comparator; AbstractType subcomparator; AbstractType defau...
java
public static void expandAll(JTree tree, TreePath path, boolean expand) { TreeNode node = (TreeNode)path.getLastPathComponent(); if (node.getChildCount() >= 0) { Enumeration<?> enumeration = node.children(); while (enumeration.hasMoreElements()) { TreeNode n = (TreeNode)enumeration.nextElement(); ...
java
public void setScript(String newScript) { String oldScript = script; script = newScript; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT, oldScript, script)); }
python
def list_delete(self, id): """ Delete a list. """ id = self.__unpack_id(id) self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id))
java
@POST @Path("delete/{repository}/{workspace}/{path:.*}") public Response deleteScript(@PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ses = sessionProviderService.getSe...
java
synchronized void setDefaultParent(final Actor defaultParent) { if (defaultParent != null && this.defaultParent != null) { throw new IllegalStateException("Default parent already exists."); } this.defaultParent = defaultParent; }
python
def inverse_qft(qubits: List[int]) -> Program: """ Generate a program to compute the inverse quantum Fourier transform on a set of qubits. :param qubits: A list of qubit indexes. :return: A Quil program to compute the inverse Fourier transform of the qubits. """ qft_result = Program().inst...
java
public List<Method> listMethods( final Class<?> classObj, final String methodName ) { // // Get the array of methods for my classname. // Method[] methods = classObj.getMethods(); List<Method> methodSignatures = new ArrayList<M...
java
private static String getResourceIconClasses(String resourceTypeName, String fileName, boolean small) { StringBuffer sb = new StringBuffer(CmsGwtConstants.TYPE_ICON_CLASS); sb.append(" ").append(getResourceTypeIconClass(resourceTypeName, small)).append(" ").append( getFileTypeIconClass(reso...
python
def interp_S_t(S, t, z, z_new, p=None): ''' Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`. Args ---- S: ndarray CTD salinities t: ndarray CTD temperatures z: ndarray CTD Depths, must be a strictly increasing or decreasing 1-D array, and its ...
java
public static String getConfigParam(String key, String defaultValue) { if (config == null) { init(null); } if (StringUtils.isBlank(key)) { return defaultValue; } String keyVar = key.replaceAll("\\.", "_"); String env = System.getenv(keyVar) == null ? System.getenv(PARA + "_" + keyVar) : System.getenv(...
java
public Observable<Boolean> beginTransaction(Observable<?> dependency) { return update("begin").dependsOn(dependency).count().map(Functions.constant(true)); }
java
public XAttributeNameMap getMapping(String name) { XAttributeNameMapImpl mapping = mappings.get(name); if(mapping == null) { mapping = new XAttributeNameMapImpl(name); mappings.put(name, mapping); } return mapping; }
java
public String getTimeString() { Calendar cal = getCalendar(); return toClockString(cal.get(Calendar.HOUR)) + (((cal.get(Calendar.SECOND) % 2) == 0) ? ":" : " ") + toClockString(cal.get(Calendar.MINUTE)); }
python
def get_users(self, capacity=None): # type: (Optional[str]) -> List[User] """Returns the organization's users. Args: capacity (Optional[str]): Filter by capacity eg. member, admin. Defaults to None. Returns: List[User]: Organization's users. """ u...
java
@CheckResult public static boolean onNewIntent(@NonNull Intent intent, @NonNull Activity activity) { //noinspection ConstantConditions checkArgument(intent != null, "intent may not be null"); if (intent.hasExtra(InternalLifecycleIntegration.INTENT_KEY)) { InternalLifecycleIntegration.require(act...
python
def terminate_all(self): """Terminate all worker processes.""" for worker in self._workers: worker.terminate() # for thread in self._threads: # try: # thread.terminate() # thread.wait() # except Exception: # pas...
python
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None): """ Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to ena...
python
def add_output(self, output): """Adds an output to a Transaction's list of outputs. Args: output (:class:`~bigchaindb.common.transaction. Output`): An Output to be added to the Transaction. """ if not isinstance(output, Output)...
python
def get_shard_by_key_id(self, key_id): """ get_shard_by_key_id returns the Redis shard given a key id. Keyword arguments: key_id -- the key id (e.g. '12345') This is similar to get_shard_by_key(key) except that it will not search for a key id within the curly braces. ...
python
def onMessage(self, payload, is_binary): """ Called when a client sends a message """ if not is_binary: payload = payload.decode('utf-8') logger.debug("Incoming message ({peer}) : {message}".format( peer=self.peer, message=payload)) #...
python
def verify(self): ''' Verify the correctness of the region arcs. Throws an VennRegionException if verification fails (or any other exception if it happens during verification). ''' # Verify size of arcs list if (len(self.arcs) < 2): raise VennRegionException("...
java
public String config(String subFolder, String fileName) { return setCurrentFilename(subFolder, fileName, CONFIG); }
python
def _init_io_container(self, init_value): """Initialize container to hold lob data. Here either a cStringIO or a io.StringIO class is used depending on the Python version. For CLobs ensure that an initial unicode value only contains valid ascii chars. """ if isinstance(init_value...
python
def xdr(self): """Packs and base64 encodes this :class:`Operation` as an XDR string. """ op = Xdr.StellarXDRPacker() op.pack_Operation(self.to_xdr_object()) return base64.b64encode(op.get_buffer())
python
def delete_calendar_event(self, id, cancel_reason=None): """ Delete a calendar event. Delete an event from the calendar and return the deleted event """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"...
java
void insertResult(PersistentStore store, Result ins) { RowSetNavigator nav = ins.initialiseNavigator(); while (nav.hasNext()) { Object[] data = nav.getNext(); Object[] newData = (Object[]) ArrayUtil.resizeArrayIfDifferent(data, getColumnCount...
java
public static Date max(Date d1, Date d2) { Date result; if (d1 == null) { result = d2; } else if (d2 == null) { result = d1; } else { result = (d1.compareTo(d2) > 0) ? d1 : d2; } return result; ...
java
public String getTopic() { if (tc.isEntryEnabled()) { SibTr.entry(tc, "getTopic"); SibTr.exit(tc, "getTopic", topic); } return topic; }
java
public com.google.api.ads.admanager.axis.v201811.DeliveryRateType getDeliveryRateType() { return deliveryRateType; }
java
public static OffsetGroup from(final CharOffset charOffset, final EDTOffset edtOffset) { return new Builder().charOffset(charOffset).edtOffset(edtOffset).build(); }
java
public void deleteNode(String path, long zxid) throws KeeperException.NoNodeException { int lastSlash = path.lastIndexOf('/'); String parentName = path.substring(0, lastSlash); String childName = path.substring(lastSlash + 1); DataNode node = nodes.get(path); if (node...
java
public static TransTypes instance(Context context) { TransTypes instance = context.get(transTypesKey); if (instance == null) instance = new TransTypes(context); return instance; }
java
public static <T, R> List<R> processList(Class<R> clazz, List<T> src, BiConsumer<R, T> biConsumer) { if (!Lists.iterable(src)) { log.warn("the src argument must be not null, return empty list. "); return Lists.newArrayList(); } return src.stream().map(e -> process(clazz, ...
java
private void handleLeaveEvent(Node node) { members.compute(MemberId.from(node.id().id()), (id, member) -> member == null || !member.isActive() ? null : member); }
python
def get_context_data(self, **kwargs): """ Hook for adding arguments to the context. """ context = {'obj': self.object } if 'queryset' in kwargs: context['conf_msg'] = self.get_confirmation_message(kwargs['queryset']) context.update(kwargs) return cont...