language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def close_chromium(self):
'''
Close the remote chromium instance.
This command is normally executed as part of the class destructor.
It can be called early without issue, but calling ANY class functions
after the remote chromium instance is shut down will have unknown effects.
Note that if you are rapidly... |
java | public synchronized BloomUpdate getUpdateFlag() {
if (nFlags == 0)
return BloomUpdate.UPDATE_NONE;
else if (nFlags == 1)
return BloomUpdate.UPDATE_ALL;
else if (nFlags == 2)
return BloomUpdate.UPDATE_P2PUBKEY_ONLY;
else
throw new IllegalSta... |
python | def _add_repr(cls, ns=None, attrs=None):
"""
Add a repr method to *cls*.
"""
if attrs is None:
attrs = cls.__attrs_attrs__
cls.__repr__ = _make_repr(attrs, ns)
return cls |
java | public void text(Object o) throws SAXException {
if (o!=null)
output.write(escape(o.toString()));
} |
java | public MockSubnet deleteSubnet(final String subnetId) {
if (subnetId != null && allMockSubnets.containsKey(subnetId)) {
return allMockSubnets.remove(subnetId);
}
return null;
} |
java | @Nullable
public String getAuthorizationUrl() throws UnsupportedEncodingException {
String authorizationCodeRequestUrl =
authorizationCodeFlow.newAuthorizationUrl().setScopes(scopes).build();
if (redirectUri != null) {
authorizationCodeRequestUrl += "&redirect_uri=" + URL... |
python | def _claim(cls, cdata: Any) -> "Tileset":
"""Return a new Tileset that owns the provided TCOD_Tileset* object."""
self = object.__new__(cls) # type: Tileset
if cdata == ffi.NULL:
raise RuntimeError("Tileset initialized with nullptr.")
self._tileset_p = ffi.gc(cdata, lib.TCOD... |
python | def read_rows(
self,
table_name,
app_profile_id=None,
rows=None,
filter_=None,
rows_limit=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Streams back t... |
java | public <T> List<Predicate> byExample(ManagedType<T> mt, Path<T> mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
List<Predicate> predicates = newArrayList();
for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
if (!isPrimaryKey(mt, attr)) {
... |
python | def makeMany2ManyRelatedManager(formodel, name_relmodel, name_formodel):
'''formodel is the model which the manager .'''
class _Many2ManyRelatedManager(Many2ManyRelatedManager):
pass
_Many2ManyRelatedManager.formodel = formodel
_Many2ManyRelatedManager.name_relmodel = name_relmodel
... |
python | def _check_time_range(time_range, now):
'''
Check time range
'''
if _TIME_SUPPORTED:
_start = dateutil_parser.parse(time_range['start'])
_end = dateutil_parser.parse(time_range['end'])
return bool(_start <= now <= _end)
else:
log.error('Dateutil is required.')
... |
python | def upsert(self, events):
"""Inserts/updates the given events into MySQL"""
existing = self.get_existing_keys(events)
inserts = [e for e in events if not e[self.key] in existing]
updates = [e for e in events if e[self.key] in existing]
self.insert(inserts)
self.update(upd... |
python | def header_echo(cls, request,
api_key: (Ptypes.header, String('API key'))) -> [
(200, 'Ok', String)]:
'''Echo the header parameter.'''
log.info('Echoing header param, value is: {}'.format(api_key))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
... |
python | def generic_add(a, b):
print
"""Simple function to add two numbers"""
logger.info('Called generic_add({}, {})'.format(a, b))
return a + b |
python | def shift_rows(state):
"""
Transformation in the Cipher that processes the State by cyclically shifting
the last three rows of the State by different offsets.
"""
state = state.reshape(4, 4, 8)
return fcat(
state[0][0], state[1][1], state[2][2], state[3][3],
state[1][0], state[2]... |
python | def _get_app_config(self, app_name):
"""
Returns an app config for the given name, not by label.
"""
matches = [app_config for app_config in apps.get_app_configs()
if app_config.name == app_name]
if not matches:
return
return matches[0] |
java | protected List<JCAnnotation> annotationsOpt(Tag kind) {
if (token.kind != MONKEYS_AT) return List.nil(); // optimization
ListBuffer<JCAnnotation> buf = new ListBuffer<>();
int prevmode = mode;
while (token.kind == MONKEYS_AT) {
int pos = token.pos;
nextToken();
... |
python | def fromfilenames(cls, filenames, coltype=LIGOTimeGPS):
"""
Read Cache objects from the files named and concatenate the results into a
single Cache.
"""
cache = cls()
for filename in filenames:
cache.extend(cls.fromfile(open(filename), coltype=coltype))
return cache |
python | def get_facet_serializer(self, *args, **kwargs):
"""
Return the facet serializer instance that should be used for
serializing faceted output.
"""
assert "objects" in kwargs, "`objects` is a required argument to `get_facet_serializer()`"
facet_serializer_class = self.get_... |
python | def write_hex(fout, buf, offset, width=16):
"""Write the content of 'buf' out in a hexdump style
Args:
fout: file object to write to
buf: the buffer to be pretty printed
offset: the starting offset of the buffer
width: how many bytes should be displayed per row
"""
skip... |
python | def raise_304(instance):
"""Abort the current request with a 304 (Not Modified) response code.
Clears out the body of the response.
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.Resource`
:raises: :class:`webob.exceptions.ResponseException` ... |
java | private AuthnStatement buildAuthnStatement(final Object casAssertion,
final RequestAbstractType authnRequest,
final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
fin... |
python | def list_mapped_classes():
"""
Returns all the rdfclasses that have and associated elasticsearch
mapping
Args:
None
"""
cls_dict = {key: value
for key, value in MODULE.rdfclass.__dict__.items()
if not isinst... |
java | public static base_response add(nitro_service client, route6 resource) throws Exception {
route6 addresource = new route6();
addresource.network = resource.network;
addresource.gateway = resource.gateway;
addresource.vlan = resource.vlan;
addresource.weight = resource.weight;
addresource.distance = resource... |
java | private void fixNCNTypes(String[] symbs, int[][] graph) {
for (int v = 0; v < graph.length; v++) {
if ("NCN+".equals(symbs[v])) {
boolean foundCNN = false;
for (int w : graph[v]) {
foundCNN = foundCNN || "CNN+".equals(symbs[w]) || "CIM+".equals(sym... |
java | public static <T extends Com4jObject> T getActiveObject(Class<T> primaryInterface, String clsid ) {
return getActiveObject(primaryInterface,new GUID(clsid));
} |
java | @Pure
public static String[] split(char leftSeparator, char rightSeparator, String str) {
final SplitSeparatorToArrayAlgorithm algo = new SplitSeparatorToArrayAlgorithm();
splitSeparatorAlgorithm(leftSeparator, rightSeparator, str, algo);
return algo.toArray();
} |
java | public static String getClassName(Object obj, boolean isSimple) {
if (null == obj) {
return null;
}
final Class<?> clazz = obj.getClass();
return getClassName(clazz, isSimple);
} |
java | public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,
double min , double max , Random rand ) {
// Create a list of all the possible element values
int N = numCols*numRows;
if( N < 0 )
throw new IllegalArg... |
python | def enable_category(self, category: str) -> None:
"""
Enable an entire category of commands
:param category: the category to enable
"""
for cmd_name in list(self.disabled_commands):
func = self.disabled_commands[cmd_name].command_function
if hasattr(func, ... |
java | public DataObject[] getDataObjectArray(){
DataObject[] res = new DataObject[this.dataList.size()];
return this.dataList.toArray(res);
} |
java | @Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
// Save the supplied value to the time picker.
setCellEditorValue(value);
// If needed, adjust the minimum row height for the table.
zAdjustTableR... |
java | private static void hideMultipleParts(IAtomContainer container, Sgroup sgroup) {
final Set<IBond> crossing = sgroup.getBonds();
final Set<IAtom> atoms = sgroup.getAtoms();
final Set<IAtom> parentAtoms = sgroup.getValue(SgroupKey.CtabParentAtomList);
for (IBond bond : container.bonds())... |
java | public void buildSignature(XMLNode node, Content constructorDocTree) {
constructorDocTree.addContent(writer.getSignature(currentConstructor));
} |
python | def dr( self, r1, r2, cutoff=None ):
"""
Calculate the distance between two fractional coordinates in the cell.
Args:
r1 (np.array): fractional coordinates for position 1.
r2 (np.array): fractional coordinates for position 2.
cutoff (optional:Bool): I... |
python | def moment_inertia(self):
"""
The analytic inertia tensor of the sphere primitive.
Returns
----------
tensor: (3,3) float, 3D inertia tensor
"""
tensor = inertia.sphere_inertia(mass=self.volume,
radius=self.primitive.radius... |
java | private void prettyprint(String xmlLogsFile, FileOutputStream htmlReportFile)
throws Exception {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
... |
java | public static Timer getNamedTotalTimer(String timerName) {
long totalCpuTime = 0;
long totalSystemTime = 0;
int measurements = 0;
int timerCount = 0;
int todoFlags = RECORD_NONE;
Timer previousTimer = null;
for (Map.Entry<Timer, Timer> entry : registeredTimers.entrySet()) {
if (entry.getValue().name.e... |
python | def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
"""
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag... |
java | public <T extends BioPAXElement> Class<T> getImplClass(Class<T> aModelInterfaceClass)
{
Class<T> implClass = null;
if (aModelInterfaceClass.isInterface()) {
String name = mapClassName(aModelInterfaceClass);
try {
implClass = (Class<T>) Class.forName(name);
} catch (ClassNotFoundException e) {
log... |
java | public List<List<String>> getAllScopes() {
this.checkInitialized();
final ImmutableList.Builder<List<String>> builder = ImmutableList.<List<String>>builder();
final Consumer<Integer> _function = (Integer it) -> {
List<String> _get = this.scopes.get(it);
StringConcatenation _builder = new StringC... |
python | def make_gdf_graph(filename, stop=True):
"""Create a graph in simple GDF format, suitable for feeding into Gephi,
or some other graph manipulation and display tool. Setting stop to True
will stop the current trace.
"""
if stop:
stop_trace()
try:
f = open(filename, 'w')
f... |
python | def _arm_track_lr_on_stack(self, addr, irsb, function):
"""
At the beginning of the basic block, we check if the first instruction stores the LR register onto the stack.
If it does, we calculate the offset of that store, and record the offset in function.info.
For instance, here is the ... |
java | private void sendEntireMessage(JsMessage jsMessage, List<DataSlice> messageSlices)
throws UnsupportedEncodingException, MessageCopyFailedException,
IncorrectMessageTypeException, MessageEncodeFailedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled(... |
java | public <T> TypeDef createTypeFromTemplate(T model, String[] parameters, String content) {
try (StringWriter writer = new StringWriter()) {
new CodeGeneratorBuilder<T>()
.withContext(context)
.withModel(model)
.withParameters(parameters)
... |
python | def get_signer_by_version(digest, ver):
"""Returns a new signer object for a digest and version combination.
Keyword arguments:
digest -- a callable that may be passed to the initializer of any Signer object in this library.
The callable must return a hasher object when called with no arguments.
... |
python | def delete_model(self, meta: dict):
"""Delete the model from GCS."""
bucket = self.connect()
if bucket is None:
raise BackendRequiredError
blob_name = "models/%s/%s.asdf" % (meta["model"], meta["uuid"])
self._log.info(blob_name)
try:
self._log.info... |
java | protected double receivePoint(LofPoint recievedPoint, LofDataSet dataSet)
{
// 現在保持している学習データ数
int dataCount = dataSet.getDataIdList().size();
// データが最小数に満たない場合はデータの追加のみを行い、LOF値は0.0として扱う
if (dataCount < this.minDataCount)
{
addDataWithoutCalculate(recievedPoint, d... |
java | public static com.liferay.commerce.model.CommerceOrder updateCommerceOrder(
com.liferay.commerce.model.CommerceOrder commerceOrder) {
return getService().updateCommerceOrder(commerceOrder);
} |
python | def get(self, key, default=None, as_int=False, setter=None):
"""Gets a value from the cache.
:param str|unicode key: The cache key to get value for.
:param default: Value to return if none found in cache.
:param bool as_int: Return 64bit number instead of str.
:param callable... |
java | public void updateCellule( SIBUuid8 newRemoteMEUuid)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "updateCellule", newRemoteMEUuid);
this.remoteMEUuid = newRemoteMEUuid;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.ex... |
python | def writeNSdict(self, nsdict):
'''Write a namespace dictionary, taking care to not clobber the
standard (or reserved by us) prefixes.
'''
for k,v in nsdict.items():
if (k,v) in _standard_ns: continue
rv = _reserved_ns.get(k)
if rv:
if r... |
java | private void onCopyFailure(
KeySetView<IOException, Boolean> innerExceptions,
GoogleJsonError e,
String srcBucketName, String srcObjectName) {
if (errorExtractor.itemNotFound(e)) {
FileNotFoundException fnfe =
GoogleCloudStorageExceptions.getFileNotFoundException(srcBucketName, src... |
python | def consume_results(self): # pylint: disable=too-many-branches
"""Handle results waiting in waiting_results list.
Check ref will call consume result and update their status
:return: None
"""
# All results are in self.waiting_results
# We need to get them first
q... |
java | @Override
public GetVocabularyResult getVocabulary(GetVocabularyRequest request) {
request = beforeClientExecution(request);
return executeGetVocabulary(request);
} |
python | def _set_state(self, state):
"""
Transition the SCTP association to a new state.
"""
if state != self._association_state:
self.__log_debug('- %s -> %s', self._association_state, state)
self._association_state = state
if state == self.State.ESTABLISHED:
... |
java | public static int search(long[] longArray, long value) {
int start = 0;
int end = longArray.length - 1;
int middle = 0;
while(start <= end) {
middle = (start + end) >> 1;
if(value == longArray[middle]) {
return middle;
... |
java | public static void solveL( double L[] , double []b , int n )
{
// for( int i = 0; i < n; i++ ) {
// double sum = b[i];
// for( int k=0; k<i; k++ ) {
// sum -= L[i*n+k]* b[k];
// }
// b[i] = sum / L[i*n+i];
// }
for( int i = 0; i < n; i... |
python | def _load(self):
"""Fetch metadata from remote. Entries are fetched lazily."""
# This will not immediately fetch any sources (entries). It will lazily
# fetch sources from the server in paginated blocks when this Catalog
# is iterated over. It will fetch specific sources when they are
... |
python | def _long_string_handler(c, ctx, is_field_name=False):
"""Handles triple-quoted strings. Remains active until a value other than a long string is encountered."""
assert c == _SINGLE_QUOTE
is_clob = ctx.ion_type is IonType.CLOB
max_char = _MAX_CLOB_CHAR if is_clob else _MAX_TEXT_CHAR
assert not (is_c... |
java | public <S extends Model, R> AnimaQuery<T> where(TypeFunction<S, R> function, Object value) {
String columnName = AnimaUtils.getLambdaColumnName(function);
conditionSQL.append(" AND ").append(columnName).append(" = ?");
paramValues.add(value);
return this;
} |
java | public java.util.List<IpRouteInfo> getIpRoutesInfo() {
if (ipRoutesInfo == null) {
ipRoutesInfo = new com.amazonaws.internal.SdkInternalList<IpRouteInfo>();
}
return ipRoutesInfo;
} |
python | def _no_more_pads(self, element):
"""The callback for GstElement's "no-more-pads" signal.
"""
# Sent when the pads are done adding (i.e., there are no more
# streams in the file). If we haven't gotten at least one
# decodable stream, raise an exception.
if not self._got_a... |
java | public static boolean stampVersion(JsonDBConfig dbConfig, File f, String version) {
FileOutputStream fos = null;
OutputStreamWriter osr = null;
BufferedWriter writer = null;
try {
fos = new FileOutputStream(f);
osr = new OutputStreamWriter(fos, dbConfig.getCharset());
writer = new Buf... |
python | def send(self, frame):
"""
Handle the SEND command: Delivers a message to a queue or topic (default).
"""
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for SEND command.')
if dest.startswith('/queue/'):
... |
python | def get_measurement_metadata(self, fields, ids=None, noneval=nan,
output_format='DataFrame'):
"""
Get the metadata fields of specified measurements (all if None given).
Parameters
----------
fields : str | iterable of str
Names of met... |
java | public FaceDetail withEmotions(Emotion... emotions) {
if (this.emotions == null) {
setEmotions(new java.util.ArrayList<Emotion>(emotions.length));
}
for (Emotion ele : emotions) {
this.emotions.add(ele);
}
return this;
} |
python | def send(self, request: Request) -> None:
"""
Dispatches a request. Expects one and one only target handler
:param request: The request to dispatch
:return: None, will throw a ConfigurationException if more than one handler factor is registered for the command
"""
handle... |
java | public void decode(AsnInputStream ais) throws ParseException {
try {
long val = ais.readInteger();
if (ais.getTag() == OperationCode._TAG_NATIONAL) {
this.setNationalOperationCode(val);
} else {
this.setPrivateOperationCode(val);
}... |
python | def middleware(self, *args, **kwargs):
"""
A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints recur... |
java | public ServiceFuture<VpnSiteInner> updateTagsAsync(String resourceGroupName, String vpnSiteName, Map<String, String> tags, final ServiceCallback<VpnSiteInner> serviceCallback) {
return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, vpnSiteName, tags), serviceCallback);
} |
java | @Override
public long dynamicQueryCount(DynamicQuery dynamicQuery,
Projection projection) {
return commerceNotificationAttachmentPersistence.countWithDynamicQuery(dynamicQuery,
projection);
} |
java | private void addTimeZoneOffset(Calendar c, StringBuilder sb) {
int min = (c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / 60000;
char op;
if (min < 0) {
op = '-';
min = min - min - min;
}
else op = '+';
int hours = min / 60;
min = min - (hours * 60);
sb.append(op);
toString(sb, hours, 2)... |
java | public static void configureLogback( ServletContext servletContext, File logDirFallback, String vHostName, Logger log ) throws FileNotFoundException, MalformedURLException, IOException {
log.debug("Reconfiguring Logback!");
String systemLogDir = System.getProperty(LOG_DIRECTORY_OVERRIDE, System.getProperty(JBOS... |
java | @Nonnull
public JSFunction name (@Nonnull @Nonempty final String sName)
{
if (!JSMarshaller.isJSIdentifier (sName))
throw new IllegalArgumentException ("The name '" + sName + "' is not a legal JS identifier!");
m_sName = sName;
return this;
} |
python | def _get_random_id():
""" Get a random (i.e., unique) string identifier"""
symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(symbols) for _ in range(15)) |
python | def save(self, fname=None, link_copy=False,raiseError=False):
""" link_copy: only works in hfd5 format
save space by creating link when identical arrays are found,
it may slows down the saving (3 or 4 folds) but saves space
when saving different dataset together (since it doe... |
python | def exists(self, record_key):
'''
a method to determine if a record exists in collection
:param record_key: string with key of record
:return: boolean reporting status
'''
title = '%s.exists' % self.__class__.__name__
# validate... |
python | def safe_data(self):
"""The data dictionary for this entity.
If this `ModelEntity` points to the dead state, it will
raise `DeadEntityException`.
"""
if self.data is None:
raise DeadEntityException(
"Entity {}:{} is dead - its attributes can no longe... |
java | public String getGroupName() {
CollapsibleGroup group = getGroup();
return (group == null ? getId() : group.getGroupName());
} |
python | def _hashed_key(self):
""" Returns 16-digit numeric hash of the redis key """
return abs(int(hashlib.md5(
self.key_prefix.encode('utf8')
).hexdigest(), 16)) % (10 ** (
self._size_mod if hasattr(self, '_size_mod') else 5)) |
python | def _keep_alive(self, get_work_response):
"""
Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pe... |
java | private String getParameterValue(CmsObject cms, String key) {
if (m_parameters == null) {
m_parameters = getParameterMap(getStringValue(cms));
}
return getParameterValue(cms, m_parameters, key);
} |
java | @Override
public void flush() throws IOException {
List<Exception> flushExceptions = new ArrayList<>(delegates.size());
for (Writer delegate : delegates) {
try {
delegate.flush();
} catch (IOException | RuntimeException flushException) {
flushE... |
java | public MethodHandle nop() {
if (type().returnType() != void.class) {
throw new InvalidTransformException("must have void return type to nop: " + type());
}
return invoke(Binder
.from(type())
.drop(0, type().parameterCount())
.cast(Objec... |
python | def metaclass(*metaclasses):
# type: (*type) -> Callable[[type], type]
"""Create the class using all metaclasses.
Args:
metaclasses: A tuple of metaclasses that will be used to generate and
replace a specified class.
Returns:
A decorator that will recreate the class using t... |
java | public int setString( String strField, boolean bDisplayOption, int iMoveMode)
{
NumberField numberField = (NumberField)this.getNextConverter();
int iErrorCode = super.setString(strField, DBConstants.DONT_DISPLAY, iMoveMode);
if (strField.length() == 0)
numberField.displayField();... |
java | private void evalUnit(MessageArg arg) {
// TODO: format unit ranges, e.g. {0;1 unit in:seconds sequence:hour,minute}
if (!arg.resolve()) {
return;
}
initUnitArgsParser();
parseArgs(unitArgsParser);
BigDecimal amount = arg.asBigDecimal();
// TODO: For future refactoring:
// T... |
python | def translate_purposes(f):
"""decorator to translate the purposes field.
translate the values of the purposes field of the API response into
translated values.
"""
@wraps(f)
def wr(r, pc):
tmp = []
for P in r["purposes"]:
try:
tmp.append(POSTCODE_API_... |
python | def get_choice_selected_value(self):
"""
Returns the default selection from a choice menu
Throws an error if this is not a choice parameter.
"""
if 'choiceInfo' not in self.dto[self.name]:
raise GPException('not a choice parameter')
choice_info_dto = self.dto[... |
python | def ekntab():
"""
Return the number of loaded EK tables.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html
:return: The number of loaded EK tables.
:rtype: int
"""
n = ctypes.c_int(0)
libspice.ekntab_c(ctypes.byref(n))
return n.value |
java | public long getNearestPosition(long recordNumber) {
if (recordNumber < startingRecordNumber || recordNumber > lastRecordNumber)
throw new IndexOutOfBoundsException();
return index.get((int) ((recordNumber - startingRecordNumber) / step));
} |
java | @Override
protected void unserializeFrom(RawDataBuffer in)
{
super.unserializeFrom(in);
consumerId = new IntegerID(in.readInt());
topic = (Topic)DestinationSerializer.unserializeFrom(in);
messageSelector = in.readNullableUTF();
noLocal = in.readBoolean();
name = in.r... |
java | public static Pattern convertPerlRegexToPattern(@Nonnull final String regex, @Nonnull final boolean faultTolerant) {
Check.notNull(regex, "regex");
String pattern = regex.trim();
final Matcher matcher = faultTolerant ? PERL_STYLE_TOLERANT.matcher(pattern) : PERL_STYLE.matcher(pattern);
if (!matcher.matches()) ... |
python | def uuid_constructor(loader, node):
""""
Construct a uuid.UUID object form a scalar YAML node.
Tests:
>>> yaml.add_constructor("!uuid", uuid_constructor, Loader=yaml.SafeLoader)
>>> yaml.safe_load("{'test': !uuid 'cc3702ca-699a-4aa6-8226-4c938f294d9b'}")
{'test': UUID('cc3702ca-699a... |
java | @NotNull
public DoubleStream mapToDouble(@NotNull final LongToDoubleFunction mapper) {
return new DoubleStream(params, new LongMapToDouble(iterator, mapper));
} |
java | public static Color stringToColor(String str) {
int icol = SVG_COLOR_NAMES.getInt(str.toLowerCase());
if(icol != NO_VALUE) {
return new Color(icol, false);
}
return colorLookupStylesheet.stringToColor(str);
} |
java | @Override
public AssociateServiceActionWithProvisioningArtifactResult associateServiceActionWithProvisioningArtifact(
AssociateServiceActionWithProvisioningArtifactRequest request) {
request = beforeClientExecution(request);
return executeAssociateServiceActionWithProvisioningArtifact(re... |
python | def __bind(self):
'''
Bind to the local port
'''
# using ZMQIOLoop since we *might* need zmq in there
install_zmq()
self.io_loop = ZMQDefaultLoop()
self.io_loop.make_current()
for req_channel in self.req_channels:
req_channel.post_fork(self._ha... |
python | def get_synset_xml(self,syn_id):
"""
call cdb_syn with synset identifier -> returns the synset xml;
"""
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.debug:
printf( "cornettodb/views/query_remote_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.