language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public IfcElectricTimeControlTypeEnum createIfcElectricTimeControlTypeEnumFromString(EDataType eDataType,
String initialValue) {
IfcElectricTimeControlTypeEnum result = IfcElectricTimeControlTypeEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '" + initialVa... |
java | public EClass getIfcTextFontName() {
if (ifcTextFontNameEClass == null) {
ifcTextFontNameEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(747);
}
return ifcTextFontNameEClass;
} |
python | def read_bom(data):
"""Read the byte order mark in the text, if present, and
return the encoding represented by the BOM and the BOM.
If no BOM can be detected, (None, None) is returned.
"""
# common case is no BOM, so this is fast
if data and data[0] in _FIRST_CHARS:
for bom, encoding i... |
python | def convert_odt_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object.
"""
# We can't use exactly the same metho... |
java | public boolean process(ContentEvent event) {
// distinguish between ClusteringContentEvent and ClusteringEvaluationContentEvent
if (event instanceof ClusteringContentEvent) {
ClusteringContentEvent cce = (ClusteringContentEvent) event;
outputStream.put(event);
if (cce... |
java | public static Boolean evaluateAsBoolean(Node node, String xPathExpression, NamespaceContext nsContext) {
return (Boolean) evaluateExpression(node, xPathExpression, nsContext, XPathConstants.BOOLEAN);
} |
python | def extract_bytes(mv):
"""Retrieve bytes out of memoryview/buffer or bytes."""
if isinstance(mv, memoryview):
return mv.tobytes() if six.PY3 else bytes(mv)
if isinstance(mv, bytes):
return mv
raise ValueError |
java | public PaymillList<Payment> list( Payment.Filter filter, Payment.Order order, Integer count, Integer offset ) {
return RestfulUtils.list( PaymentService.PATH, filter, order, count, offset, Payment.class, super.httpClient );
} |
java | public static String getErrorResult(Process process, Charset charset) {
InputStream in = null;
try {
in = process.getErrorStream();
return IoUtil.read(in, charset);
} finally {
IoUtil.close(in);
destroy(process);
}
} |
java | @Override
public void visitInnerClasses(InnerClasses obj) {
super.visitInnerClasses(obj);
InnerClass[] inner_classes = obj.getInnerClasses();
for (InnerClass inner_class : inner_classes) {
inner_class.accept(this);
}
} |
java | public void setupKeys()
{
KeyAreaInfo keyArea = null;
keyArea = new KeyAreaInfo(this, Constants.UNIQUE, ID_KEY);
keyArea.addKeyField(ID, Constants.ASCENDING);
keyArea = new KeyAreaInfo(this, Constants.NOT_UNIQUE, START_DATE_TIME_KEY);
keyArea.addKeyField(START_DATE_TIME, Cons... |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case XtextPackage.NAMED_ARGUMENT__PARAMETER:
setParameter((Parameter)null);
return;
case XtextPackage.NAMED_ARGUMENT__VALUE:
setValue((Condition)null);
return;
case XtextPackage.NAMED_ARGUMENT__CALLED_BY_NAME:
setCalledBy... |
python | def add(self, properties):
"""
Add a faked NIC resource.
Parameters:
properties (dict):
Resource properties.
Special handling and requirements for certain properties:
* 'element-id' will be auto-generated with a unique value across
... |
python | def find_all_by_parameters(self, task_name, session=None, **task_params):
"""
Find tasks with the given task_name and the same parameters as the kwargs.
"""
with self._session(session) as session:
query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == tas... |
python | def angle_solver(AA, timeseries, N_max, sign, symNx = 2, throw_out_modes=False):
""" Constructs the matrix A and the vector b from a timeseries of toy
action-angles AA to solve for the vector x = (theta_0,theta_1,theta_2,omega_1,
omega_2,omega_3, dSdx..., dSdy..., dSdz...) where x contains all derivatives
... |
java | Field dereference(Field self, String field) {
if (field.startsWith("[") && field.endsWith("]")) {
field = field.substring(1, field.length() - 1);
}
Type type = protoTypeNames.get(self.type().toString());
if (type instanceof MessageType) {
MessageType messageType = (MessageType) type;
... |
java | public T withSerialConsistencyLevel(ConsistencyLevel serialConsistencyLevel) {
getOptions().setSerialCL(Optional.of(serialConsistencyLevel));
return getThis();
} |
python | def known(self, object):
""" get the type specified in the object's metadata """
try:
md = object.__metadata__
known = md.sxtype
return known
except:
pass |
java | public String formatDurationUnrounded(Date then)
{
Duration duration = approximateDuration(then);
return formatDurationUnrounded(duration);
} |
java | public static TimeBasedKeys create( int bitsUsedInCounter ) {
CheckArg.isPositive(bitsUsedInCounter, "bitsUsedInCounter");
int maxAvailableBitsToShift = Long.numberOfLeadingZeros(System.currentTimeMillis());
CheckArg.isLessThan(bitsUsedInCounter, maxAvailableBitsToShift, "bitsUsedInCounter");
... |
java | public static List<String> getManagableOUs(CmsObject cms) {
List<String> ous = new ArrayList<String>();
try {
for (CmsRole role : OpenCms.getRoleManager().getRolesOfUser(
cms,
cms.getRequestContext().getCurrentUser().getName(),
"",
... |
python | def partymode(self):
"""Put all the speakers in the network in the same group, a.k.a Party
Mode.
This blog shows the initial research responsible for this:
http://blog.travelmarx.com/2010/06/exploring-sonos-via-upnp.html
The trick seems to be (only tested on a two-speaker setup... |
java | public Project.Resources.Resource.Rates.Rate createProjectResourcesResourceRatesRate()
{
return new Project.Resources.Resource.Rates.Rate();
} |
java | public ConstraintValidatorFactory getConstraintValidatorFactoryOverride(Configuration<?> config) {
ValidationReleasable<ConstraintValidatorFactory> releasable = null;
String cvfClassName = config.getBootstrapConfiguration().getConstraintValidatorFactoryClassName();
// If the validation.xml Cons... |
java | public static boolean isIgnorableInternalName(String className) {
return (className.startsWith("[", 0)
|| className.startsWith(JAVA_VM, 0)
|| className.startsWith(JAVAX_VM, 0)
|| className.startsWith(JDK_VM, 0)
|| className.startsWith(SUN_VM, 0)
... |
python | def as_dict(self, depth=0):
"""Return a dictionary containing only the attributes which map to
an instance's database columns.
:param int depth: Maximum depth to recurse subobjects
:rtype: dict
"""
result_dict = {}
for column in self.__table__.columns.keys():
... |
python | def image(random=random, width=800, height=600, https=False, *args, **kwargs):
"""
Generate the address of a placeholder image.
>>> mock_random.seed(0)
>>> image(random=mock_random)
'http://dummyimage.com/800x600/292929/e3e3e3&text=mighty poop'
>>> image(random=mock_random, width=60, height=60)... |
java | public QueryContext with( Problems problems ) {
return new QueryContext(context, repositoryCache, workspaceNames, overriddenNodeCachesByWorkspaceName, schemata,
indexDefns, nodeTypes, bufferManager, hints, problems, variables);
} |
python | def expand_query(config, kwds):
"""
Expand `kwds` based on `config.search.query_expander`.
:type config: .config.Configuration
:type kwds: dict
:rtype: dict
:return: Return `kwds`, modified in place.
"""
pattern = []
for query in kwds.pop('pattern', []):
expansion = config.... |
java | public static Map<String, Integer> getGeometryTypes(Connection connection, TableLocation location)
throws SQLException {
Map<String, Integer> map = new HashMap<>();
ResultSet geomResultSet = getGeometryColumnsView(connection,location.getCatalog(),location.getSchema(),
locatio... |
java | public final CompletableFuture<Integer> send(Object message, boolean last) {
return send(false, message, last);
} |
java | public Object getObject(int index)
{
try (InputStream is = openInputStream(index)) {
if (is == null) {
return null;
}
try (InH3 in = serializer().in(is)) {
return in.readObject();
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Excep... |
java | @Override
public int getCacheIdsHashcodeInPushPullTable(boolean debug) {
final String methodName = "getCacheIdsHashcodeInPushPullTable()";
if (this.featureSupport.isReplicationSupported()) {
// TODO write code to support getCacheIdsHashcodeInPushPullTable function
if (tc.isDe... |
python | def getAllData(self, temp = True, accel = True, gyro = True):
"""!
Get all the available data.
@param temp: True - Allow to return Temperature data
@param accel: True - Allow to return Accelerometer data
@param gyro: True - Allow to return Gyroscope data
@return a dicti... |
java | @Bean
public BraveModule braveModule() {
String serviceName = "exampleApp";
Endpoint localEndpoint = Endpoint.builder().serviceName(serviceName).build();
InheritableServerClientAndLocalSpanState spanState = new InheritableServerClientAndLocalSpanState(localEndpoint);
Brave.Builder builder = new Brave.Builder(s... |
java | public Response updateItems( HttpServletRequest request,
String repositoryName,
String workspaceName,
String requestContent ) throws JSONException, RepositoryException {
JSONObject requestBody = stringToJSONObject... |
java | public void removeStickyFooterItemAtPosition(int position) {
if (mDrawerBuilder.mStickyDrawerItems != null && mDrawerBuilder.mStickyDrawerItems.size() > position) {
mDrawerBuilder.mStickyDrawerItems.remove(position);
}
DrawerUtils.rebuildStickyFooterView(mDrawerBuilder);
} |
python | def sanitize_html(value, valid_tags=VALID_TAGS, strip=True):
"""
Strips unwanted markup out of HTML.
"""
return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip) |
python | def save_file(self, filename, text):
"""Save the given text under the given control filename and the
current path."""
if not filename.endswith('.py'):
filename += '.py'
path = os.path.join(self.currentpath, filename)
with open(path, 'w', encoding="utf-8") as file_:
... |
java | protected void bindClass(PersistentEntity domainClass, PersistentClass persistentClass, InFlightMetadataCollector mappings) {
// set lazy loading for now
persistentClass.setLazy(true);
final String entityName = domainClass.getName();
persistentClass.setEntityName(entityName);
pe... |
python | def get_shard_stats(self):
"""
:return: get stats for this mongodb shard
"""
return requests.get(self._stats_url, params={'include_stats': True},
headers={'X-Auth-Token': self._client.auth._token}
).json()['data']['stats'] |
java | public static boolean isAvailable() throws Exception {
try {
Registry myRegistry = LocateRegistry.getRegistry("127.0.0.1", port);
com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);
return tru... |
python | async def check_user(self, request, func=None, location=None, **kwargs):
"""Check for user is logged and pass the given func.
:param func: user checker function, defaults to default_user_checker
:param location: where to redirect if user is not logged in.
May be either string (URL) ... |
java | public void setFpgaImageIds(java.util.Collection<String> fpgaImageIds) {
if (fpgaImageIds == null) {
this.fpgaImageIds = null;
return;
}
this.fpgaImageIds = new com.amazonaws.internal.SdkInternalList<String>(fpgaImageIds);
} |
java | public static <L, R> @NonNull Pair<L, R> of(final @Nullable L left, final @Nullable R right) {
return new Pair<>(left, right);
} |
python | def write_gtiff_file(f_name, n_rows, n_cols, data, geotransform, srs, nodata_value,
gdal_type=GDT_Float32):
"""Output Raster to GeoTiff format file.
Args:
f_name: output gtiff file name.
n_rows: Row count.
n_cols: Col count.
data:... |
java | public void setListeners(Collection<IWebSocketDataListener> listeners) {
log.trace("setListeners: {}", listeners);
this.listeners.addAll(listeners);
} |
python | def flatten_list(lobj):
"""
Recursively flattens a list.
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
ret = []
for item in lobj:
... |
java | public void marshall(DeleteProjectRequest deleteProjectRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteProjectRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteProjectReques... |
python | def get_new_messages(self, domain):
"""
Returns new valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'new' not in... |
java | protected List<SchemaDescriptor> scanConnection(String url, String user, String password, String infoLevelName, String bundledDriverName,
Properties properties, Store store) throws IOException {
LOGGER.info("Scanning schema '{}'", url);
Catalog catalog... |
python | def idle_all_workers(self):
'''Set the global mode to :attr:`IDLE` and wait for workers to stop.
This can wait arbitrarily long before returning. The worst
case in "normal" usage involves waiting five minutes for a
"lost" job to expire; a well-behaved but very-long-running job
... |
python | def check_lengths(*arrays):
"""
tool to ensure input and output data have the same number of samples
Parameters
----------
*arrays : iterable of arrays to be checked
Returns
-------
None
"""
lengths = [len(array) for array in arrays]
if len(np.unique(lengths)) > 1:
... |
java | public List<String> getVariableNames() {
return variables.asList().stream() //
.map(TemplateVariable::getName) //
.collect(Collectors.toList());
} |
python | def _get_data_segments(channels, start, end, connection):
"""Get available data segments for the given channels
"""
allsegs = io_nds2.get_availability(channels, start, end,
connection=connection)
return allsegs.intersection(allsegs.keys()) |
python | def alterar(self, id_perm, id_permission, read, write, id_group):
"""Change Administrative Permission from by the identifier.
:param id_perm: Identifier of the Administrative Permission. Integer value and greater than zero.
:param id_permission: Identifier of the Permission. Integer value and g... |
python | def color_cycle(colors=None):
"""An infinite iterator of the given (or default) colors
"""
if colors:
return itertools.cycle(colors)
try:
return itertools.cycle(p["color"] for p in rcParams["axes.prop_cycle"])
except KeyError: # matplotlib < 1.5
return itertools.cycle(rcPara... |
java | @Override
public BlockingMessage createBLO() {
BlockingMessageImpl blo = new BlockingMessageImpl(_BLO_HOLDER.mandatoryCodes, _BLO_HOLDER.mandatoryVariableCodes,
_BLO_HOLDER.optionalCodes, _BLO_HOLDER.mandatoryCodeToIndex, _BLO_HOLDER.mandatoryVariableCodeToIndex,
_BLO_HOLDER.... |
java | public synchronized Object lastKey(Transaction transaction)
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"lastKey",
new Object[] {... |
python | def write_cell(self, x, y, value, style=None):
"""
writing style and value in the cell of x and y position
"""
if isinstance(style, str):
style = self.xlwt.easyxf(style)
if style:
self._sheet.write(x, y, label=value, style=style)
else:
... |
java | public void moveItem(int start, int end){
M startItem = filteredItems.get(start);
M endItem = filteredItems.get(end);
int realStart = items.indexOf(startItem);
int realEnd = items.indexOf(endItem);
Collections.swap(items, realStart, realEnd);
applyFilter();
onI... |
java | @Override
public ConsumableKey attachToDurableSubscription(
LocalConsumerPoint consumerPoint,
ConsumerDispatcherState subState)
throws SIDurableSubscriptionMismatchException, SIDurableSubscr... |
java | public static ShardedJedisPool newShardedJedisPool(JedisPoolConfig poolConfig,
String hostsAndPorts, int timeoutMs) {
return newShardedJedisPool(poolConfig, hostsAndPorts, null, timeoutMs);
} |
python | def _map(self, data_item):
"Map ``data_item`` separately in each thread."
delegate = self.delegate
logger.debug(f'mapping: {data_item}')
if self.clobber or not self.exists(data_item.id):
logger.debug(f'exist: {data_item.id}: {self.exists(data_item.id)}')
delegate.... |
java | public boolean add(WeightedDirectedTypedEdge<T> e) {
if (e.from() == rootVertex) {
Set<WeightedDirectedTypedEdge<T>> edges = outEdges.get(e.to());
if (edges.contains(e))
return false;
// We can't rely on the edge's equality method since that uses the
... |
python | def _restore_file(path, delete_backup=True):
"""
Restore a file if it exists and remove the backup
"""
backup_base = '/var/local/woven-backup'
backup_path = ''.join([backup_base,path])
if exists(backup_path):
if delete_backup:
sudo('mv -f %s %s'% (backup_path,path))
e... |
python | def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is already the same.
"""
if self.format == format:
return self
else:
image = Image(self.pil_image)
image._format = format
... |
java | public Login login(TokenResult token, String username, String password)
throws Exception {
return login(token, username, password, null);
} |
python | def normalize_list(text):
"""
Get a list of word stems that appear in the text. Stopwords and an initial
'to' will be stripped, unless this leaves nothing in the stem.
>>> normalize_list('the dog')
['dog']
>>> normalize_list('big dogs')
['big', 'dog']
>>> normalize_list('the')
['the... |
python | def getCandScoresMap(self, profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
Bucklin score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to conta... |
java | public Set<BugPattern> getReportedBugPatterns() {
Set<BugPattern> result = new TreeSet<>();
StringTokenizer tok = new StringTokenizer(reports, ",");
while (tok.hasMoreTokens()) {
String type = tok.nextToken();
BugPattern bugPattern = DetectorFactoryCollection.instance().l... |
java | public static <S, SS extends S, T, TT extends T> Tuple2<S, T> of(SS s, TT t)
{
return new Tuple2<S, T>(s, t);
} |
python | def Message(self, text):
"""Inform about what we are doing right now, e.g.
'Checking for SOMETHING ... '
"""
self.Display(text)
self.sconf.cached = 1
self.did_show_result = 0 |
python | def close(self):
"""
Collects the result from the workers and closes the thread pool.
"""
self.pool.close()
self.pool.terminate()
self.pool.join() |
java | public static final Function<String,Short> toShort(final RoundingMode roundingMode, final DecimalPoint decimalPoint) {
return new ToShort(roundingMode, decimalPoint);
} |
java | public String get(Context context, String url) {
final Cursor cursor = context.getContentResolver().query(getUri(OfflinerDBHelper.TABLE_CACHE),
OfflinerDBHelper.PARAMS_CACHE, OfflinerDBHelper.REQUEST_URL
+ " = '" + url + "'", null, null);
String result = null;
... |
java | @Override
public long dynamicQueryCount(DynamicQuery dynamicQuery,
Projection projection) {
return cpDefinitionGroupedEntryPersistence.countWithDynamicQuery(dynamicQuery,
projection);
} |
java | public ApiResponse<Float> postCharactersCharacterIdCspaWithHttpInfo(Integer characterId, List<Integer> requestBody,
String datasource, String token) throws ApiException {
com.squareup.okhttp.Call call = postCharactersCharacterIdCspaValidateBeforeCall(characterId, requestBody,
datasou... |
java | public void close()
{
synchronized (closeLock)
{
if (closed)
return;
closed = true;
}
synchronized (this)
{
Iterator<T> allObjects = all.iterator();
while (allObjects.hasNext())
{
T poolObject = allObjects.next();
internalDestroyPoolObject(poolObject);
}
all.clear();... |
python | def set_security_groups(mounttargetid,
securitygroup,
keyid=None,
key=None,
profile=None,
region=None,
**kwargs):
'''
Modifies the set of security groups in effect for ... |
java | private void overrideAbstractMethods() throws IOException
{
for (final ExecutableElement method : El.getEffectiveMethods(superClass))
{
if (method.getModifiers().contains(Modifier.ABSTRACT))
{
if (
method.getAnnotation(Terminal.c... |
java | public ServiceFuture<List<SecretItem>> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName, final Integer maxresults, final ListOperationCallback<SecretItem> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName... |
java | public Response setTags(String photoId, List<String> tags) throws JinxException {
JinxUtils.validateParams(photoId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.setTags");
params.put("photo_id", photoId);
if (tags == null || tags.size() == 0) {
params.put(... |
python | def StartTiming(self, profile_name):
"""Starts timing CPU time.
Args:
profile_name (str): name of the profile to sample.
"""
if profile_name not in self._profile_measurements:
self._profile_measurements[profile_name] = CPUTimeMeasurement()
self._profile_measurements[profile_name].Sampl... |
python | def _register_key(fingerprint, gpg):
"""Registers key in config"""
for private_key in gpg.list_keys(True):
try:
if str(fingerprint) == private_key['fingerprint']:
config["gpg_key_fingerprint"] = \
repr(private_key['fingerprint'])
except KeyError:
... |
python | def _pyxb_from_perm_dict(self, perm_dict):
"""Return an AccessPolicy PyXB representation of ``perm_dict``
- If ``norm_perm_list`` is empty, None is returned. The schema does not allow
AccessPolicy to be empty, but in SystemMetadata, it can be left out
altogether. So returning None inste... |
python | def swapoff(name):
'''
Deactivate a named swap mount
.. versionchanged:: 2016.3.2
CLI Example:
.. code-block:: bash
salt '*' mount.swapoff /root/swapfile
'''
on_ = swaps()
if name in on_:
if __grains__['kernel'] == 'SunOS':
if __grains__['virtual'] != 'zon... |
java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLLiteralImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} |
python | def get_top_headlines(self, q=None, sources=None, language='en', country=None, category=None, page_size=None,
page=None):
"""
Returns live top and breaking headlines for a country, specific category in a country, single source, or multiple sources..
Optional pa... |
java | public <T> T get(Class<T> type) {
return get(type.getName(), type);
} |
java | public Connection getConnection() throws SQLException {
try {
return new DrizzleConnection(new MySQLProtocol(hostname, port, database, null, null, new Properties()),
new DrizzleQueryFactory());
} catch (QueryException e) {
throw SQLExceptionMapper.get(e);
... |
python | def request(self, path, data=None, method='GET'):
""" Convenience Facebook request function.
Utility function to request resources via the graph API, with the
format expected by Facebook.
"""
url = '%s%s?access_token=%s' % (
'https://graph.facebook.com',
... |
python | def sizes(self, fileids=None) -> Generator[int, int, None]:
"""
Returns a list of tuples, the fileid and size on disk of the file.
This function is used to detect oddly large files in the corpus.
"""
if not fileids:
fileids = self.fileids()
# Create a generato... |
java | public final static void appendMailto(final StringBuilder out, final String in, final int start, final int end)
{
for (int i = start; i < end; i++)
{
final char c;
final int r = rnd();
switch (c = in.charAt(i))
{
case '&':
case ... |
java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
br_enable_responses result = (br_enable_responses) service.get_payload_formatter().string_to_resource(br_enable_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESS... |
python | def overlays_at(self, key):
"""
Key may be a slice or a point.
"""
if isinstance(key, slice):
s, e, _ = key.indices(len(self.text))
else:
s = e = key
return [o for o in self.overlays if o.start in Rng(s, e)] |
python | def names(cls):
"""A list of all emoji names without file extension."""
if not cls._files:
for f in os.listdir(cls._image_path):
if(not f.startswith('.') and
os.path.isfile(os.path.join(cls._image_path, f))):
cls._files.append(os.path.sp... |
java | public void onFailure() throws InterruptedException {
int val = currentFailureCount.incrementAndGet();
if (val > 50) {
currentFailureCount.compareAndSet(val, MAX_FAILURE_COUNT);
val = MAX_FAILURE_COUNT;
}
int delay = MIN_DELAY + ((MAX_DELAY - MIN_DELAY) / MAX_FAI... |
python | def try_recv(self):
"""Return None immediately if nothing is waiting"""
try:
lenstr = self.sock.recv(4, socket.MSG_DONTWAIT)
except socket.error:
return None
if len(lenstr) < 4:
raise EOFError("Socket closed")
length = struct.unpack("<I", lenst... |
python | def check_support_cyclic_msg(cls, hw_info_ex):
"""
Checks whether the module supports automatically transmission of cyclic CAN messages.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.