language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _set_properties(self, flags): """Set the properties of the message flags based on a byte input.""" flagByte = self._normalize(flags) if flagByte is not None: self._messageType = (flagByte[0] & 0xe0) >> 5 self._extended = (flagByte[0] & MESSAGE_FLAG_EXTENDED_0X10) >> ...
python
def routingAreaUpdateRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, DrxParameter_presence=0, TmsiStatus_presence=0): """ROUTING AREA UPDATE REQUEST Section 9.4.14""" a = TpPd(pd=0x3) b = MessageType(mesType=0x8)...
python
def get_actor(self, name): """ Get an actor by name :param name: str :return: """ return next((x for x in self.actors if x.name == name), None)
java
public void setupDB() throws Exception { if (m_bean.isInitialized()) { System.out.println("Setup-Bean initialized successfully."); CmsSetupDb db = new CmsSetupDb(m_bean.getWebAppRfsPath()); try { // try to connect as the runtime user db...
java
public static Flow create() { return new Flow(ID_GENERATOR.updateAndGet(i -> i == Integer.MAX_VALUE ? 0 : i + 1), 0); }
python
def quick_idw(input_geojson_points, variable_name, power, nb_class, nb_pts=10000, resolution=None, disc_func=None, mask=None, user_defined_breaks=None, variable_name2=None, output='GeoJSON', **kwargs): """ Function acting as a one-shot wrapper around SmoothIdw object. ...
java
@Override public boolean configure(FeatureContext context) { if (!context.getConfiguration().isRegistered(TextMessageBodyWriter.class)) { context.register(TextMessageBodyWriter.class); } if (!context.getConfiguration().isRegistered(CaptchaWriterInterceptor.class)) { ...
java
public java.util.Map<String, String> getEvalDecisionDetails() { if (evalDecisionDetails == null) { evalDecisionDetails = new com.amazonaws.internal.SdkInternalMap<String, String>(); } return evalDecisionDetails; }
python
def pythonize(self, val): """Convert value into a dict:: * If value is a list, try to take the last element * split "key=value" string and convert to { key:value } :param val: value to convert :type val: :return: log level corresponding to value :rtype: str ...
java
public int[] getKeys() { int[] keys = this.keys; int n = keyCount; int[] result = new int[n]; for (int i = 0; n != 0; ++i) { int entry = keys[i]; if (entry != EMPTY && entry != DELETED) { result[--n] = entry; } } return ...
python
def check_oversized_pickle(pickled, name, obj_type, worker): """Send a warning message if the pickled object is too large. Args: pickled: the pickled object. name: name of the pickled object. obj_type: type of the pickled object, can be 'function', 'remote function', 'actor'...
java
public void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { try { CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction; if (txObject.getHolder() == null) { CompensatingTransactionHolderSupport contextHolder = getNewHolder(); txO...
java
public static ExecutableScript getScriptFromResource(String language, String resource, ExpressionManager expressionManager, ScriptFactory scriptFactory) { ensureNotEmpty(NotValidException.class, "Script language", language); ensureNotEmpty(NotValidException.class, "Script resource", resource); if (isDynamic...
java
public PngByteArrayOutputStream inflate(PngByteArrayOutputStream bytes) throws IOException { try (final PngByteArrayOutputStream inflatedOut = new PngByteArrayOutputStream(); final InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(bytes.get(), 0, bytes.len()))) { int readLengt...
java
public ModelService getService(String serviceName, Watcher watcher){ WatcherRegistration wcb = null; if (watcher != null) { wcb = new WatcherRegistration(serviceName, watcher); } ProtocolHeader header = new ProtocolHeader(); header.setType(ProtocolType.GetService); ...
java
public Message setBuffer(Buffer buf) { if(buf != null) { this.buf=buf.getBuf(); this.offset=buf.getOffset(); this.length=buf.getLength(); } return this; }
python
def IP_verified(directory, extensions_to_ignore=None, directories_to_ignore=None, files_to_ignore=None, verbose=False): """Find and audit potential data files that might violate IP This is the public function to be used to ascertain that all d...
java
public static void splitSqlScript(EncodedResource resource, String script, String separator, String commentPrefix, String blockCommentStartDelimiter, String blockCommentEndDelimiter, List<String> statements) throws ScriptException { Assert.hasText(script, "scri...
java
void recomputeProgress() { if (isComplete()) { this.progress = 1; // update the counters and the state TaskStatus completedStatus = taskStatuses.get(getSuccessfulTaskid()); this.counters = completedStatus.getCounters(); this.state = completedStatus.getStateString(); } else if (fail...
python
def directed_tripartition_indices(N): """Return indices for directed tripartitions of a sequence. Args: N (int): The length of the sequence. Returns: list[tuple]: A list of tuples containing the indices for each partition. Example: >>> N = 1 >>> directed_tripar...
java
@Override public S withProperties(Properties props) { XmlConfigHelper.showUnrecognizedAttributes(XmlConfigHelper.setAttributes(attributes, props, false, false)); attributes.attribute(PROPERTIES).set(new TypedProperties(props)); this.properties = props; return self(); }
java
public static Collection<AnnotationValue> resolveTypeQualifiers(Collection<AnnotationValue> values) { if (values.isEmpty()) { return Collections.emptyList(); } LinkedList<AnnotationValue> result = new LinkedList<>(); LinkedList<ClassDescriptor> onStack = new LinkedList<>(); ...
python
def triggered(self): """ For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached. """ if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_re...
python
def quartz_mouse_process(pipe): """Single subprocess for reading mouse events on Mac using newer Quartz.""" # Quartz only on the mac, so don't warn about Quartz # pylint: disable=import-error import Quartz # pylint: disable=no-member class QuartzMouseListener(QuartzMouseBaseListener): "...
java
private void performCopytoTask(final Map<FileInfo, FileInfo> copyToMap) { for (final Map.Entry<FileInfo, FileInfo> entry : copyToMap.entrySet()) { final URI copytoTarget = entry.getKey().uri; final URI copytoSource = entry.getValue().uri; final URI srcFile = job.tempDirURI.re...
python
def epsilon_crit(self): """ returns the critical projected mass density in units of M_sun/Mpc^2 (physical units) """ const_SI = const.c**2 / (4*np.pi * const.G) #c^2/(4*pi*G) in units of [kg/m] conversion = const.Mpc / const.M_sun # converts [kg/m] to [M_sun/Mpc] pre_co...
python
def scale(self, factor, inplace=True): """ Multiplies all branch lengths by factor. """ if not inplace: t = self.copy() else: t = self t._tree.scale_edges(factor) t._dirty = True return t
java
public void clean() { if (!remove(this)) return; try { thunk.run(); } catch (final Throwable x) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { if (System.err != null) ...
java
public static double[] unshuffleDoubleArray(byte[] input) throws IOException { double[] output = new double[input.length / 8]; int numProcessed = impl.unshuffle(input, 0, 8, input.length, output, 0); assert(numProcessed == input.length); return output; }
python
def common_mean_watson(Data1, Data2, NumSims=5000, print_result=True, plot='no', save=False, save_folder='.', fmt='svg'): """ Conduct a Watson V test for a common mean on two directional data sets. This function calculates Watson's V statistic from input files through Monte Carlo simulation in order to...
java
public static File addPrjFileToArchive(File file, String targetCrs) throws ZipException, IOException, NoSuchAuthorityCodeException, FactoryException { ZipFile zipFile = new ZipFile(file); CoordinateReferenceSystem decodedTargetCrs = CRS.decode(targetCrs); String targetCrsWkt = toSingle...
java
public static String getClassName(Class<?> cls) { if (cls.isMemberClass()) { String name = cls.getName(); name = StringUtils.substringAfterLast(name, PACKAGE_SEPARATOR); return name; } return cls.getSimpleName(); }
python
def write_posterior(self, filename, **kwargs): """Write posterior only file Parameters ---------- filename : str Name of output file to store posterior """ f = h5py.File(filename, 'w') # Preserve top-level metadata for key in self.attrs: ...
java
private void extractCurrPtInfo() { // Get new drag/pinch params. Only read multitouch fields that are needed, // to avoid unnecessary computation (diameter and angle are expensive operations). mCurrPtX = mCurrPt.getX(); mCurrPtY = mCurrPt.getY(); mCurrPtDiam = Math.max(MIN_MULTITOUCH_SEPARATION * .71f, !mCurr...
java
@SuppressWarnings({"SameParameterValue", "WeakerAccess"}) public static void createMetadataCache(final SlotReference slot, final int playlistId, final File cache, final MetadataCacheCreationListener listener) throws Exception { ConnectionManager.ClientTask<Obj...
java
@Override public GrantAccessResult grantAccess(GrantAccessRequest request) { request = beforeClientExecution(request); return executeGrantAccess(request); }
python
def _build_search_query(self, from_date): """Build an ElasticSearch search query to retrieve items for read methods. :param from_date: date to start retrieving items from. :return: JSON query in dict format """ sort = [{self._sort_on_field: {"order": "asc"}}] filters =...
python
def show_kernel_error(self, error): """Show kernel initialization errors in infowidget.""" # Replace end of line chars with <br> eol = sourcecode.get_eol_chars(error) if eol: error = error.replace(eol, '<br>') # Don't break lines in hyphens # From htt...
python
def __get_grants(self, target_file, all_grant_data): """ Return grant permission, grant owner, grant owner email and grant id as a list. It needs you to set k.key to a key on amazon (file path) before running this. note that Amazon returns a list of grants for each file. option...
python
def _finalize(self): """Dump traces using cPickle.""" container = {} try: for name in self._traces: container[name] = self._traces[name]._trace container['_state_'] = self._state_ file = open(self.filename, 'w+b') std_pickle.dump(c...
python
def add_permissions_view(self, base_permissions, view_menu): """ Adds a permission on a view menu to the backend :param base_permissions: list of permissions from view (all exposed methods): 'can_add','can_edit' etc... :param view_menu: ...
java
public static String joinWithOriginalWhiteSpace(List<CoreLabel> tokens) { if (tokens.size() == 0) { return ""; } CoreLabel lastToken = tokens.get(0); StringBuffer buffer = new StringBuffer(lastToken.word()); for (int i = 1; i < tokens.size(); i++) { CoreLabel currentToken = to...
python
def board_msg(self): """Structure a board as in print_board.""" board_str = "s\t\t" for i in xrange(self.board_width): board_str += str(i)+"\t" board_str = board_str.expandtabs(4)+"\n\n" for i in xrange(self.board_height): temp_line = str(i)+"\t\t" ...
python
def compliance_violation(self, column=None, value=None, **kwargs): """ A compliance schedule violation reflects the non-achievement of a given compliance schedule event including the type of violation and ty pe of resolution. >>> PCS().compliance_violation('cs_rnc_detect_date', ...
java
public void decode(ByteBuffer source, ByteBuffer target) throws IOException { if (target == null) throw new IllegalStateException(); int last = this.last; int state = this.state; int remaining = source.remaining(); int targetRemaining = targe...
python
def newLayer(self, name, color=None): """ Make a new layer with **name** and **color**. **name** must be a :ref:`type-string` and **color** must be a :ref:`type-color` or ``None``. >>> layer = font.newLayer("My Layer 3") The will return the newly created :cl...
java
public CompletableFuture<Object> deleteAsync(@DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> delete(closure), getExecutor()); }
java
public void removeMatch(String name, PseudoClassType pseudoClass) { if (names != null) { Set<PseudoClassType> classes = names.get(name); if (classes != null) classes.remove(pseudoClass); } }
python
def unique_index(data, keys=None, fail_on_dup=True): """ RETURN dict THAT USES KEYS TO INDEX DATA ONLY ONE VALUE ALLOWED PER UNIQUE KEY """ o = UniqueIndex(listwrap(keys), fail_on_dup=fail_on_dup) for d in data: try: o.add(d) except Exception as e: o.add(...
java
@Override public final void makeOtherEntries(final Map<String, Object> pAddParam, final SalesReturn pEntity, final IRequestData pRequestData, final boolean pIsNew) throws Exception { String actionAdd = pRequestData.getParameter("actionAdd"); if ("makeAccEntries".equals(actionAdd) && pEntity.ge...
java
public final HourRanges compress() { final List<HourRanges> normalized = normalize(); if (normalized.size() == 1) { return valueOf(normalized.get(0).toMinutes()); } else if (normalized.size() == 2) { final HourRanges firstDay = valueOf(normalized.get(0).toMinutes()); ...
python
def apply_check_config(self, config): """ Takes the `query` and `response` fields from a validated config dictionary and sets the proper instance attributes. """ self.query = config.get("query") self.expected_response = config.get("response")
python
def addTopLevelItem(self, item): """ Adds the inputed item to the gantt widget. :param item | <XGanttWidgetItem> """ vitem = item.viewItem() self.treeWidget().addTopLevelItem(item) self.viewWidget().scene().addItem(vitem) ...
python
def createGroupResponse(self, group, vendorSpecific=None): """CNIdentity.createGroup(session, groupName) → Subject https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.createGroup. Args: group: vendorSpecific: Returns: ...
java
static void processError(String type, String errString, HttpServerExchange exchange) { exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE); exchange.getResponseHeaders().add(new HttpString("Version"), VERSION_PROTOCOL);...
java
@Override public synchronized IServiceImplementation getServiceImplementation() throws ModelException { if (null == this.serviceImplementation) { IServiceFunctionality advFunc = this.getAdvertisedFunctionality(); if (advFunc instanceof ServiceFunctionality) { ...
python
def get_repository_tags(self, namespace, repository): """GET /v1/repositories/(namespace)/(repository)/tags""" return self._http_call(self.TAGS, get, namespace=namespace, repository=repository)
python
def get_condition_filter(condition, field_map={}): """ Return the appropriate filter for a given group condition. # TODO: integrate this into groups_filter_from_query function. """ field_name = condition.get("field") field_name = field_map.get(field_name, field_name) operation = condition[...
java
public void setOwner(Path p, String username, String groupname ) throws IOException { if (username == null && groupname == null) { throw new IOException("username == null && groupname == null"); } dfs.setOwner(getPathName(p), username, groupname); }
java
public long getContentLength(MIMETypedStream stream) { long length = 0; if (stream.header != null) { for (int i = 0; i < stream.header.length; i++) { if (stream.header[i].name != null && !stream.header[i].name.equalsIgnoreCase("") ...
java
public static <T extends Enum<T> & Defaultable> PropertiesManager<T> newManager(File file, Class<T> keyType, final Retriever... retrievers) { ...
python
def track_progress( measure: MeasureProgress, target: MetricProgress, interval_check: float, capture_maybe: Optional[CaptureProgress] = None ) -> None: """ Tracks progress against a certain end condition of the simulation (for instance, a certain duration on the simulated clock), reporting t...
java
protected String uploadToExternalPayloadStorage(ExternalPayloadStorage.PayloadType payloadType, byte[] payloadBytes, long payloadSize) { Preconditions.checkArgument(payloadType.equals(ExternalPayloadStorage.PayloadType.WORKFLOW_INPUT) || payloadType.equals(ExternalPayloadStorage.PayloadType.TASK_OUTPUT), ...
python
def get_trees(self, data, showerrors = False): # -> list: """ returns a list of trees with valid guesses """ if not all(check(self._productionset.alphabet, [x]) for x in data): raise ValueError("Unknown element in {}, alphabet:{}".format(str(data), self.productionset.alphabet)) resul...
java
public static boolean same(Localizable a, Localizable b) { return Double.compare(a.getX(), b.getX()) == 0 && Double.compare(a.getY(), b.getY()) == 0; }
python
def netconf_state_sessions_session_in_bad_rpcs(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") sessions = ET.SubElement(netconf_state, "se...
python
def dfsmooth (window, df, ucol, k=None): """Smooth a :class:`pandas.DataFrame` according to a window, weighting based on uncertainties. Arguments are: window The smoothing window. df The :class:`pandas.DataFrame`. ucol The name of the column in *df* that contains the uncertai...
python
def check_path_traversal(path, user='root', skip_perm_errors=False): ''' Walk from the root up to a directory and verify that the current user has access to read each directory. This is used for making sure a user can read all parent directories of the minion's key before trying to go and generate...
java
protected Path getPath(long time) { String formatString = getPathFormat(); if (formatString == null) throw new IllegalStateException(L.l("getPath requires a format path")); String pathString = getFormatName(formatString, time); return getPwd().resolve(pathString); }
python
def _on_changed(self): """Slot for changed events""" page = self._get_page() if not page.flag_autosave: page.flag_changed = True self._update_gui_text_tabs()
java
public final long getBeUint32(final int pos) { final int position = origin + pos; if (pos + 3 >= limit || pos < 0) throw new IllegalArgumentException("limit excceed: " + (pos < 0 ? pos : (pos + 3))); byte[] buf =...
java
@Override public void setWeights(Map<String, INDArray> weights) throws InvalidKerasConfigurationException { this.weights = new HashMap<>(); // TODO: "embeddings" is incorrectly read as "s" for some applications if (weights.containsKey("s")) { INDArray kernel = weights.get("s"); ...
python
def tag_image(self, image_id, tag_list): ''' a method for adding or updating tags on an AWS instance :param image_id: string with AWS id of instance :param tag_list: list of tags to add to instance :return: dictionary with response data ''' title = '%s.tag_...
java
private void doMultiMapKeys(final Message<JsonObject> message) { final String name = message.body().getString("name"); if (name == null) { message.reply(new JsonObject().putString("status", "error").putString("message", "No name specified.")); return; } context.execute(new Action<Set<Object...
java
public AspImpl assignAspToAs(String asName, String aspName) throws Exception { // check ASP and AS exist with given name AsImpl asImpl = (AsImpl) this.getAs(asName); if (asImpl == null) { throw new Exception(String.format(M3UAOAMMessages.NO_AS_FOUND, asName)); } Asp...
python
def to_dict_formatter(row, cursor): """ Take a row and use the column names from cursor to turn the row into a dictionary. Note: converts column names to lower-case! :param row: one database row, sequence of column values :type row: (value, ...) :param cursor: the cursor which was used to make...
python
def contains_pt(self, pt): """Containment test.""" obj1, obj2 = self.objects return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt))
java
public void start() throws Throwable { if (!isExternal) { executorService = Executors.newSingleThreadExecutor(new IdleThreadFactory()); } shutdown.set(false); interval = Long.MAX_VALUE; next = Long.MAX_VALUE; executorService.execute(new IdleConnectionRemoverRunner...
java
public KType indexGet(int index) { assert index >= 0 : "The index must point at an existing key."; assert index <= mask || (index == mask + 1 && hasEmptyKey); return Intrinsics.<KType> cast(keys[index]); }
java
@Override public void debug(String msg) { log.logIfEnabled(FQCN, Level.DEBUG, null, msg, (Object) null); }
python
def check_data_types(self, ds): ''' Checks the data type of all netCDF variables to ensure they are valid data types under CF. CF §2.2 The netCDF data types char, byte, short, int, float or real, and double are all acceptable :param netCDF4.Dataset ds: An open netCDF da...
python
def reset(self): """ Resets the player and discards loaded data. """ self.clip = None self.loaded_file = None self.fps = None self.duration = None self.status = UNINITIALIZED self.clock.reset() self.loop_count = 0
java
public void marshall(DeleteRoomSkillParameterRequest deleteRoomSkillParameterRequest, ProtocolMarshaller protocolMarshaller) { if (deleteRoomSkillParameterRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarsha...
python
def _init_from_dictionary(self, from_dictionary, template_model=None): """ Private helper to init values from a dictionary, wraps children into AttributeFilter objects :param from_dictionary: dictionary to get attribute names and visibility from :type from_dictionary: dict ...
java
@Override public boolean acceptsURL(String url) throws SQLException { if(url.startsWith(sqldroidPrefix) || url.startsWith(xerialPrefix)) { return true; } return false; }
java
protected void moveNode(TreeNode node, double dx, double dy) { node.x += dx; node.y += dy; apply(node, null); TreeNode child = node.child; while (child != null) { moveNode(child, dx, dy); child = child.next; } }
python
def get_item2(self, tablename, key, attributes=None, alias=None, consistent=False, return_capacity=None): """ Fetch a single item from a table Parameters ---------- tablename : str Name of the table to fetch from key : dict Prima...
java
@SuppressWarnings("unchecked") public static Object getRng(Object subject, int index) { if (subject instanceof VDMMap) { VDMMap map = (VDMMap) subject; VDMSeq seq = SeqUtil.seq(); seq.addAll(map.values()); return seq.get(index); } throw new IllegalArgumentException("Method is only supported for...
java
private static String formatSimple(ChannelHandlerContext ctx, String eventName, Object msg) { String chStr = ctx.channel().toString(); String msgStr = String.valueOf(msg); StringBuilder buf = new StringBuilder(chStr.length() + 1 + eventName.length() + 2 + msgStr.length()); return buf.app...
java
@Indexable(type = IndexableType.REINDEX) @Override public CPDefinition moveCPDefinitionToTrash( long userId, CPDefinition cpDefinition) throws PortalException { // Commerce product definition if (cpDefinition.isInTrash()) { throw new TrashEntryException(); } int oldStatus = cpDefinition.getStatus()...
java
public java.util.List<String> getEC2InstanceIdsToTerminate() { if (eC2InstanceIdsToTerminate == null) { eC2InstanceIdsToTerminate = new com.amazonaws.internal.SdkInternalList<String>(); } return eC2InstanceIdsToTerminate; }
python
def load_iris(): """Iris Dataset.""" dataset = datasets.load_iris() return Dataset(load_iris.__doc__, dataset.data, dataset.target, accuracy_score, stratify=True)
java
public boolean destinationMatches(DestinationHandler destinationHandlerToCompare, JSConsumerManager consumerDispatcher) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "destinationMatches", new Object[] {destinationHandlerToCompare, cons...
python
def internal_classpath(cls, targets, classpath_products, confs=('default',)): """Return the list of internal classpath entries for a classpath covering all `targets`. Any classpath entries contributed by external dependencies will be omitted. :param targets: Targets to build an aggregated classpath for. ...
java
@Override public ReisMogelijkheden getModel(InputStream stream) { SimpleDateFormat format = new SimpleDateFormat(NsApi.DATETIME_FORMAT); try { Xml xml = Xml.getXml(stream, "ReisMogelijkheden"); List<ReisMogelijkheid> reisMogelijkheden = new ArrayList<>(xml.children("Reis...
java
public static String formatLatitude(double latitude, UnitType unit) { return formatLatitude(Locale.getDefault(), latitude, unit); }
python
def _validate_token(self): ''' a method to validate active access token ''' title = '%s._validate_token' % self.__class__.__name__ # construct access token url import requests url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % self.access_...
python
def extract_irc_colours(msg): """Extract the IRC colours from the start of the string. Extracts the colours from the start, and returns the colour code in our format, and then the rest of the message. """ # first colour fore, msg = _extract_irc_colour_code(msg) if not fore: return ...
java
public double getCovariance() { if(covariance == null) { Observation o = new Observation(); for(int i=0; i<observationA.getObservationCount(); i++) o.addValue(observationA.getValueAt(i)*observationB.getValueAt(i)); covariance = o.getExpectation()-observationA.getExpectation()*observationB.getExpecta...
python
def create_entry(i): """ Input: { path - path where to create an entry (data_uoa) - data UOA (data_uid) - if uoa is an alias, we can force data UID (force) - if 'yes', force creation even if directory already exists } Output: { ...