language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def get_temp_url(self, obj, seconds, method="GET", key=None, cached=True):
"""
Given a storage object in this container, returns a URL that can be
used to access that object. The URL will expire after `seconds`
seconds.
The only methods supported are GET and PUT. Anything else w... |
python | def fetch(db=None, sql=None):
'''
Retrieve data from an sqlite3 db (returns all rows, be careful!)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;'
'''
cur = _connect(db)
if not cur:
return False
cur.execute(sql)
rows =... |
java | public Observable<Page<ManagedInstanceEncryptionProtectorInner>> listByInstanceAsync(final String resourceGroupName, final String managedInstanceName) {
return listByInstanceWithServiceResponseAsync(resourceGroupName, managedInstanceName)
.map(new Func1<ServiceResponse<Page<ManagedInstanceEncryption... |
python | def _make_intersection(edge_info, all_edge_nodes):
"""Convert a description of edges into a curved polygon.
.. note::
This is a helper used only by :meth:`.Surface.intersect`.
Args:
edge_info (Tuple[Tuple[int, float, float], ...]): Information
describing each edge in the curved... |
java | private int doContentCache() throws IOException {
// file
cacheItem = generateCacheResource(key, true);
// use cache
if (cacheItem.isValid(timespan)) {
pageContext.write(cacheItem.getValue());
doCaching = false;
return SKIP_BODY;
}
doCaching = true;
return EVAL_BODY_BUFFERED;
} |
java | public static af_persistant_stat_info[] get(nitro_service client) throws Exception
{
af_persistant_stat_info resource = new af_persistant_stat_info();
resource.validate("get");
return (af_persistant_stat_info[]) resource.get_resources(client);
} |
java | public java.util.List<com.google.appengine.v1.Version> getVersionsList() {
return versions_;
} |
java | synchronized void upsertMessages(ArrayList<CTMessageDAO> inboxMessages){
if (!this.belowMemThreshold()) {
Logger.v("There is not enough space left on the device to store data, data discarded");
return;
}
//noinspection TryFinallyCanBeTryWithResources
try {
... |
python | def kamada_kawai(self,defaultEdgeWeight=None,EdgeAttribute=None,\
m_anticollisionSpringStrength=None,m_averageIterationsPerNode=None,\
m_disconnectedNodeDistanceSpringRestLength=None,\
m_disconnectedNodeDistanceSpringStrength=None,m_layoutPass=None,\
m_nodeDistanceRestLengthConstant=None,m_nodeDistanceStrengthC... |
java | public Observable<List<ApplicationInfoResponse>> listAsync(ListAppsOptionalParameter listOptionalParameter) {
return listWithServiceResponseAsync(listOptionalParameter).map(new Func1<ServiceResponse<List<ApplicationInfoResponse>>, List<ApplicationInfoResponse>>() {
@Override
public List<... |
java | @SafeVarargs
public static <T extends Model, R> Select select(TypeFunction<T, R>... functions) {
return select(
Arrays.stream(functions)
.map(AnimaUtils::getLambdaColumnName)
.collect(joining(", ")));
} |
python | def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates blank versions of the form and its inline formsets.
"""
# Prepare base
if 'pk' in kwargs:
self.object = self.get_object()
else:
self.object = None
form_clas... |
python | def submit_cookbook(self, cookbook, params={}, _extra_params={}):
"""
Submit a cookbook.
"""
self._check_user_parameters(params)
files = {'cookbook': cookbook}
return self._submit(params, files, _extra_params=_extra_params) |
java | final public void print(int i)
{
Writer out = this.out;
if (out == null)
return;
if (i == 0x80000000) {
print("-2147483648");
return;
}
try {
if (i < 0) {
out.write('-');
i = -i;
} else if (i < 9) {
out.write('0' + i);
return;
... |
java | public Options addyAxis(final Axis yAxis) {
if (this.getyAxis() == null) {
this.setyAxis(new ArrayList<Axis>());
}
this.getyAxis().add(yAxis);
return this;
} |
java | public void cacheConcept(Concept concept) {
conceptCache.put(concept.id(), concept);
if (concept.isSchemaConcept()) {
SchemaConcept schemaConcept = concept.asSchemaConcept();
schemaConceptCache.put(schemaConcept.label(), schemaConcept);
labelCache.put(schemaConcept.la... |
java | public static long getMultipartSizeProperty(Configuration conf,
String property, long defVal) {
long partSize = conf.getLongBytes(property, defVal);
if (partSize < MULTIPART_MIN_SIZE) {
LOG.warn("{} must be at least 5 MB; configured value is {}", property, partSize);
partSize = MULTIPART_MIN_S... |
java | public final void mSFIXED32() throws RecognitionException {
try {
int _type = SFIXED32;
int _channel = DEFAULT_TOKEN_CHANNEL;
// com/dyuproject/protostuff/parser/ProtoLexer.g:187:5: ( 'sfixed32' )
// com/dyuproject/protostuff/parser/ProtoLexer.g:187:9: 'sfixed32'
... |
java | private LockedObject generateTempLockedObjects(ITransaction transaction,
String path) {
if (!_tempLocks.containsKey(path)) {
LockedObject returnObject = new LockedObject(this, path, _temporary);
String parentPath = getParentPath(path);
if (parentPath != null) {
... |
java | public boolean isBaseLevelForKey(Slice userKey)
{
// Maybe use binary search to find right entry instead of linear search?
UserComparator userComparator = inputVersion.getInternalKeyComparator().getUserComparator();
for (int level = this.level + 2; level < NUM_LEVELS; level++) {
... |
python | def filter(self, criteria: Q, offset: int = 0, limit: int = 10,
order_by: list = ()) -> ResultSet:
"""
Filter objects from the repository. Method must return a `ResultSet`
object
""" |
python | def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(HostedGraphiteHandler, self).get_default_config()
config.update({
'apikey': '',
'host': 'carbon.hostedgraphite.com',
'port': 2003,
'prot... |
python | def post_process(self, xout, yout, params):
""" Transforms internal values to output, used internally. """
for post_processor in self.post_processors:
xout, yout, params = post_processor(xout, yout, params)
return xout, yout, params |
java | public static Atomic atomic(Runnable runnable) {
try {
AnimaQuery.beginTransaction();
runnable.run();
AnimaQuery.commit();
return Atomic.ok();
} catch (Exception e) {
boolean isRollback = ifReturn(
of().rollbackException.is... |
java | public static CPOptionValue fetchByC_K(long CPOptionId, String key,
boolean retrieveFromCache) {
return getPersistence().fetchByC_K(CPOptionId, key, retrieveFromCache);
} |
python | def arguments_from_signature(signature, *args, **kwargs):
"""Validate signature against `args` and `kwargs` and return the kwargs
asked for in the signature
Parameters
----------
args : Tuple[object...]
kwargs : Dict[str, object]
Returns
-------
Tuple[Tuple, Dict[str, Any]]
Ex... |
java | static public Set<String> expandFileNames(String[] filePathList)
throws SnowflakeSQLException
{
Set<String> result = new HashSet<String>();
// a location to file pattern map so that we only need to list the
// same directory once when they appear in multiple times.
Map<String, List<String>> locatio... |
java | public static String exceptionToString(Exception e)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
} |
python | def parse(self, value):
"""
Parse date
"""
value = super(DateOpt, self).parse(value)
if value is None:
return None
if isinstance(value, str):
value = self.parse_date(value)
if isinstance(value, datetime) and self.date_only:
valu... |
python | def moving_average(data, periods, type='simple'):
"""
compute a <periods> period moving average.
type is 'simple' | 'exponential'
"""
data = np.asarray(data)
if type == 'simple':
weights = np.ones(periods)
else:
weights = np.exp(np.linspace(-1., 0., periods))
weights /= ... |
java | public PagedList<HybridConnectionInner> listHybridConnections(final String resourceGroupName, final String name) {
ServiceResponse<Page<HybridConnectionInner>> response = listHybridConnectionsSinglePageAsync(resourceGroupName, name).toBlocking().single();
return new PagedList<HybridConnectionInner>(resp... |
java | @Override
public void set(final String name, final UserCredentials hostUser) throws IOException {
assert this.proxyUGI == null;
assert hostUser instanceof YarnProxyUser;
LOG.log(Level.FINE, "UGI: user {0} copy from: {1}", new Object[] {name, hostUser});
final UserGroupInformation hostUGI = ((YarnPr... |
java | protected String getTypeName(JvmType type) {
if (type != null) {
if (type instanceof JvmDeclaredType) {
final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, type);
return owner.toLightweightTypeReference(type).getHumanReadableName();
}
return type.getSimpleName();
}
ret... |
java | @Override
public EEnum getPluginType() {
if (pluginTypeEEnum == null) {
pluginTypeEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(105);
}
return pluginTypeEEnum;
} |
python | def _clean_datetime(self, obj):
"""Python objects want to be text."""
if isinstance(obj, datetime):
# if it's not naive, put it on zulu time first:
if obj.tzinfo is not None:
obj = obj.astimezone(pytz.utc)
return obj.isoformat()[:self.MAX_LENGTH]
... |
python | def add_milestone(self,
milestone,
codelistoid="MILESTONES"):
"""
Add a milestone
:param codelistoid: specify the CodeListOID (defaults to MILESTONES)
:param str milestone: Milestone to add
"""
if milestone not in self.milestone... |
java | public static RubyEnumerator<String> foreach(InputStream inputStream) {
return Ruby.Enumerator.of(new EachLineIterable(inputStream));
} |
java | public void skipUntil(final TokenType... tokenTypes) {
Set<TokenType> tokenTypeSet = Sets.newHashSet(tokenTypes);
tokenTypeSet.add(Assist.END);
while (!tokenTypeSet.contains(lexer.getCurrentToken().getType())) {
lexer.nextToken();
}
} |
java | String getSpaceIdOrThrow(CMAResource resource, String param) {
final String spaceId = resource.getSpaceId();
if (spaceId == null) {
throw new IllegalArgumentException(String.format(
"%s must have a space associated.", param));
}
return spaceId;
} |
python | def logs(self, follow=False):
"""
Get logs from this container. Every item of the iterator contains one log line
terminated with a newline. The logs are encoded (they are bytes, not str).
Let's look at an example::
image = conu.DockerImage("fedora", tag="27")
co... |
python | def end(self):
"""End of the standalone CLI."""
if not self.quiet:
self.screen.end()
# Exit from export modules
self.stats.end()
# Check Glances version versus PyPI one
if self.outdated.is_outdated():
print("You are using Glances version {}, howe... |
java | public void writeExternal(ObjectOutput out) throws IOException
{
out.writeInt(orderNumber);
byte[] data = new JCRDateFormat().serialize(value);
out.writeInt(data.length);
out.write(data);
} |
java | public Payload add(String key, String value) {
getData().put(key, value);
return this;
} |
python | def load_module(ldr, fqname):
'''Load `fqname` from under `ldr.fspath`.
The `fqname` argument is the fully qualified module name,
eg. "spam.eggs.ham". As explained above, when ::
finder.find_module("spam.eggs.ham")
is called, "spam.eggs" has already been imported and added
t... |
java | @Override
public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
throw new IllegalArgumentException("Internal error: wrong types: "
+ nodes[0].getClass().getName() + " / " + nodes[1].getClas... |
python | def factorial(N):
"""Compute the factorial of N.
If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial
"""
if N < len(FACTORIALS):
return FACTORIALS[N]
else:
from scipy import special
return int(special.factorial(N)) |
python | def id_unique(dict_id, name, lineno):
"""Returns True if dict_id not already used. Otherwise, invokes error"""
if dict_id in name_dict:
global error_occurred
error_occurred = True
print(
"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}"
.format(... |
python | def _get_content_hash(self): # type: () -> str
"""
Returns the sha256 hash of the sorted content of the pyproject file.
"""
content = self._local_config
relevant_content = {}
for key in self._relevant_keys:
relevant_content[key] = content.get(key)
c... |
python | def create_sitemap(app, exception):
"""Generates the sitemap.xml from the collected HTML page links"""
site_url = app.builder.config.site_url or app.builder.config.html_baseurl
if not site_url:
print("sphinx-sitemap error: neither html_baseurl nor site_url "
"are set in conf.py. Sitema... |
python | def gather_sorting_comparison(working_folder, ground_truths, use_multi_index=True):
"""
Loop over output folder in a tree to collect sorting from
several sorter on several dataset and returns sythetic DataFrame with
several metrics (performance, run_time, ...)
Use SortingComparison internally.... |
python | def _parse_request_method(request: web.Request):
"""Parse Access-Control-Request-Method header of the preflight request
"""
method = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_METHOD)
if method is None:
raise web.HTTPForbidden(
text="CORS preflight reques... |
python | def endpoint(value: Any) -> Any:
"""
Convert a endpoint string to the corresponding Endpoint instance type
:param value: Endpoint string or subclass
:return:
"""
if issubclass(type(value), Endpoint):
return value
elif isinstance(value, str):
for api, cls in MANAGED_API.items... |
java | void doInfo(){
this.infos.add("scanned directories: " + this.scDir);
this.infos.add("unreadable directories: " + this.scDirUnreadable);
this.infos.add("found files: " + this.scFiles);
this.infos.add("unreadable files: " + this.scFilesUnreadable);
} |
java | @Override
public FileOutputStream createOutputStream(String name, boolean append) throws IOException {
return new TaggedFileOutputStream(new File(name), append);
} |
java | public static ProgressBar getProgressBar(float value) {
ProgressBar res = new ProgressBar(value);
String style = "";
if (value > 0.75) {
style = "o-nearlyfull";
}
if (value > 0.9) {
style = "o-full";
}
res.addStyleName(style);
retu... |
python | def decode_values(fct):
''' Decode base64 encoded responses from Consul storage '''
def inner(*args, **kwargs):
''' decorator '''
data = fct(*args, **kwargs)
if 'error' not in data:
for result in data:
result['Value'] = base64.b64decode(result['Value'])
... |
java | private void createProbeSenders(ArgoClientContext context) throws TransportConfigException {
senders = new ArrayList<ProbeSender>();
if (config.usesNetworkInterface()) {
try {
for (String niName : context.getAvailableNetworkInterfaces(config.requiresMulticast())) {
try {
... |
java | private static boolean slowEquals(byte[] a, byte[] b) {
int diff = a.length ^ b.length;
for(int i = 0; i < a.length && i < b.length; i++) {
diff |= a[i] ^ b[i];
}
return diff == 0;
} |
python | def lookup(self, dotted_path, lineno=None):
"""Given a dotted path in the format ``class_name`` or
``class_name:method_name`` this performs an alias lookup. For
methods the line number must be supplied or the result is
unreliable.
"""
rv = None
try:
r... |
java | @Override
public final boolean satisfiedForFlowOrdering(final FilterOutcomes outcomes) {
if (isAlwaysSatisfiedRequirement()) {
return true;
}
final ComponentRequirement componentRequirement = _hasComponentRequirement.getComponentRequirement();
if (componentRequirement ==... |
java | @Override
public void setCenter(double x, double y, double z) {
this.cxProperty.set(x);
this.cyProperty.set(y);
this.czProperty.set(z);
} |
java | protected Statement methodInvoker(FrameworkMethod method, Object test) {
return new ParameterizedInvokeMethod(method, test, methodArgs);
} |
python | def _execute_commands_from_dir(self, directory):
"""Re-attempt to split and execute the failed commands"""
# Get file paths and contents
commands = get_commands_from_dir(directory)
# Execute failed commands again
print('\tAttempting to execute {0} failed commands'.format(len(com... |
python | def ruleName(self):
''' overrides from parent class '''
return _('%s at %s' % (self.room.name, self.room.location.name)) |
python | def _bse_cli_get_basis(args):
'''Handles the get-basis subcommand'''
return api.get_basis(
name=args.basis,
elements=args.elements,
version=args.version,
fmt=args.fmt,
uncontract_general=args.unc_gen,
uncontract_spdf=args.unc_spdf,
uncontract_segmented=ar... |
java | private File getProjectDir(String projectId, boolean create) throws IOException {
File projectDir = new File(getKeenCacheDirectory(), projectId);
if (create && !projectDir.exists()) {
KeenLogging.log("Cache directory for project '" + projectId + "' doesn't exist. " +
"Cre... |
java | public List<UserDto> selectByOrderedLogins(DbSession session, Collection<String> logins) {
List<UserDto> unordered = selectByLogins(session, logins);
return logins.stream()
.map(new LoginToUser(unordered))
.filter(Objects::nonNull)
.collect(Collectors.toList());
} |
python | def get_ssid(_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n313.
Positional arguments:
data -- bytearray data to read.
Returns:
String.
"""
converted = list()
for i in range(len(data)):
try:
c = unichr(data[i])
ex... |
java | public static Specification<JpaTarget> hasTags(final String[] tagNames, final Boolean selectTargetWithNoTag) {
return (targetRoot, query, cb) -> {
final Predicate predicate = getPredicate(targetRoot, cb, selectTargetWithNoTag, tagNames);
query.distinct(true);
return predicate... |
java | private void initComponents() {
fileLabel = new JLabel();
fileTextField = new ZapTextField();
browseButton = new JButton();
nameLabel = new JLabel();
nameTextField = new ZapTextField();
slotLabel = new JLabel();
slotTextField = new ZapTextField();
slotListIndexLabel = new JLabel();
slotListIndexTextFi... |
python | def autosave(self, index):
"""
Autosave a file.
Do nothing if the `changed_since_autosave` flag is not set or the file
is newly created (and thus not named by the user). Otherwise, save a
copy of the file with the name given by `self.get_autosave_filename()`
and clear th... |
python | def get_cmdclass():
''' A ``cmdclass`` that works around a setuptools deficiency.
There is no need to build wheels when installing a package, however some
versions of setuptools seem to mandate this. This is a hacky workaround
that modifies the ``cmdclass`` returned by versioneer so that not having
... |
python | def get_current_live_chat(self):
""" Check if there is a live chat on the go, so that we should take
over the AskMAMA page with the live chat.
"""
now = datetime.now()
chat = self.upcoming_live_chat()
if chat and chat.is_in_progress():
return chat
... |
java | @Override
public String getNarInfoFile(final String groupId, final String artifactId, final String type) {
return "META-INF/nar/" + groupId + "/" + artifactId + "/" + NarInfo.NAR_PROPERTIES;
} |
python | def prepare(self, request):
"""
Performs any preparations necessary for the Format.
:param request: The webob Request object describing the
request.
:returns: A list of dictionary values needed by the convert()
method.
"""
data... |
java | public ServiceFuture<OpenShiftManagedClusterInner> beginUpdateTagsAsync(String resourceGroupName, String resourceName, final ServiceCallback<OpenShiftManagedClusterInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateTagsWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallbac... |
python | def login(self, request, session, creds, segments):
"""
Called to check the credentials of a user.
Here we extend guard's implementation to preauthenticate users if they
have a valid persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP re... |
python | def eps(self, nodeids=None):
"""
Return the EPs with the given *nodeid*, or all EPs.
Args:
nodeids: an iterable of nodeids of EPs to return; if
`None`, return all EPs
"""
if nodeids is None: nodeids = self._nodeids
_eps = self._eps
ret... |
python | def _get_colors(self,
name):
"""
A magical function which maintains the sanity of vertex and face colors.
* If colors have been explicitly stored or changed, they are considered
user data, stored in self._data (DataStore), and are returned immediately
when re... |
java | public CouchDbConnector createConnector() {
val connector = new StdCouchDbConnector(couchDbProperties.getDbName(), getCouchDbInstance(), objectMapperFactory);
LOGGER.debug("Connector created: [{}]", connector);
return connector;
} |
java | protected Document getWebXmlDocument(String baseDir)
throws ParserConfigurationException, FactoryConfigurationError,
SAXException, IOException {
File webXml = new File(baseDir, WEB_XML_FILE_PATH);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
docBuilder.setEnti... |
python | def _asym_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
eta,
intercept_params,
shape_ref_position=None,
intercept_ref_pos=None,
... |
java | public void createRTreeIndex(String tableName, String geometryColumnName) {
String sqlName = GeoPackageProperties.getProperty(SQL_PROPERTY,
CREATE_PROPERTY);
executeSQL(sqlName, tableName, geometryColumnName);
} |
java | public Observable<ServiceResponse<PacketCaptureQueryStatusResultInner>> beginGetStatusWithServiceResponseAsync(String resourceGroupName, String networkWatcherName, String packetCaptureName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required... |
java | public void typeMissing() {
this.parameterMissing(
ProtocolConstants.Parameters.Delete.TYPE,
"Please provide the type of the delete request. Use \""
+ DeleteRequestType.USER.getIdentifier()
+ "\" to delete a user, \""
+ DeleteRequestType.FOLLOW.getIdentifier()
+ "\" to delete a follow ... |
python | def load_sgf(self, sgf_data):
"""Load, persist a sensor_graph file.
The data passed in `sgf_data` can either be a path or the already
loaded sgf lines as a string. It is determined to be sgf lines if
there is a '\n' character in the data, otherwise it is interpreted as
a path.
... |
python | def _cram_to_fastq_regions(regions, cram_file, dirs, data):
"""Convert CRAM files to fastq, potentially within sub regions.
Returns multiple fastq files that can be merged back together.
"""
base_name = utils.splitext_plus(os.path.basename(cram_file))[0]
work_dir = utils.safe_makedir(os.path.join(d... |
python | def setJoiner(self, joiner):
"""
Sets the join operator type for this entry widget to the given value.
:param joiner | <QueryCompound.Op>
"""
text = QueryCompound.Op[joiner].upper()
if self._first:
if self._last:
... |
python | def bench(client, n):
""" Benchmark n requests """
items = list(range(n))
# Time client publish operations
# ------------------------------
started = time.time()
for i in items:
client.publish('test', i)
duration = time.time() - started
print('Publisher client stats:')
util... |
python | def normalize_residuals(self, points):
"""Normalize residuals by the level of the variable."""
residuals = self.evaluate_residual(points)
solutions = self.evaluate_solution(points)
return [resid / soln for resid, soln in zip(residuals, solutions)] |
java | public static void setPreferredAttributeNameForRoadNumber(String name) {
final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class);
if (prefs != null) {
if (name == null || "".equals(name) || DEFAULT_ATTR_ROAD_NUMBER.equalsIgnoreCase(name)) { //$NON-NLS-1$
prefs.remove("ROAD_NUMBER... |
java | public VaultExtendedInfoResourceInner createOrUpdate(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, resourceResourceExtendedInfoDetails).toBlocking().single().body();
... |
java | public Observable<ServiceResponse<IssuerBundle>> setCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName, String provider) {
if (vaultBaseUrl == null) {
throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null.");
}
if (iss... |
python | def tags(self):
'''List tags (py_version, abi, platform) supported by this wheel.'''
return itertools.product(
self.py_version.split('.'),
self.abi.split('.'),
self.platform.split('.'),
) |
java | private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
try {
s.defaultReadObject();
this.queue = new Object[q.size()];
comparator = q.comparator();
addAll(q);
} finally {
q = null;
... |
python | def get_serializer(self, *args, **kwargs):
""" if an array is passed, set serializer to many """
if isinstance(kwargs.get('data', {}), list):
kwargs['many'] = True
return super().get_serializer(*args, **kwargs) |
java | public static appfwlearningsettings[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{
appfwlearningsettings obj = new appfwlearningsettings();
options option = new options();
option.set_filter(filter);
appfwlearningsettings[] response = (appfwlearningsettings[]) obj.getfiltered(servi... |
java | public void marshall(DescribeProvisioningArtifactRequest describeProvisioningArtifactRequest, ProtocolMarshaller protocolMarshaller) {
if (describeProvisioningArtifactRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
pr... |
java | private void handleDataAvailable() {
InputStream inputStream = serialPort.getInputStream();
try {
while (inputStream.available() > 0) {
byte inputByte = (byte) inputStream.read();
if (inputByte == -1) {
log.error("Reached end of stream try... |
python | def set_static_ip_address(self, context, msg):
"""Process request for setting rules in iptables.
In cases that static ip address is assigned for a VM, it is needed
to update the iptables rule for that address.
"""
args = jsonutils.loads(msg)
macaddr = args.get('mac')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.