language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def prompt_cfg(self, msg, sec, name, ispass=False):
"""Prompt for a config value, optionally saving it to the user-level
cfg. Only runs if we are in an interactive mode.
@param msg: Message to display to user.
@param sec: Section of config to add to.
@param name: Config item name.
@param ispass: If... |
python | def alias_bin(self, bin_id, alias_id):
"""Adds an ``Id`` to a ``Bin`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Bin`` is determined by the provider.
The new ``Id`` performs as an alias to the primary ``Id``. If
the alias is a pointer to another bin, it is re... |
python | def search_videohub(cls, query, filters=None, status=None, sort=None, size=None, page=None):
"""searches the videohub given a query and applies given filters and other bits
:see: https://github.com/theonion/videohub/blob/master/docs/search/post.md
:see: https://github.com/theonion/videohub/blob... |
java | @Override
public void onFinish(ISuite suite) {
logger.entering(suite);
if (ListenerManager.isCurrentMethodSkipped(this)) {
logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);
return;
}
LocalGridManager.shutDownHub();
logger.exiting();
} |
java | private void assignValue(SimpleNode node, RelationQueryNode queryNode) {
if (node.getId() == JJTSTRINGLITERAL) {
queryNode.setStringValue(unescapeQuotes(node.getValue()));
} else if (node.getId() == JJTDECIMALLITERAL) {
queryNode.setDoubleValue(Double.parseDouble(node.getValue())... |
python | def export_live_eggs(self, env=False):
"""Adds all of the eggs in the current environment to PYTHONPATH."""
path_eggs = [p for p in sys.path if p.endswith('.egg')]
command = self.get_finalized_command("egg_info")
egg_base = path.abspath(command.egg_base)
unique_path_eggs = set(... |
python | def hil_state_encode(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc):
'''
DEPRECATED PACKET! Suffers from missing airspeed fields and
singularities due to Euler angles. Please use
HIL_STATE_Q... |
python | def get_lux_count(lux_byte):
""" Method to convert data from the TSL2550D lux sensor
into more easily usable ADC count values.
"""
LUX_VALID_MASK = 0b10000000
LUX_CHORD_MASK = 0b01110000
LUX_STEP_MASK = 0b00001111
valid = lux_byte & LUX_VALID_MASK
if valid != 0:
step_n... |
java | private void checkError() throws IOException {
final Throwable t = channelError.get();
if (t != null) {
if (t instanceof IOException) {
throw (IOException) t;
} else {
throw new IOException("There has been an error in the channel.", t);
}
}
} |
java | public List<RemoveMethodType<SessionBeanType<T>>> getAllRemoveMethod()
{
List<RemoveMethodType<SessionBeanType<T>>> list = new ArrayList<RemoveMethodType<SessionBeanType<T>>>();
List<Node> nodeList = childNode.get("remove-method");
for(Node node: nodeList)
{
RemoveMethodType<SessionB... |
java | public synchronized void load(LCMSDataSubset subset, Object user) throws FileParsingException {
if (user == null) {
throw new IllegalArgumentException("User can't be null");
}
// load data, if it's not there yet
if (!isLoaded(subset)) {
scans.loadData(subset, null);
}
// add the sub... |
java | @FFDCIgnore({ InterruptedException.class })
public synchronized void waitForLevel() {
// Don't bother waiting if the vm has been shutdown in the meanwhile...
while (levelReached.get() == false && !shutdownHook.vmShutdown()) {
try {
// waiting for a start level event shoul... |
java | @Override
public void removeConsumerPointMatchTarget(DispatchableKey consumerPointData)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "removeConsumerPointMatchTarget", consumerPointData);
// Remove the consumer point from the matchspace
/... |
python | def layer_register(
log_shape=False,
use_scope=True):
"""
Args:
log_shape (bool): log input/output shape of this layer
use_scope (bool or None):
Whether to call this layer with an extra first argument as variable scope.
When set to None, it can be called e... |
python | def str_if_nested_or_str(s):
"""Turn input into a native string if possible."""
if isinstance(s, ALL_STRING_TYPES):
return str(s)
if isinstance(s, (list, tuple)):
return type(s)(map(str_if_nested_or_str, s))
if isinstance(s, (dict, )):
return stringify_dict_contents(s)
return... |
python | def sysinfo2float(version_info=sys.version_info):
"""Convert a sys.versions_info-compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can only be used for released version
of C Python, not interim development versions, since we can... |
java | public void initForNextResponse(IResponse resp) {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) //306998.15
logger.entering(CLASS_NAME,"initForNextResponse", "resp = " + resp + " ["+this+"]");
if (resp == null) {
_rawOut.init(null);
... |
python | def namedb_get_record_states_at(cur, history_id, block_number):
"""
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed a... |
python | def repel_text(texts, renderer=None, ax=None, expand=(1.2, 1.2),
only_use_max_min=False, move=False):
"""
Repel texts from each other while expanding their bounding boxes by expand
(x, y), e.g. (1.2, 1.2) would multiply width and height by 1.2.
Requires a renderer to get the actual sizes ... |
java | private boolean checkForVariables(List<Map<String, String>> values) {
if (values == null || values.isEmpty()) {
return false;
} else {
for (Map<String, String> list : values) {
if (list.containsKey("type") && list.get("type")
.equals(MtasParserMapping.PARSER_TYPE_VARIABLE)) {
... |
python | def enable_nn_ha(self, active_name, standby_host_id, nameservice, jns,
standby_name_dir_list=None, qj_name=None, standby_name=None,
active_fc_name=None, standby_fc_name=None, zk_service_name=None,
force_init_znode=True, clear_existing_standby_name_dirs=True, clear_existing_jn_edits_dir=True):
"""
... |
python | def create_app(applet_id, applet_name, src_dir, publish=False, set_default=False, billTo=None, try_versions=None,
try_update=True, confirm=True, regional_options=None):
"""
Creates a new app object from the specified applet.
.. deprecated:: 0.204.0
Use :func:`create_app_multi_region()... |
java | public void setDocumentation(String doc) {
if (Strings.isEmpty(doc)) {
getSarlAnnotationType().eAdapters().removeIf(new Predicate<Adapter>() {
public boolean test(Adapter adapter) {
return adapter.isAdapterForType(DocumentationAdapter.class);
}
});
} else {
DocumentationAdapter adapter = (Docu... |
python | def getSystemVariable(self, remote, name):
"""Get single system variable from CCU / Homegear"""
if self._server is not None:
return self._server.getSystemVariable(remote, name) |
python | def sslv2_derive_keys(self, key_material):
"""
There is actually only one key, the CLIENT-READ-KEY or -WRITE-KEY.
Note that skip_first is opposite from the one with SSLv3 derivation.
Also, if needed, the IV should be set elsewhere.
"""
skip_first = True
if ((sel... |
python | def view_current_app_behavior(self) -> str:
'''View application behavior in the current window.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'windows')
return re.findall(r'mCurrentFocus=.+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)', output)[0] |
python | def write_libxc_docs_json(xcfuncs, jpath):
"""Write json file with libxc metadata to path jpath."""
from copy import deepcopy
xcfuncs = deepcopy(xcfuncs)
# Remove XC_FAMILY from Family and XC_ from Kind to make strings more human-readable.
for d in xcfuncs.values():
d["Family"] = d["Family"... |
python | def serialize_with_sampled_logs(self, logs_limit=-1):
"""serialize a result with up to `logs_limit` logs.
If `logs_limit` is -1, this function will return a result with all its
logs.
"""
return {
'id': self.id,
'pathName': self.path_name,
'na... |
python | def _warning(self, msg, node_id, ex, *args, **kwargs):
"""
Handles the error messages.
.. note:: If `self.raises` is True the dispatcher interrupt the dispatch
when an error occur, otherwise it logs a warning.
"""
raises = self.raises(ex) if callable(self.raises) els... |
java | public static Geometry convert(JGeometry geometry) {
switch (geometry.getType()) {
case GTYPE_COLLECTION: return convertCollection(geometry);
case GTYPE_CURVE: return convertCurve(geometry);
case GTYPE_MULTICURVE: return convertMultiCurve(geometry);
case GTYPE_MULTIPOINT: return ... |
python | def Recurrent(step_model):
"""Apply a stepwise model over a sequence, maintaining state. For RNNs"""
ops = step_model.ops
def recurrent_fwd(seqs, drop=0.0):
lengths = [len(X) for X in seqs]
X, size_at_t, unpad = ops.square_sequences(seqs)
Y = ops.allocate((X.shape[0], X.shape[1], st... |
java | public static String driversLicense() {
StringBuffer dl = new StringBuffer(JDefaultAddress.stateAbbr());
dl.append("-");
dl.append(JDefaultNumber.randomNumberString(8));
return dl.toString();
} |
java | public static void createHtmlSequencePlotFile(String title, Schema schema, List<List<Writable>> sequence,
File output) throws Exception {
String s = createHtmlSequencePlots(title, schema, sequence);
FileUtils.writeStringToFile(output, s, StandardCharsets.UTF_8);
} |
python | def CMY_to_RGB(cobj, target_rgb, *args, **kwargs):
"""
Converts CMY to RGB via simple subtraction.
NOTE: Returned values are in the range of 0-255.
"""
rgb_r = 1.0 - cobj.cmy_c
rgb_g = 1.0 - cobj.cmy_m
rgb_b = 1.0 - cobj.cmy_y
return target_rgb(rgb_r, rgb_g, rgb_b) |
java | @NonNull
public static Icon base64(byte[] bytes) {
return new Icon(sanitize(DatatypeConverter.printBase64Binary(bytes)), true);
} |
java | public boolean isTemporary()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "isTemporary");
boolean isTemporary = _foreignBus.isTemporary();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "isTemporary", new Boolean(isTe... |
python | def get_gradebook_column_lookup_session_for_gradebook(self, gradebook_id, proxy):
"""Gets the ``OsidSession`` associated with the gradebook column lookup service for the given gradebook.
arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook
arg: proxy (osid.proxy.Proxy): a proxy
... |
java | public List<EntityExtractor> listCustomPrebuiltEntities(UUID appId, String versionId) {
return listCustomPrebuiltEntitiesWithServiceResponseAsync(appId, versionId).toBlocking().single().body();
} |
java | public static String trim(String xml) {
String content = removeDeclaration(xml);
return trimElements(content);
} |
python | def where(self, params):
"""Set a dict of parameters to be passed to the API when invoking this request.
:param params: (dict) query parameters.
:return: this :class:`.RequestArray` instance for convenience.
"""
self.params = dict(self.params, **params) # params overrides self... |
java | @Override
public void cookieEquals(String cookieName, String expectedCookieValue) {
assertEquals("Cookie Value Mismatch", expectedCookieValue, checkCookieEquals(cookieName, expectedCookieValue, 0, 0));
} |
java | public static final String printTimestamp(Date value)
{
return (value == null ? null : TIMESTAMP_FORMAT.get().format(value));
} |
java | public void convertClass(TypeElement te, DocPath outputdir)
throws DocFileIOException, SimpleDocletException {
if (te == null) {
return;
}
FileObject fo = utils.getFileObject(te);
if (fo == null)
return;
try {
Reader r = fo.openRea... |
python | def QA_util_format_date2str(cursor_date):
"""
对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串
支持格式包括:
1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S",
"%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S"
2. datetime.datetime
3. pd.Timestamp
4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019... |
python | def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
# Items should be an array of type CoinState, not of ints!
corrected_items = list(map(lambda i: CoinState(i), self.Items))
return super(UnspentCoinState, self).Size... |
java | protected Future<?> getFuture() {
long stamp = lock.tryOptimisticRead();
Future<?> future = this.future;
if (!lock.validate(stamp)) { // Not valid so wait for read lock
stamp = lock.readLock();
try {
future = this.future;
} finally {
lock.unlockRead(stamp);
}
}
return future;
} |
python | def Setup(self, input, URL, encoding, options):
"""Setup an XML reader with new options """
if input is None: input__o = None
else: input__o = input._o
ret = libxml2mod.xmlTextReaderSetup(self._o, input__o, URL, encoding, options)
return ret |
java | public void loadExampleStatementsFromXMLString(String xmlString)
throws JSONException, IllegalArgumentException, JsonParseException, JsonMappingException, IOException
{
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Receiving json string: " + xmlString);
}
JSONObject jsonobject = XML.toJSO... |
java | public List<TColumn> columnsOfType(GeoPackageDataType type) {
List<TColumn> columnsOfType = new ArrayList<>();
for (TColumn column : columns) {
if (column.getDataType() == type) {
columnsOfType.add(column);
}
}
return columnsOfType;
} |
python | def encryption_key(self, alg, **kwargs):
"""
Return an encryption key as per
http://openid.net/specs/openid-connect-core-1_0.html#Encryption
:param alg: encryption algorithm
:param kwargs:
:return: encryption key as byte string
"""
if not self.key:
... |
java | private String appendMoreLogsLink(final String fileName, String url) throws IOException {
FileBackedStringBuffer buffer = new FileBackedStringBuffer();
int index = retrieveIndexValueFromFileName(fileName);
index++;
File logFileName = retrieveFileFromLogsFolder(Integer.toString(index));
... |
python | def getObjectByPid(self, pid):
"""
Args:
pid : str
Returns:
str : URIRef of the entry identified by ``pid``."""
self._check_initialized()
opid = rdflib.term.Literal(pid)
res = [o for o in self.subjects(predicate=DCTERMS.identifier, object=opid)]
return res[0] |
python | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._type_ is not None:
return False
if self._second_line is not None:
return False
if self._expiry_date is not None:
... |
java | public LoginConfigType<WebAppType<T>> getOrCreateLoginConfig()
{
List<Node> nodeList = childNode.get("login-config");
if (nodeList != null && nodeList.size() > 0)
{
return new LoginConfigTypeImpl<WebAppType<T>>(this, "login-config", childNode, nodeList.get(0));
}
return create... |
python | def redirect_to_url(req, url, redirection_type=None, norobot=False):
"""
Redirect current page to url.
@param req: request as received from apache
@param url: url to redirect to
@param redirection_type: what kind of redirection is required:
e.g.: apache.HTTP_MULTIPLE_CHOICES = 300
... |
java | public void warn(Object message)
{
if (IS12)
{
getLogger().log(FQCN, Level.WARN, message, null);
}
else
{
getLogger().log(FQCN, Level.WARN, message, null);
}
} |
java | @com.fasterxml.jackson.annotation.JsonProperty("RequestID")
public void setRequestID(String requestID) {
this.requestID = requestID;
} |
java | public static void write(byte[] bytes,File file) throws IOException {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
outputStream.write(bytes);
outputStream.close();
} |
python | def _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data):
"""Perform a BWA alignment using 'aln' backtrack algorithm.
"""
bwa = config_utils.get_program("bwa", data["config"])
config = data["config"]
sai1_file = "%s_1.sai" % os.path.splitext(out_file)[0]
sai2_file = ... |
python | def send_env_text(self, text, episode_id):
''' text channel to communicate with the agent '''
reactor.callFromThread(self._send_env_text, text, episode_id) |
java | public final DataHasher addData(File file, int bufferSize) {
Util.notNull(file, "File");
FileInputStream inStream = null;
try {
inStream = new FileInputStream(file);
return addData(inStream, bufferSize);
} catch (FileNotFoundException e) {
throw new Il... |
python | def _wait_for_tasks(tasks, service_instance):
'''
Wait for tasks created via the VSAN API
'''
log.trace('Waiting for vsan tasks: {0}',
', '.join([six.text_type(t) for t in tasks]))
try:
vsanapiutils.WaitForTasks(tasks, service_instance)
except vim.fault.NoPermission as exc:... |
python | def add_z(self, name, prior, q, index=True):
""" Adds latent variable
Parameters
----------
name : str
Name of the latent variable
prior : Prior object
Which prior distribution? E.g. Normal(0,1)
q : Distribution object
Which distribu... |
java | public void writeExternal(ObjectOutput out) throws IOException
{
out.writeInt(orderNumber);
byte[] data = value.getIdentity().getBytes(Constants.DEFAULT_ENCODING);
out.writeInt(data.length);
if (data.length > 0)
{
out.write(data);
}
data = value.getPermission().g... |
java | public static <T> StreamEx<List<T>> cartesianProduct(Collection<? extends Collection<T>> source) {
if (source.isEmpty())
return StreamEx.of(new ConstSpliterator.OfRef<>(Collections.emptyList(), 1, true));
return of(new CrossSpliterator.ToList<>(source));
} |
python | def wipe_cfg_vals_from_git_cfg(*cfg_opts):
"""Remove a set of options from Git config."""
for cfg_key_suffix in cfg_opts:
cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
cmd = "git", "config", "--local", "--unset-all", cfg_key
subprocess.check_call(cmd, stderr=subprocess.ST... |
python | def pop(self):
"""Retrieve the next element in line, this will remove it from the queue"""
e = self.data[self.start]
self.start += 1
if self.start > 5 and self.start > len(self.data)//2:
self.data = self.data[self.start:]
self.start = 0
return e |
java | private SplitBrainJoinMessage sendSplitBrainJoinMessage(Address target, SplitBrainJoinMessage request) {
if (logger.isFineEnabled()) {
logger.fine("Sending SplitBrainJoinMessage to " + target);
}
Connection conn = node.getEndpointManager(MEMBER).getOrConnect(target, true);
l... |
java | public void addMembership(Membership membership) throws RedmineException {
final Project project = membership.getProject();
if (project == null)
throw new IllegalArgumentException("Project must be set");
if (membership.getUser() == null)
throw new IllegalArgumentException("User must be set");
transport.ad... |
python | def get_cim_ns(namespaces):
"""
Tries to obtain the CIM version from the given map of namespaces and
returns the appropriate *nsURI* and *packageMap*.
"""
try:
ns = namespaces['cim']
if ns.endswith('#'):
ns = ns[:-1]
except KeyError:
ns = ''
logger.er... |
python | def col_frequencies(col, weights=None, gap_chars='-.'):
"""Frequencies of each residue type (totaling 1.0) in a single column."""
counts = col_counts(col, weights, gap_chars)
# Reduce to frequencies
scale = 1.0 / sum(counts.values())
return dict((aa, cnt * scale) for aa, cnt in counts.iteritems()) |
java | public com.squareup.okhttp.Call getCorporationsCorporationIdAlliancehistoryAsync(Integer corporationId,
String datasource, String ifNoneMatch, final ApiCallback<List<CorporationAlliancesHistoryResponse>> callback)
throws ApiException {
com.squareup.okhttp.Call call = getCorporationsCorp... |
python | def band_path(self, band_id, for_gdal=False, absolute=False):
"""Return paths of given band's jp2 files for all granules."""
band_id = str(band_id).zfill(2)
if not isinstance(band_id, str) or band_id not in BAND_IDS:
raise ValueError("band ID not valid: %s" % band_id)
if self... |
java | public int[] getElementIndices() {
if (indices != null)
return indices;
Integer[] objIndices = indexToValue.keySet().toArray(new Integer[0]);
indices = new int[objIndices.length];
for (int i = 0; i < objIndices.length; ++i)
indices[i] = objIndices[i].intValue();
... |
python | def yank_fields_from_attrs(attrs, _as=None, sort=True):
"""
Extract all the fields in given attributes (dict)
and return them ordered
"""
fields_with_names = []
for attname, value in list(attrs.items()):
field = get_field_as(value, _as)
if not field:
continue
... |
java | private static boolean isDefinitePrimitive(SoyType type) {
return type.getKind() == SoyType.Kind.BOOL
|| isNumericPrimitive(type)
|| type.getKind().isKnownStringOrSanitizedContent();
} |
java | public Set<String> getUnconditionalClasses() {
Set<String> filtered = new HashSet<>(this.unconditionalClasses);
filtered.removeAll(this.exclusions);
return Collections.unmodifiableSet(filtered);
} |
java | public boolean isRevisitDigest() {
String dupeType = get(CAPTURE_DUPLICATE_ANNOTATION);
return (dupeType != null && dupeType.equals(CAPTURE_DUPLICATE_DIGEST));
} |
python | def gaussian(cls, mu=0, sigma=1):
'''
:mu: mean
:sigma: standard deviation
:return: Point subclass
Returns a point whose coordinates are picked from a Gaussian
distribution with mean 'mu' and standard deviation 'sigma'.
See random.gauss for further explanati... |
python | def _write(self, command, future):
"""Write a command to the socket
:param Command command: the Command data structure
"""
def on_written():
self._on_written(command, future)
try:
self._stream.write(command.command, callback=on_written)
except ... |
python | def _remove_accents(filename):
"""
Function that will try to remove accents from a unicode string to be used in a filename.
input filename should be either an ascii or unicode string
"""
# noinspection PyBroadException
try:
filename = filename.replace(" ", "_")
if isinstance(file... |
java | public Account getAccount(String sessionId) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.SESSION_ID, sessionId);
URL url = new ApiUrl(apiKey, MethodBase.ACCOUNT).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
... |
java | public CmsResourceFilter addRequireTimerange() {
CmsResourceFilter extendedFilter = (CmsResourceFilter)clone();
extendedFilter.m_filterTimerange = true;
extendedFilter.updateCacheId();
return extendedFilter;
} |
python | def handle_pubrec(self):
"""Handle incoming PUBREC packet."""
self.logger.info("PUBREC received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventPubrec(mid)
self.push_event(evt)
return NC.ERR_SUCCESS |
java | protected void writeToArchive(File[] sources, ArchiveOutputStream archive) throws IOException {
for (File source : sources) {
if (!source.exists()) {
throw new FileNotFoundException(source.getPath());
} else if (!source.canRead()) {
throw new FileNotFoundE... |
java | public void setForwardRoutingPath(List<SIDestinationAddress> value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setForwardRoutingPath");
setFRP(value);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exi... |
python | def _s3_resource(dallinger_region=False):
"""A boto3 S3 resource using the AWS keys in the config."""
config = get_config()
if not config.ready:
config.load()
region = "us-east-1" if dallinger_region else config.get("aws_region")
return boto3.resource(
"s3",
region_name=regi... |
java | @SuppressWarnings("unchecked")
@Override
public void setup() throws CoreException {
final boolean canProcessAnnotation = ComponentEnhancer.canProcessAnnotation((Class<? extends Component<?>>) this.getClass());
if (canProcessAnnotation) {
// Search Singleton and Multiton annotation ... |
java | public Observable<BlobContainerInner> getAsync(String resourceGroupName, String accountName, String containerName) {
return getWithServiceResponseAsync(resourceGroupName, accountName, containerName).map(new Func1<ServiceResponse<BlobContainerInner>, BlobContainerInner>() {
@Override
publ... |
python | def parse_kwargs(kwargs):
"""
Convert a list of kwargs into a dictionary. Duplicates of the same keyword
get added to an list within the dictionary.
>>> parse_kwargs(['--var1=1', '--var2=2', '--var1=3']
{'var1': [1, 3], 'var2': 2}
"""
d = defaultdict(list)
for k, v in ((k.lstrip('-... |
java | public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java twitter4j.examples.list.GetUserListMemberships [list member screen name]");
System.exit(-1);
}
try {
Twitter twitter = new TwitterFactory().getInstance();
... |
java | @Override
public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) {
return cpDefinitionPersistence.findWithDynamicQuery(dynamicQuery);
} |
java | public void addDataElement(String elemName, String content, Attributes attrs) {
writeDataElement(elemName, attrs, content);
} |
python | def read_var_uint32(self):
"""Reads a varint from the stream, interprets this varint
as an unsigned, 32-bit integer, and returns the integer.
"""
i = self.read_var_uint64()
if i > wire_format.UINT32_MAX:
raise errors.DecodeError('Value out of range for uint32: %d' % i... |
java | public static Type[] getImplicitLowerBounds(final WildcardType wildcardType) {
Validate.notNull(wildcardType, "wildcardType is null");
final Type[] bounds = wildcardType.getLowerBounds();
return bounds.length == 0 ? new Type[] { null } : bounds;
} |
java | @Override
public GallicWeight commonDivisor(GallicWeight a, GallicWeight b) {
double newWeight = this.weightSemiring.plus(a.getWeight(), b.getWeight());
if (isZero(a)) {
if (isZero(b)) {
return zero;
}
if (b.getLabels().isEmpty()) {
return GallicWeight.create(GallicWeight.EMP... |
python | def portalAdmin(self):
"""gets a reference to a portal administration class"""
from ..manageportal import PortalAdministration
return PortalAdministration(admin_url="https://%s/portaladmin" % self.portalHostname,
securityHandler=self._securityHandler,
... |
python | def strtol(value, strict=True):
"""As most as possible close equivalent of strtol(3) function (with base=0),
used by postgres to parse parameter values.
>>> strtol(0) == (0, '')
True
>>> strtol(1) == (1, '')
True
>>> strtol(9) == (9, '')
True
>>> strtol(' +0x400MB') == (1024, 'MB'... |
java | @RequirePOST
public HttpResponse doNewLogRecorder(@QueryParameter String name) {
Jenkins.checkGoodName(name);
logRecorders.put(name,new LogRecorder(name));
// redirect to the config screen
return new HttpRedirect(name+"/configure");
} |
python | def rename_property(cr, model, old_name, new_name):
"""Rename property old_name owned by model to new_name. This should happen
in a pre-migration script."""
cr.execute(
"update ir_model_fields f set name=%s "
"from ir_model m "
"where m.id=f.model_id and m.model=%s and f.name=%s "
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.