language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void setAttributes(Map<String, Attribute> attributes) { if (null == attributes) { throw new IllegalArgumentException("Attributes should be not-null."); } this.attributes = attributes; this.attributesLoaded = true; }
python
def listen(self, name=None): """A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as :func:`.on_ready` The functions being listened to must be a coroutine. Example ...
java
public static void copyThread(Reader in, Writer out) { try { instance().run(new Job(in,out)); } catch(InterruptedException e) { log.warn(LogSupport.EXCEPTION,e); } }
python
def get_filter_config(platform, filter_name, filter_options=None, terms=None, prepend=True, pillar_key='acl', pillarenv=None, saltenv=None, merg...
java
public Response.ResponseBuilder getTimeMapBuilder(final LdpRequest req, final IOService serializer, final String baseUrl) { final List<MediaType> acceptableTypes = req.getHeaders().getAcceptableMediaTypes(); final String identifier = getBaseUrl(baseUrl, req) + req.getPartition() + req.getPa...
java
protected String createProcessCommand(String commandArguments) { //create command StringBuilder buffer=new StringBuilder(500); buffer.append("\""); buffer.append(this.fax4jExecutableFileLocation); buffer.append("\""); buffer.append(Fax4jExeConstants.SPACE_STR); ...
python
def open(self, section_index=0): """Launch a help section.""" uri = self._sections[section_index][1] if len(uri.split()) == 1: self._open_url(uri) else: if self._verbose: print "running command: %s" % uri p = popen(uri, shell=True) ...
python
def update_chat_username( self, chat_id: Union[int, str], username: Union[str, None] ) -> bool: """Use this method to update a channel or a supergroup username. To update your own username (for users only, not bots) you can use :meth:`update_username`. Args:...
python
def altitude_difference(self, pressure1, pressure2, ground_temp): '''calculate barometric altitude''' scaling = pressure2 / pressure1 temp = ground_temp + 273.15 return 153.8462 * temp * (1.0 - math.exp(0.190259 * math.log(scaling)))
java
@NonNull public Expression collate(@NonNull Collation collation) { if (collation == null) { throw new IllegalArgumentException("collation cannot be null."); } return new CollationExpression(this, collation); }
java
public void marshall(ThingTypeDefinition thingTypeDefinition, ProtocolMarshaller protocolMarshaller) { if (thingTypeDefinition == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(thingTypeDefinition.ge...
python
def _get_indexes(self, schema, **kwargs): """return all the indexes for the given schema""" ret = {} query_str = [] query_str.append('SELECT') query_str.append(' tbl.relname AS table_name, i.relname AS index_name, a.attname AS field_name,') query_str.append(' ix.indkey ...
java
@Override public DescribeFleetAttributesResult describeFleetAttributes(DescribeFleetAttributesRequest request) { request = beforeClientExecution(request); return executeDescribeFleetAttributes(request); }
python
def roc_values(fg_vals, bg_vals): """ Return fpr (x) and tpr (y) of the ROC curve. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. Returns ------- fpr : array ...
java
private static void writeParam(Object v, DataOutput writer) throws IOException { if (v instanceof Byte) { writer.write(BYTE_ID); writer.writeByte(((Byte) v).byteValue()); } else if (v instanceof Short) { writer.write(SHORT_ID); writer.writeShort(((Short) v).shortValue()); } else if (v instanceof Integ...
java
@InterfaceAudience.Public public void setUserProperties(Map<String, Object> userProperties) { Map<String, Object> newProps = new HashMap<String, Object>(); newProps.putAll(userProperties); for (String key : properties.keySet()) { if (key.startsWith("_")) { newProp...
java
public void createPassword(PersonForm form, String token) { final String username = form.getUsername(); // Re-validate the token to prevent URL hacking if (!validateLoginToken(username, token)) { throw new RuntimeException( "Attempt to set a password for user '"...
python
def add_reference(self, subj: Node, val: str) -> None: """ Add a fhir:link and RDF type arc if it can be determined :param subj: reference subject :param val: reference value """ match = FHIR_RESOURCE_RE.match(val) ref_uri_str = res_type = None if match: ...
java
@Override public List<CommerceOrder> findByG_C(long groupId, long commerceAccountId, int start, int end, OrderByComparator<CommerceOrder> orderByComparator) { return findByG_C(groupId, commerceAccountId, start, end, orderByComparator, true); }
python
def get_name(self, key): '''Return a name for the given key Argument: key -- Pokemon number id (int) ''' try: return self.nameDict[key] except IndexError as e: print 'IndexError {0}: {1}'.format(e.errno, e.strerror)
python
def has_scope(context=None): ''' Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205. ''' if not booted(context): return False _sd_version = version(context) if _sd_version is None: re...
java
public GraphHopper setDataReaderFile(String dataReaderFileStr) { ensureNotLoaded(); if (isEmpty(dataReaderFileStr)) throw new IllegalArgumentException("Data reader file cannot be empty."); dataReaderFile = dataReaderFileStr; return this; }
python
def to_array(self): """ Serializes this PhotoSize to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PhotoSize, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str array[...
java
public static boolean compare(final String me, final String you) { // If both null or intern equals if (me == you) return true; // if me null and you are not if (me == null && you != null) return false; // me will not be null, test for equality return me.equals...
python
def _handle_paper(article): """ Yields a :class:`.Paper` from an article ET node. Parameters ---------- article : Element ElementTree Element 'article'. Returns ------- paper : :class:`.Paper` """ paper = Paper() pdata = dict_from_node(article) for key, value i...
python
def _get_classpath(self, workunit_factory): """Returns the bootstrapped ivy classpath as a list of jar paths. :raises: Bootstrapper.Error if the classpath could not be bootstrapped """ if not self._classpath: self._classpath = self._bootstrap_ivy_classpath(workunit_factory) return self._class...
java
@Override public void getPlaceTrends(final int woeid) { getDispatcher().invokeLater(new AsyncTask(PLACE_TRENDS, listeners) { @Override public void invoke(List<TwitterListener> listeners) throws TwitterException { Trends trends = twitter.getPlaceTrends(woeid); ...
python
def is_almost_simplicial(G, n): """Determines whether a node n in G is almost simplicial. Parameters ---------- G : NetworkX graph The graph on which to check whether node n is almost simplicial. n : node A node in graph G. Returns ------- is_almost_simplicial : bool ...
python
def search_packages_info(query): """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ installed = {} for p in pkg_re...
python
def calc_qma_v1(self): """Calculate the discharge responses of the different MA processes. Required derived parameters: |Nmb| |MA_Order| |MA_Coefs| Required log sequence: |LogIn| Calculated flux sequence: |QMA| Examples: Assume there are three response func...
python
def features_from_image( self, data, voxelsize, seeds=None, unique_cls=None ): # , voxels=None): """ Input data is 3d image :param data: is 3d image :param seeds: ndimage with same shape as data, nonzero values means seeds. :param unique_cls: can select only fv for ...
python
def polfit_residuals_with_sigma_rejection( x, y, deg, times_sigma_reject, color='b', size=75, xlim=None, ylim=None, xlabel=None, ylabel=None, title=None, use_r=None, geometry=(0,0,640,480), debugplot=0): """Polynomial fit with iterative rejection of points. ...
python
def fromdb(dbo, query, *args, **kwargs): """Provides access to data from any DB-API 2.0 connection via a given query. E.g., using :mod:`sqlite3`:: >>> import petl as etl >>> import sqlite3 >>> connection = sqlite3.connect('example.db') >>> table = etl.fromdb(connection, 'SELECT ...
python
def _setup_ipc(self): ''' Setup the IPC PUB and SUB sockets for the proxy. ''' log.debug('Setting up the internal IPC proxy') self.ctx = zmq.Context() # Frontend self.sub = self.ctx.socket(zmq.SUB) self.sub.bind(PUB_PX_IPC_URL) self.sub.setsockopt(...
java
public static DateTimePatternGenerator getEmptyInstance() { DateTimePatternGenerator instance = new DateTimePatternGenerator(); instance.addCanonicalItems(); instance.fillInMissing(); return instance; }
python
def _atexit__register(self, func, *targs, **kwargs): """ Intercept :func:`atexit.register` calls, diverting any to :func:`shutil.rmtree` into a private list. """ if func == shutil.rmtree: self.deferred.append((func, targs, kwargs)) return self.ori...
python
def assuncao_rate(e, b): """The standardized rates where the mean and stadard deviation used for the standardization are those of Empirical Bayes rate estimates The standardized rates resulting from this function are used to compute Moran's I corrected for rate variables [Choynowski1959]_ . Paramet...
java
private boolean isJavaProperty(String token) { String opt = token.substring(0, 1); Option option = options.getOption(opt); return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES); }
java
public void start() throws Exception { if(log.isInfoEnabled()) { log.info("Starting Zabbix agent."); } if(enablePassive) { if(log.isInfoEnabled()) { log.info("Starting passive listener."); } if(listenAddress == null) { listenerThrea...
java
@SuppressWarnings("unchecked") public List<Failure> validate(Validate vo, ResourceBundle rb) { if (vo != null && Key.MANAGED_CONNECTION == vo.getKey()) { if (!ManagedConnection.class.isAssignableFrom(vo.getClazz())) { List<Failure> failures = new ArrayList<Failure>(1); ...
python
def read(mfile, sfile): """ Returns an IadhoreData object, constructed from the passed i-ADHoRe multiplicon and segments output. - mfile (str), location of multiplicons.txt - sfile (str), location of segments.txt """ assert os.path.isfile(mfile), "%s multiplicon file does not exist"...
java
public static <T> List<T> load(GVRContext gvrContext, String zipFileName, ZipEntryProcessor<T> processor) throws IOException { Context context = gvrContext.getContext(); InputStream inputStream = context.getAssets().open(zipFileName); ZipInputStream zipInputStream = new ZipInputStrea...
java
private OptionElement readOption(char keyValueSeparator) { boolean isExtension = (peekChar() == '['); boolean isParenthesized = (peekChar() == '('); String name = readName(); // Option name. if (isExtension) { name = "[" + name + "]"; } String subName = null; char c = readChar(); i...
python
def initialize(self,num_reals=1,init_lambda=None,enforce_bounds="reset", parensemble=None,obsensemble=None,restart_obsensemble=None, regul_factor=0.0,use_approx_prior=True,build_empirical_prior=False): """Initialize the iES process. Depending on arguments, draws or loads ...
python
def store_directory(ctx, param, value): """Store directory as a new Git home.""" Path(value).mkdir(parents=True, exist_ok=True) set_git_home(value) return value
java
public EClass getIfcTopologicalRepresentationItem() { if (ifcTopologicalRepresentationItemEClass == null) { ifcTopologicalRepresentationItemEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(617); } return ifcTopologicalRepresentationItemEClass; ...
python
def _execute_config_show(self, show_command, delay_factor=.1): """ Executes a configuration show-type command. """ rpc_command = '<CLI><Configuration>{show_command}</Configuration></CLI>'.format( show_command=escape_xml(show_command) ) response = self._execute...
python
def set_alarm_mode(self, mode): """ :param mode: one of [None, "activity", "tamper", "forced_entry"] :return: nothing """ values = {"desired_state": {"alarm_mode": mode}} response = self.api_interface.set_device_state(self, values) self._update_state_from_r...
java
@Override public LexemeDocument withStatement(Statement statement) { Map<String, List<Statement>> newGroups = addStatementToGroups(statement, claims); return new LexemeDocumentImpl(getEntityId(), lexicalCategory, language, lemmas, newGroups, forms, revisionId); }
python
def get_timeout(service): """ Returns either a custom timeout for the given service, or a default """ custom_timeout_key = "RESTCLIENTS_%s_TIMEOUT" % service.upper() if hasattr(settings, custom_timeout_key): return getattr(settings, custom_timeout_key) default_key = "RESTCLIENTS_DEFAULT_TIM...
python
def _get_station_file(path_name, station, channel, debug=0): """ Helper function to find the correct file. :type path_name: str :param path_name: Path to files to check. :type station: str :type channel: str :returns: list of filenames, str """ wavfiles = glob.glob(path_name + os.s...
java
@Override public CommerceUserSegmentEntry remove(Serializable primaryKey) throws NoSuchUserSegmentEntryException { Session session = null; try { session = openSession(); CommerceUserSegmentEntry commerceUserSegmentEntry = (CommerceUserSegmentEntry)session.get(CommerceUserSegmentEntryImpl.class, prim...
java
public com.google.privacy.dlp.v2.BigQueryKeyOrBuilder getBigQueryKeyOrBuilder() { if (typeCase_ == 3) { return (com.google.privacy.dlp.v2.BigQueryKey) type_; } return com.google.privacy.dlp.v2.BigQueryKey.getDefaultInstance(); }
java
@Override public void setReadyToFlush() throws IOException { doubleBuf.getCurrentBuf().write(FSEditLogOpCodes.OP_INVALID.getOpCode()); // insert eof marker doubleBuf.setReadyToFlush(); }
java
public static String getTinyMceBlockFormats(String formatSelectOptions) { String[] options = formatSelectOptions.split(";"); List<String> resultParts = Lists.newArrayList(); for (String option : options) { String label = TINYMCE_DEFAULT_BLOCK_FORMAT_LABELS.get(option); i...
python
def install_versioning(self, conn): """ Create the version table into an already populated database and insert the base script. :param conn: a DB API 2 connection """ logging.info('Creating the versioning table %s', self.version_table) conn.executescript(CREATE_V...
python
def apply_constraints(phash, size, nonalphanumeric): """ Fiddle with the password a bit after hashing it so that it will get through most website filters. We require one upper and lower case, one digit, and we look at the user's password to determine if there should be at least one alphanumeric or n...
java
public List<T> values(final int state) { final List<T> list = sharedList.stream().filter(e -> e.getState() == state).collect(Collectors.toList()); Collections.reverse(list); return list; }
java
private final Object parseValue( Field fieldContext, Type valueType, ArrayList<Type> context, Object destination, CustomizeJsonParser customizeParser, boolean handlePolymorphic) throws IOException { valueType = Data.resolveWildcardTypeOrTypeVariable(context, valueType); ...
python
def _find_matching_collections_internally(collections, record): """Find matching collections with internal engine. :param collections: set of collections where search :param record: record to match """ for name, data in iteritems(collections): if _build_query(data['query']).match(record): ...
python
def fit(self, order=3): """ Overriden since this eos works with volume**(2/3) instead of volume. """ x = self.volumes**(-2./3.) self.eos_params = np.polyfit(x, self.energies, order) self._set_params()
java
public static int pid() { int localPID = 0; try { String name = ManagementFactory.getRuntimeMXBean().getName(); String[] nameSplit = name.split("@"); if(nameSplit.length > 1) { localPID = Integer.parseInt(nameSplit[0]); } return...
java
private JSlider getSliderHostPerScan() { if (sliderHostPerScan == null) { sliderHostPerScan = new JSlider(); sliderHostPerScan.setMaximum(5); sliderHostPerScan.setMinimum(1); sliderHostPerScan.setMinorTickSpacing(1); sliderHostPerScan.setPaintTic...
python
def list(self, device_sid=values.unset, limit=None, page_size=None): """ Lists KeyInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param unicode device_sid: Find all Keys authenticating...
java
public static TopologyAPI.Config.Builder getConfigBuilder(Config config) { TopologyAPI.Config.Builder cBldr = TopologyAPI.Config.newBuilder(); Set<String> apiVars = config.getApiVars(); for (String key : config.keySet()) { if (key == null) { LOG.warning("ignore: null config key found"); ...
java
static Secret tryDecrypt(Cipher cipher, byte[] in) { try { String plainText = new String(cipher.doFinal(in), UTF_8); if(plainText.endsWith(MAGIC)) return new Secret(plainText.substring(0,plainText.length()-MAGIC.length())); return null; } catch (Genera...
python
def execute(self, timeSeries): """Creates a new TimeSeries containing the smoothed values. :return: TimeSeries object containing the smoothed TimeSeries, including the forecasted values. :rtype: TimeSeries :note: The first normalized value is chosen as the starting p...
python
def runner( engine, configfile, output_vars, interval, pause, mpi, tracker, port, bmi_class ): """ run a BMI compatible model """ # keep track of info # update mpi information or use rank 0 runner = mmi.runner.Runner( ...
python
async def controller(self): """Return a Connection to the controller at self.endpoint """ return await Connection.connect( self.endpoint, username=self.username, password=self.password, cacert=self.cacert, bakery_client=self.bakery_clie...
python
def recv(self, timeout=None): """Receive a handover select message from the remote server.""" message = self._recv(timeout) if message and message.type == "urn:nfc:wkt:Hs": log.debug("received '{0}' message".format(message.type)) return nfc.ndef.HandoverSelectMessage(mess...
java
public ConverterServerBuilder baseUri(String baseUri) { checkNotNull(baseUri); this.baseUri = URI.create(baseUri); return this; }
python
def related_element_type(self): """ .. versionadded:: 0.6.0 Requires SMC version >= 6.4 Related element type defines the 'type' of element at this routing or antispoofing node level. :rtype: str """ if 'related_element_type' in se...
python
def get_user_id(username): """ Returns the user id to a given user name. Returns ``None`` if the user does not exist. :param username: User name. :type username: unicode :return: User id. :rtype: int """ uid = single_line_stdout('id -u {0}'.format(username), expected_errors=(1,), shell=...
java
public static Channel intercept(Channel channel, ClientInterceptor... interceptors) { return intercept(channel, Arrays.asList(interceptors)); }
java
@SuppressWarnings("unchecked") // keytype from conf not static public void configure(JobConf job) { try { String parts = getPartitionFile(job); final Path partFile = new Path(parts); final FileSystem fs = (DEFAULT_PATH.equals(parts)) ? FileSystem.getLocal(job) // assume in Distribute...
python
def _page(q, chunk=1000): """ Quick utility to page a query, 1000 items at a time. We need this so we don't OOM (out of memory) ourselves loading the world. """ offset = 0 while True: r = False for elem in q.limit(chunk).offset(offset): r = True yield elem ...
java
private void put(String name, BeanDefine beanDefine) { if (pool.put(name, beanDefine) != null) { log.warn("Duplicated Bean: {}", name); } }
java
public void setTickMarkSections(final List<Section> SECTIONS) { tickMarkSections.setAll(SECTIONS); Collections.sort(tickMarkSections, new SectionComparator()); fireUpdateEvent(REDRAW_EVENT); }
java
public static PhoneNumber get(final BandwidthClient client, final String phoneNumberId) throws Exception { assert(client != null && phoneNumberId != null); final String phoneNumberUri = client.getUserResourceInstanceUri(BandwidthConstants.PHONE_NUMBER_URI_PATH, phoneNumberId); final JSONObject p...
java
public void addChild(Config child) { Params.notNull(child, "Child"); child.parent = this; children.add(child); }
python
def _prep_components(component_list: Sequence[str]) -> List[Tuple[str, Tuple[str]]]: """Transform component description strings into tuples of component paths and required arguments. Parameters ---------- component_list : The component descriptions to transform. Returns ------- Lis...
python
def from_config(cls, config, prefix="postmark_", is_uppercase=False): """ Helper method for instantiating PostmarkClient from dict-like objects. """ kwargs = {} for arg in get_args(cls): key = prefix + arg if is_uppercase: key = key.upper()...
python
def volume_up(self, delta=0.1): """ Increment volume by 0.1 (or delta) unless it is already maxed. Returns the new volume. """ if delta <= 0: raise ValueError( "volume delta must be greater than zero, not {}".format(delta)) return self.set_volume(self...
python
def handle_feedback(self, pkt): """This part of the protocol is used by IRAF to erase a frame in the framebuffers. """ self.logger.debug("handle feedback") self.frame = self.decode_frameno(pkt.z & 0o7777) - 1 # erase the frame buffer self.server.controller.init_f...
java
@Override public XBELDocument unmarshal(Source s) throws JAXBException, IOException { final Unmarshaller unmarshaller = createNewUnmashaller(); return (XBELDocument) unmarshaller.unmarshal(s); }
python
def get_endpoint_by_address(self, endpoint_addr): """ Get an endpoint by address """ url = "/notification/v1/endpoint?endpoint_address={}".format( endpoint_addr) response = NWS_DAO().getURL(url, self._read_headers) if response.status != 200: rais...
python
def symbol(self, symbol_str, country_code=None): """Lookup an Equity by its ticker symbol. Parameters ---------- symbol_str : str The ticker symbol for the equity to lookup. country_code : str or None, optional A country to limit symbol searches to. ...
python
def _do_setup(self): """Setup basic parameters for this class. `base` is the numeric base which when raised to `power` is equivalent to 1 unit of the corresponding prefix. I.e., base=2, power=10 represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte. Likewise, for the SI prefix classes `base` will be...
python
def request_id(self, request_id): """ Sets the request_id of this ErrorResponse. Request ID. :param request_id: The request_id of this ErrorResponse. :type: str """ if request_id is not None and not re.search('^[A-Za-z0-9]{32}', request_id): raise Val...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.IDD__UNITBASE: return UNITBASE_EDEFAULT == null ? unitbase != null : !UNITBASE_EDEFAULT.equals(unitbase); case AfplibPackage.IDD__XRESOL: return XRESOL_EDEFAULT == null ? xresol != null : !XRESOL_EDEFAULT.equals(xr...
java
public EnvironmentImage withVersions(String... versions) { if (this.versions == null) { setVersions(new java.util.ArrayList<String>(versions.length)); } for (String ele : versions) { this.versions.add(ele); } return this; }
java
private GVRSceneObject loadJassimpModel(AssetRequest request, final GVRSceneObject model) throws IOException { Jassimp.setWrapperProvider(GVRJassimpAdapter.sWrapperProvider); org.gearvrf.jassimp.AiScene assimpScene = null; String filePath = request.getBaseName(); GVRJassimpAdapter ja...
java
protected Map<String, ZipEntry> getEntries(ZipFile zf) { Enumeration<?> e = zf.entries(); Map<String, ZipEntry> m = new HashMap<String, ZipEntry>(); while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); m.put(ze.getName(), ze); } return m...
java
public String[] get_class_attribute_list(String classname, String wildcard) throws DevFailed { return databaseDAO.get_class_attribute_list(this, classname, wildcard); }
python
def create_channel(api_key, api_secret, channel_type='manual', **kwargs): """ Function which creates a new channel. Channels serve as containers of video/media objects. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param channel_type: <string> REQ...
java
public Set<String> keySet() { // prepare container HashSet<String> set = new HashSet<String>(); // add container keys set.addAll(container.keySet()); // add cache keys set.addAll(cache.keySet()); return set; }
java
public static void writeUnsignedIntegerLittleEndian(IO.WritableByteStream io, long value) throws IOException { io.write((byte)(value & 0xFF)); io.write((byte)((value >> 8) & 0xFF)); io.write((byte)((value >> 16) & 0xFF)); io.write((byte)((value >> 24) & 0xFF)); }
java
@Override public List<String> getSynonyms(String word, Language lang) { return getSynonyms(word, getLocale(lang)); }
java
public ResourceRefType<ApplicationType<T>> getOrCreateResourceRef() { List<Node> nodeList = childNode.get("resource-ref"); if (nodeList != null && nodeList.size() > 0) { return new ResourceRefTypeImpl<ApplicationType<T>>(this, "resource-ref", childNode, nodeList.get(0)); } ret...
java
@Override public Boolean readBoolean() { return (buf.get() == AMF.VALUE_TRUE) ? Boolean.TRUE : Boolean.FALSE; }