language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def announcement_posted_hook(request, obj): """Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object """ logger.debug("Announcement posted") if obj.notify_post: logger.debug("Announcement notify on") announcement_posted_twit...
java
public List<PvPLeaderBoard> getPvPSeasonLeaderboardInfo(String id, String type, World.Region region) throws GuildWars2Exception { try { Response<List<PvPLeaderBoard>> response = gw2API.getPvPSeasonLeaderBoardInfo(id, type, region.name().toLowerCase()).execute(); if (!response.isSuccessful()) throwError(response...
python
def get_ligand_ring_selection(self,ring): """MDAnalysis atom selections of aromatic rings present in the ligand molecule. Takes: * ring * - index in self.ligrings dictionary Output: * ring_selection * - MDAnalysis Atom group""" ring_names = "" for atom in ...
java
public Map<String,Object> getProperties() { Map<String,Object> properties = ((PropertiesField)this.getField(CalendarEntry.PROPERTIES)).getProperties(); if (!this.getField(Anniversary.ANNIV_MASTER_ID).isNull()) if (this.getField(Anniversary.ANNIV_MASTER_ID) instanceof ReferenceField) ...
java
@Nonnull public static List<PluginWrapper.Dependency> getImpliedDependencies(String pluginName, String jenkinsVersion) { List<PluginWrapper.Dependency> out = new ArrayList<>(); for (DetachedPlugin detached : getDetachedPlugins()) { // don't fix the dependency for itself, or else we'll ha...
java
@NotNull @Override public ExternalSetQueryContext<E, ?> queryContext(E key) { //noinspection unchecked return (ExternalSetQueryContext<E, ?>) m.queryContext(key); }
python
def _get_path_by_name(part, paths): """ Given a command part, find the path it represents. :throws ValueError: if no valid file is found. """ for path in paths: if path.alias == part: return path raise ValueError
java
protected double distance(DBIDRef a, DBIDRef b) { ++distComputations; return distanceQuery.distance(a, b); }
python
def sign(check_request): """Obtains a signature for an operation in a `CheckRequest` Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `CheckRequest` Returns: string: a secure hash generated from the operation """ if no...
java
public void setEnabled(boolean bEnable) { super.setEnabled(bEnable); if (m_recordReference != null) { Record recReference = this.getReferenceRecord(); for (int iIndex = 0 + 1; iIndex < recReference.getKeyAreaCount(); iIndex++) { KeyArea key...
java
public static boolean promoteAndCheckResponse(Promotion promotion, ArtifactoryBuildInfoClient client, TaskListener listener, String buildName, String buildNumber) throws IOException { // If failFast is true, perform dry run first if (promotion.isFailFast...
java
public void setASpace(Integer newASpace) { Integer oldASpace = aSpace; aSpace = newASpace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FNIRG__ASPACE, oldASpace, aSpace)); }
python
def enqueue(self, destination): """Enqueues given destination for processing. Given instance should be a valid destination. """ if not destination: raise BgpProcessorError('Invalid destination %s.' % destination) dest_queue = self._dest_queue # RtDest are qu...
java
@Override public void onReceive(Object message) throws Exception { try { if (message instanceof RequestWorkerMsgType) { switch ((RequestWorkerMsgType) message) { case PROCESS_REQUEST: tryCount++; if (tryCount == 1) { ...
java
public java.util.List<String> getChildHealthChecks() { if (childHealthChecks == null) { childHealthChecks = new com.amazonaws.internal.SdkInternalList<String>(); } return childHealthChecks; }
python
def pop_column(self, index=-1): """Remove and return row at index (default last). Parameters ---------- index : int, str index of the column, or the header of the column. If index is specified, then normal list rules apply. Raises ------ ...
python
def extract_client_auth(request): """ Get client credentials using HTTP Basic Authentication method. Or try getting parameters via POST. See: http://tools.ietf.org/html/rfc6750#section-2.1 Return a tuple `(client_id, client_secret)`. """ auth_header = request.META.get('HTTP_AUTHORIZATION', ...
java
public Observable<DetectorResponseInner> getSiteDetectorResponseSlotAsync(String resourceGroupName, String siteName, String detectorName, String slot, DateTime startTime, DateTime endTime, String timeGrain) { return getSiteDetectorResponseSlotWithServiceResponseAsync(resourceGroupName, siteName, detectorName, s...
java
public static String replaceBadChars(String string) { return string.replace(' ', '_').replace(',', '_').replace('.', '_') .replace('-', '_').trim().replace("\n", "").replace("?", "Int").replace("!", "Exc").replace("ñ", "gn"); }
python
def walk(fn, obj, *args, **kwargs): """Recursively walk an object graph applying `fn`/`args` to objects.""" if type(obj) in [list, tuple]: return list(walk(fn, o, *args) for o in obj) if type(obj) is dict: return dict((walk(fn, k, *args), walk(fn, v, *args)) for k, v in o...
java
@Override public void error(Throwable t) { log.log(Level.SEVERE, t.getMessage(), t); }
java
public static boolean cleanEmpty(File directory) throws IORuntimeException { if (directory == null || directory.exists() == false || false == directory.isDirectory()) { return true; } final File[] files = directory.listFiles(); if(ArrayUtil.isEmpty(files)) { //空文件夹则删除之 directory.delete(); }...
python
def generate_static(self, path): """ This method generates a valid path to the public folder of the running project """ if not path: return "" if path[0] == '/': return "%s?v=%s" % (path, self.version) return "%s/%s?v=%s" % (self.static, path, se...
java
public DataPoint set(DataPoint another) { if (type == Type.NONE) { _cloneFrom(another); } else { if (another.type != Type.NONE) { set(another.value()); } } return this; }
java
public static void filterWalkableLowHeightSpans(Context ctx, int walkableHeight, Heightfield solid) { ctx.startTimer("FILTER_WALKABLE"); int w = solid.width; int h = solid.height; int MAX_HEIGHT = 0xffff; // Remove walkable flag from spans which do not have enough // sp...
java
public Comparator<S> comparator() { if (mChunkMatcher == null) { return mChunkSorter; } return new Comparator<S>() { public int compare(S a, S b) { int result = mChunkMatcher.compare(a, b); if (result == 0) { res...
python
def get_throttled_by_consumed_write_percent( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled write events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookb...
python
def set_flowcontrol_receive(self, name, value=None, default=False, disable=False): """Configures the interface flowcontrol receive value Args: name (string): The interface identifier. It must be a full interface name (ie Ethernet, not Et) ...
java
@Deprecated public void setTokenFromCache(String accessToken, long accessExpires, long lastAccessUpdate) { checkUserSession("setTokenFromCache"); synchronized (this.lock) { this.accessToken = accessToken; accessExpiresMillisecondsAfterEpoch = accessExpires; lastAc...
python
def keyring_refresh(**kwargs): """ Refresh the keyring in the cocaine-runtime. """ ctx = Context(**kwargs) ctx.execute_action('keyring:refresh', **{ 'tvm': ctx.repo.create_secure_service('tvm'), })
java
protected void defineFilter(Context ctx, String name, String classname, Map<String,String> parameters, String[] urls) { FilterHolder holder = new FilterHolder(); holder.setName(name); holder.setClassName(classname); holder.setInitParameters(parameters); FilterMapping fmap = new FilterMapping(...
java
public static Query toQuery(Object o, Query defaultValue) { if (o instanceof Query) return (Query) o; else if (o instanceof ObjectWrap) { return toQuery(((ObjectWrap) o).getEmbededObject(defaultValue), defaultValue); } return defaultValue; }
java
public static int getTriplet(NucleotideSequence nSequence, int tripletStart) { int triplet = (nSequence.codeAt(tripletStart) << 4) | (nSequence.codeAt(tripletStart + 1) << 2) | nSequence.codeAt(tripletStart + 2); return triplet; }
java
public synchronized void openDriver(SurfaceHolder holder) throws IOException { OpenCamera theCamera = camera; if (theCamera == null) { theCamera = OpenCameraInterface.open(requestedCameraId); if (theCamera == null) { throw new IOException("Camera.open() failed to return object from driver");...
python
def get_build_status(req_id, nodename): ''' get the build status from CLC to make sure we dont return to early ''' counter = 0 req_id = six.text_type(req_id) while counter < 10: queue = clc.v1.Blueprint.GetStatus(request_id=(req_id)) if queue["PercentComplete"] == 100: ...
java
public void dumpOut(){ System.out.println(this.toString()); TraceStep root = getRootStep(); dumpOut(root, 1); }
java
@Override public BrownianMotionInterface getCloneWithModifiedSeed(int seed) { return new BrownianBridge(timeDiscretization, numberOfPaths, seed, start, end); }
java
public String getMap(String word){ if(nameMap==null||!nameMap.containsKey(word)) return word; else return nameMap.get(word); }
java
public void setClaimedVictim() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(this, tc, "marking this mc as _claimedVictim"); _claimedVictim = true; }
python
def load_data(self, data, **kwargs): """ Bulk adds rdf data to the class args: data: the data to be loaded kwargs: strip_orphans: True or False - remove triples that have an orphan blanknode as the object obj_method: "list"...
java
public static byte[] encrypt(byte[] data, byte[] key) throws Exception{ //恢复密钥 SecretKey secretKey = new SecretKeySpec(key, "AES"); //Cipher完成加密 Cipher cipher = Cipher.getInstance("AES"); //根据密钥对cipher进行初始化 cipher.init(Cipher.ENCRYPT_MODE, secretKey); //加密 byte[] encrypt = cipher.doFinal(data); ret...
java
public void setOutputs(java.util.Collection<Output> outputs) { if (outputs == null) { this.outputs = null; return; } this.outputs = new java.util.ArrayList<Output>(outputs); }
python
def _deserialize(data, klass): """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ if data is None: return None if klass in six.integer_types or klass in (float, str, bool): ...
python
def set_copyright(self, copyright_): """Sets the copyright. arg: copyright (string): the new copyright raise: InvalidArgument - ``copyright`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``copyright`` is ``null`` *complia...
python
def _evaluate(self,*args,**kwargs): """ NAME: __call__ (_evaluate) PURPOSE: evaluate the actions (jr,lz,jz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single object (phi is optional) (each can be ...
python
def store_sample_set(self, md5_list): """ Store a sample set (which is just a list of md5s). Note: All md5s must already be in the data store. Args: md5_list: a list of the md5s in this set (all must exist in data store) Returns: The md5 of ...
python
def run(self): '''Run until there are no events to be processed.''' # We left-append rather than emit (right-append) because some message # may have been already queued for execution before the director runs. global_event_queue.appendleft((INITIATE, self, (), {})) while global_ev...
python
def install_caller_instruction(self, token_type="Unrestricted", transaction_id=None): """ Set us up as a caller This will install a new caller_token into the FPS section. This should really only be called to regenerate the caller token. """ ...
java
public static StructuredType getAndCheckStructuredType(EntityDataModel entityDataModel, Class<?> javaType) { return checkIsStructuredType(getAndCheckType(entityDataModel, javaType)); }
python
def _convert_many_to_one(self, col_name, label, description, lst_validators, filter_rel_fields, form_props): """ Creates a WTForm field for many to one related fields, will use a Select box based on a query. Will only ...
java
public static String compactDecimal(final Number value, final Locale locale) { return compactDecimal(value, CompactStyle.SHORT, locale); }
python
def stationary_distribution(T): r"""Compute stationary distribution of stochastic matrix T. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix Returns ------- mu : (M,) ndarray Vector of stationary probabilities. Notes ----- The s...
java
@Override public Promise<String> deployVerticle(Verticle verticle) { return adapter.toPromise(handler -> vertx.deployVerticle(verticle, handler)); }
python
def DEFINE_float(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'float'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a float. docstring: A helpful message expl...
python
def ensure_is_date_object(x): """ Ensure input represents a valid date and return the corresponding `datetime.date` object. Valid inputs: - string of the form "YYYY-MM-DD" - dt.date object - pd.Timestamp of the form "YYYY-MM-DD 00:00:00" with freq='D' (as is generated by pd.date_range())...
python
def find_by_fields(self, table, queryset={}): ''' 从数据库里查询 符合多个条件的记录 Args: table: 表名字 str queryset : key 字段 value 值 dict return: 成功: [dict] 保存的记录 失败: -1 并打印返回报错信息 ''' querys = "" for k, v in que...
java
protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException { long result; // lookup sequence name String sequenceName = calculateSequenceName(field); try { result = buildNextSequence(field.getClassDescriptor(), sequenceName); ...
python
def _get_value(self, key, context): """Works out whether key is a value or if it's a variable referencing a value in context and returns the correct value. """ string_quotes = ('"', "'") if key[0] in string_quotes and key[-1] in string_quotes: return key[1:-1] ...
java
@Override public EClass getIfcStructuralCurveReaction() { if (ifcStructuralCurveReactionEClass == null) { ifcStructuralCurveReactionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(637); } return ifcStructuralCurveReactionEClass; }
python
def _get_storage_resource(self): """Gets the SmartStorage resource if exists. :raises: IloCommandNotSupportedError if the resource SmartStorage doesn't exist. :returns the tuple of SmartStorage URI, Headers and settings. """ system = self._get_host_details() ...
java
private final int deserializeAdditionalHeaderSegments (final ByteBuffer pdu, final int offset) throws InternetSCSIException { // parsing Additional Header Segment int off = offset; int ahsLength = basicHeaderSegment.getTotalAHSLength(); while (ahsLength != 0) { final Additio...
python
def save_dependencies(self, instance, schema): """Save data: and list:data: references as parents.""" def add_dependency(value): """Add parent Data dependency.""" try: DataDependency.objects.update_or_create( parent=Data.objects.get(pk=value), ...
python
def change_size_for_active_pane(self, up=0, right=0, down=0, left=0): """ Increase the size of the current pane in any of the four directions. """ child = self.active_pane self.change_size_for_pane(child, up=up, right=right, down=down, left=left)
java
public static void registerOperations(KnowledgeComponentImplementationModel model, Map<String, KnowledgeOperation> operations, KnowledgeOperation defaultOperation) { OperationsModel operationsModel = model.getOperations(); if (operationsModel != null) { for (OperationModel operationModel : o...
python
def fmt(msg, *args, **kw): # type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ global is_tty if len(args) or len(kw): msg = msg.format(*args, **kw) opcode_subst = '\x1b[\\1m' if is_tty else '' return re.sub(r'<(\d{1,2})>', opcode_subst,...
python
def remove_hyperedge(self, hyperedge_id): """Removes a hyperedge and its attributes from the hypergraph. :param hyperedge_id: ID of the hyperedge to be removed. :raises: ValueError -- No such hyperedge exists. Examples: :: >>> H = UndirectedHypergraph() ...
python
def present(name, mediatype, **kwargs): ''' Creates new mediatype. NOTE: This function accepts all standard mediatype properties: keyword argument names differ depending on your zabbix version, see: https://www.zabbix.com/documentation/3.0/manual/api/reference/host/object#host_inventory :param ...
java
public static <T> UnicastAutoReleaseSubject<T> createWithoutNoSubscriptionTimeout(Action0 onUnsubscribe) { State<T> state = new State<T>(onUnsubscribe); return new UnicastAutoReleaseSubject<T>(state); }
java
public SortModel createSortModel(List/*<Sort>*/ sorts) { SortModel sortModel = new SortModel(sorts); sortModel.setSortStrategy(SORT_STRATEGY); return sortModel; }
python
def set_itunes_subtitle(self): """Parses subtitle from itunes tags and sets value""" try: self.itunes_subtitle = self.soup.find('itunes:subtitle').string except AttributeError: self.itunes_subtitle = None
python
def update_forum_votes(sender, **kwargs): """ When a Vote is added, re-saves the topic or post to update vote count. Since Votes can be assigned to any content type, first makes sure we are dealing with a forum post or topic. Deprecated 1-6-14 by storing score as cached property """ ...
java
public static void assertTree(String rootText, String preorder, ParseResults parseResults) { assertTree(rootText, preorder, parseResults.getTree()); }
java
public Collection getReaders(Object obj) { Collection result = null; try { Identity oid = new Identity(obj, getBroker()); byte selector = (byte) 'r'; byte[] requestBarr = buildRequestArray(oid, selector); HttpURLConnection conn = g...
java
@RequestMapping(value = "/api/history/{profileIdentifier}", method = RequestMethod.DELETE) public @ResponseBody HashMap<String, Object> deleteHistory(Model mode, @PathVariable String profileIdentifier, @RequestParam(value = "clientUUID", defaultValue = Constants.PRO...
java
public final synchronized String process(final IoSession session, final String... args) { if (this.message == null) { final StringBuffer strb = new StringBuffer(); // Get all available Commands and get its usage final TcpCommand[] cmds = TcpIpCommands.getCommands().values().toArray(new TcpCommand[]{}); Ar...
python
def savefig(self, output_path, **kwargs): """Save figure during generation. This method is used to save a completed figure during the main function run. It represents a call to ``matplotlib.pyplot.fig.savefig``. # TODO: Switch to kwargs for matplotlib.pyplot.savefig Args: ...
java
protected boolean isProcessable() { // Comparaison des modes boolean correctMode = DAOValidatorHelper.arraryContains(getAnnotationMode(), this.systemDAOMode); // Comparaison des instants d'evaluation boolean correctTime = DAOValidatorHelper.arraryContains(getAnnotationEvaluationTime(), this.systemEv...
java
public T addUniqueKey(final Connection _con, final String _tableName, final String _uniqueKeyName, final String _columns) throws SQLException { final StringBuilder cmd = new StringBuilder(); cmd.append("alter table...
python
def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. """ for line in open(path, 'rt'): if line.startswith('#') and '=' in line: splitted = ...
java
public static double trim(double value) { if (value > MAX_DOUBLE_TO_ROUND || value < -MAX_DOUBLE_TO_ROUND) { return value; } return Math.round(value * ROUND_PRECISION) / ROUND_PRECISION; }
java
public void tstore(String name) throws IOException { TypeMirror cn = getLocalType(name); int index = getLocalVariableIndex(name); if (Typ.isPrimitive(cn)) { tstore(cn, index); } else { astore(index); } }
python
def add_output(self, key, value, variable_type): """Dynamically add output to output_data dictionary to be written to DB later. This method provides an alternative and more dynamic way to create output variables in an App. Instead of storing the output data manually and writing all at once the ...
java
public static String fromNamedReference(CharSequence s) { if (s == null) { return null; } final Integer code = SPECIALS.get(s.toString()); if (code != null) { return "&#" + code + ";"; } return null; }
python
def run_step(context): """Wipe the entire context. Args: Context is a dictionary or dictionary-like. Does not require any specific keys in context. """ logger.debug("started") context.clear() logger.info(f"Context wiped. New context size: {len(context)}") logger.debug("don...
python
def empty(cls: Type[BoardT], *, chess960: bool = False) -> BoardT: """Creates a new empty board. Also see :func:`~chess.Board.clear()`.""" return cls(None, chess960=chess960)
java
static JulianDate create(int prolepticYear, int month, int dayOfMonth) { JulianChronology.YEAR_RANGE.checkValidValue(prolepticYear, YEAR); MONTH_OF_YEAR.checkValidValue(month); DAY_OF_MONTH.checkValidValue(dayOfMonth); if (dayOfMonth > 28) { int dom = 31; switch (...
java
@SuppressWarnings({"cast", "unchecked"}) public static <K, V> EntryWeigher<K, V> entrySingleton() { return (EntryWeigher<K, V>) SingletonEntryWeigher.INSTANCE; }
python
def describe(self, **kwargs): """ Returns descriptive information about this cruddy handler and the methods supported by it. """ response = self._new_response() description = { 'cruddy_version': __version__, 'table_name': self.table_name, ...
python
def mtxm(m1, m2): """ Multiply the transpose of a 3x3 matrix and a 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxm_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of floats :param m2: 3x3 double precision matrix. :type m2: 3x3-Element Arr...
java
private byte[] json(Object object) { try { return mapper.writeValueAsBytes(object); } catch (JsonProcessingException e) { throw new ZendeskException(e.getMessage(), e); } }
python
def process_mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() # if you add processing for an mtype here, remember to add it # to mavlink_packet, above if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']: if (self.num_wps_expected == 0):...
python
def _Close(self): """Closes the file-like object. If the file-like object was passed in the init function the compressed stream file-like object does not control the file-like object and should not actually close it. """ if not self._file_object_set_in_init: self._file_object.close() ...
python
def _convert_number(self, number): """Converts a number to float or int as appropriate""" number = float(number) return int(number) if number.is_integer() else float(number)
python
def create(self): """ Create the directory. """ lib.gp_camera_folder_make_dir( self._cam._cam, self.parent.path.encode(), self.name.encode(), self._cam._ctx)
java
private List<String> getIdList(final List<? extends AuditModel> toDelete) { List<String> ids = new ArrayList<>(toDelete.size()); for (AuditModel auditModel : toDelete) { ids.add(auditModel.getId()); } return ids; }
java
private IQTree updateChild(UnaryIQTree liftedChildTree, ImmutableSubstitution<ImmutableTerm> mergedSubstitution, ImmutableSet<Variable> projectedVariables) { ConstructionNode constructionNode = (ConstructionNode) liftedChildTree.getRootNode(); ConstructionNodeTools.NewSub...
python
def get_anchor_point(self, anchor_name): """Return an anchor point of the node, if it exists.""" if anchor_name in self._possible_anchors: return TikZNodeAnchor(self.handle, anchor_name) else: try: anchor = int(anchor_name.split('_')[1]) excep...
python
def doubleprox_dc_simple(x, y, f, phi, g, K, niter, gamma, mu): """Non-optimized version of ``doubleprox_dc``. This function is intended for debugging. It makes a lot of copies and performs no error checking. """ for _ in range(niter): f.proximal(gamma)(x + gamma * K.adjoint(y) - ...
java
@Override public final Parameters load(final File configFile) throws IOException { final Loading loading = new Loading(); loading.topLoad(configFile); return Parameters.fromMap(loading.ret); }
java
@Override public Resource[] getResources(String pattern) { Resource[] resources = cache.get(pattern); return resources == null ? internalGet(pattern) : resources; }