language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static CPRule findByGroupId_Last(long groupId,
OrderByComparator<CPRule> orderByComparator)
throws com.liferay.commerce.product.exception.NoSuchCPRuleException {
return getPersistence().findByGroupId_Last(groupId, orderByComparator);
} |
python | def get_obj_name(obj, full=True):
""" Gets the #str name of @obj
@obj: any python object
@full: #bool returns with parent name as well if True
-> #str object name
..
from redis_structures.debug import get_parent_obj
get_obj_name(get_obj_name)
# ... |
python | def make_spo(sub, prd, obj):
'''
Decorates the three given strings as a line of ntriples
'''
# To establish string as a curie and expand,
# we use a global curie_map(.yaml)
# sub are allways uri (unless a bnode)
# prd are allways uri (unless prd is 'a')
# should fail loudly if curie do... |
java | public static boolean isAllAssignableFrom(Class<?>[] types1, Class<?>[] types2) {
if (ArrayUtil.isEmpty(types1) && ArrayUtil.isEmpty(types2)) {
return true;
}
if (null == types1 || null == types2) {
// 任何一个为null不相等(之前已判断两个都为null的情况)
return false;
}
if (types1.length != types2.length) {
re... |
java | public Observable<ServiceResponse<Page<FileInner>>> listOutputFilesWithServiceResponseAsync(final String resourceGroupName, final String workspaceName, final String experimentName, final String jobName, final JobsListOutputFilesOptions jobsListOutputFilesOptions) {
return listOutputFilesSinglePageAsync(resource... |
java | void passfg(final int nac[], final int ido, final int ip, final int l1, final int idl1, final float in[], final int in_off, final float out[], final int out_off, final int offset, final int isign) {
int idij, idlj, idot, ipph, l, jc, lc, idj, idl, inc, idp;
float w1r, w1i, w2i, w2r;
int iw1;
iw1 = offset;
id... |
java | public static String extractMetricName(String[] strs) {
if (strs.length < 6) return null;
return strs[strs.length - 1];
} |
java | public <T> void putCustom(String key, T value) {
custom.put(key, value);
} |
python | def send_msg(self, chat_id, msg_type, **kwargs):
""" deprecated, use `send` instead """
return self.send(chat_id, msg_type, **kwargs) |
python | def _get_valid_stan_args(base_args=None):
"""Fill in default values for arguments not provided in `base_args`.
RStan does this in C++ in stan_args.hpp in the stan_args constructor.
It seems easier to deal with here in Python.
"""
args = base_args.copy() if base_args is not None else {}
# Defau... |
java | static String[] getServersFromURL(String url) {
// get everything between the prefix and the ?
String prefix = URL_PREFIX + "//";
int end = url.length();
if (url.indexOf("?") > 0) {
end = url.indexOf("?");
}
String servstring = url.substring(prefix.length(), e... |
java | public static double sabrBerestyckiNormalVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity)
{
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
strike += displ... |
java | private void complete(Subscriber<? super T> subscriber) {
if (!subscriber.isUnsubscribed()) {
debug("onCompleted");
subscriber.onCompleted();
} else
debug("unsubscribed");
} |
python | def attribute_crawl(self, key):
"""
Grab all attribute values associated with the given feature.
Traverse the given feature (and all of its descendants) to find all
values associated with the given attribute key.
>>> import tag
>>> reader = tag.GFF3Reader(tag.pkgdata('o... |
java | public void setProjectsNotFound(java.util.Collection<String> projectsNotFound) {
if (projectsNotFound == null) {
this.projectsNotFound = null;
return;
}
this.projectsNotFound = new java.util.ArrayList<String>(projectsNotFound);
} |
python | def token_getter(provider, token=None):
""" Generic token getter for all the providers """
session_key = provider + '_token'
if token is None:
token = session.get(session_key)
return token |
python | def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None |
python | def is_valid_transition(self, source: str, dest: str) -> bool:
"""
Checks if a transitions is registered in the FSM
Args:
source (str): the source state name
dest (str): the destination state name
Returns:
bool: wether the transition is valid or not
... |
java | @Override
public CreatePermissionResult createPermission(CreatePermissionRequest request) {
request = beforeClientExecution(request);
return executeCreatePermission(request);
} |
python | def buy_item(self, item_name, abbr):
url = 'https://www.duolingo.com/2017-06-30/users/{}/purchase-store-item'
url = url.format(self.user_data.id)
data = {'name': item_name, 'learningLanguage': abbr}
request = self._make_req(url, data)
"""
status code '200' indicates tha... |
java | public static void generateTarGz(String src, String target) throws IOException {
File sourceDirectory = new File(src);
File destinationArchive = new File(target);
String sourcePath = sourceDirectory.getAbsolutePath();
FileOutputStream destinationOutputStream = new FileOutputStream(destinationArchive);
TarAr... |
java | @Override
public void add(final int index, final SyndCategory obj) {
final SyndCategoryImpl sCat = (SyndCategoryImpl) obj;
DCSubject subject;
if (sCat != null) {
subject = sCat.getSubject();
} else {
subject = null;
}
subjects.add(index, subjec... |
python | def _map_trajectory(self):
""" Return filepath as a class attribute"""
self.trajectory_map = {}
with open(self.filepath, 'r') as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) ... |
python | def _serialize_model_helper(self, model, field_dict=None):
"""
A recursive function for serializing a model
into a json ready format.
"""
field_dict = field_dict or self.dot_field_list_to_dict()
if model is None:
return None
if isinstance(model, Query... |
java | public static Geometry computeShadow(Geometry geometry, double azimuth, double altitude, double height, boolean doUnion) {
if (geometry == null) {
return null;
}
if (height <= 0) {
throw new IllegalArgumentException("The height of the geometry must be greater than 0.");
... |
java | public List<DetailParam> getParameterFromMethodWithAnnotation(Class<?> parentClass, Method method, Class<?> annotationClass) {
List<DetailParam> params = new ArrayList<>();
if (method.getParameterCount() < 1) {
return params;
}
for (Parameter param : method.getParameters()) ... |
java | public ServiceFuture<VariableInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String variableName, VariableCreateOrUpdateParameters parameters, final ServiceCallback<VariableInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resou... |
python | def wait_for_string(self, expected_string, timeout=60):
"""Wait for string FSM."""
# 0 1 2 3
events = [self.syntax_error_re, self.connection_closed_re, expected_string, self.press_return_re,
... |
python | def embed(inp, n_inputs, n_features, initializer=None,
fix_parameters=False, apply_w=None):
""" Embed.
Embed slices a matrix/tensor with indexing array/tensor. Weights are initialized with :obj:`nnabla.initializer.UniformInitializer` within the range of :math:`-\\sqrt{3}` and :math:`\\sqrt{3}`.
... |
python | def buffer_focus(self, buf, redraw=True):
"""focus given :class:`~alot.buffers.Buffer`."""
# call pre_buffer_focus hook
prehook = settings.get_hook('pre_buffer_focus')
if prehook is not None:
prehook(ui=self, dbm=self.dbman, buf=buf)
success = False
if buf n... |
java | public Where<T, ID> and(Where<T, ID> first, Where<T, ID> second, Where<T, ID>... others) {
Clause[] clauses = buildClauseArray(others, "AND");
Clause secondClause = pop("AND");
Clause firstClause = pop("AND");
addClause(new ManyClause(firstClause, secondClause, clauses, ManyClause.AND_OPERATION));
return this... |
java | public void insertNewAttributeValue(CmsEntity value, int index, Panel container) {
// make sure not to add more values than allowed
int maxOccurrence = getEntityType().getAttributeMaxOccurrence(m_attributeName);
CmsEntityAttribute attribute = m_entity.getAttribute(m_attributeName);
... |
python | def set_inlets(self, pores=None, clusters=None):
r"""
Parameters
----------
pores : array_like
The list of inlet pores from which the Phase can enter the Network
clusters : list of lists - can be just one list but each list defines
a cluster of pores tha... |
java | public static boolean isAssignableFrom(String lookingFor, TypeDescriptor candidate) {
String[] interfaces = candidate.getSuperinterfacesName();
for (String intface : interfaces) {
if (intface.equals(lookingFor)) {
return true;
}
boolean b = isAssignableFrom(lookingFor, candidate.getTypeRegistry().getDe... |
java | public AccountInfo getAccountInfo() throws Exception {
final JSONObject jsonObject = toJSONObject(client.get(getUri(), null));
return new AccountInfo(client, jsonObject);
} |
java | public static PublishDelete createPublishDelete(Identifier i1, Identifier i2,
String filter) {
PublishDelete pd = createPublishDelete();
fillIdentifierHolder(pd, i1, i2);
pd.setFilter(filter);
return pd;
} |
java | @Override
public SendTemplatedEmailResult sendTemplatedEmail(SendTemplatedEmailRequest request) {
request = beforeClientExecution(request);
return executeSendTemplatedEmail(request);
} |
java | public OvhClusterAllowedNetwork serviceName_cluster_clusterId_allowedNetwork_allowedNetworkId_GET(String serviceName, String clusterId, String allowedNetworkId) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/cluster/{clusterId}/allowedNetwork/{allowedNetworkId}";
StringBuilder sb = path(qPath, servi... |
java | public static List<String> readLinesWithRestOrFilePathOrClasspath(
String resourceWithRestOrFilePathOrClasspath, String charsetName) {
return JMCollections
.buildListByLine(getStringWithRestOrClasspathOrFilePath(
resourceWithRestOrFilePathOrClasspath, charsetN... |
java | public void changeConnector(String connectorName, String attribName, String attribValue) throws Exception {
final Address address = Address.root().add(SUBSYSTEM, SUBSYSTEM_WEB, CONNECTOR, connectorName);
final ModelNode op = createWriteAttributeRequest(attribName, attribValue, address);
final Mo... |
java | private void writeHeader(final String dtd) throws IOException {
if (forHtml){
wtr.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
return;
}
wtr.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
if (dtd == null) {
return;
}
wtr.write("<!D... |
python | def convert_units(self, from_units, to_units):
'''
Convert the mesh from one set of units to another.
These calls are equivalent:
- mesh.convert_units(from_units='cm', to_units='m')
- mesh.scale(.01)
'''
from blmath import units
factor = units.factor(
... |
java | public final void memberDecl() throws RecognitionException {
int memberDecl_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 22) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:365:5: ( genericMethodOrConstructorDecl | methodDeclara... |
java | private boolean hasDelimiter(String word, String[] delimiters) {
boolean delim = false;
for (int i = 0; i < delimiters.length; i++) {
if (word.indexOf(delimiters[i]) > -1) {
delim = true;
break;
}
}
return delim;
} |
java | public OperationStatus deletePatterns(UUID appId, String versionId, List<UUID> patternIds) {
return deletePatternsWithServiceResponseAsync(appId, versionId, patternIds).toBlocking().single().body();
} |
python | def activate(self, token):
"""Make a copy of the received token and call `self._activate`."""
if watchers.worth('MATCHER', 'DEBUG'): # pragma: no cover
watchers.MATCHER.debug(
"Node <%s> activated with token %r", self, token)
return self._activate(token.copy()) |
python | def set_data(self, image):
"""Set the data
Parameters
----------
image : array-like
The image data.
"""
data = np.asarray(image)
if self._data is None or self._data.shape != data.shape:
self._need_vertex_update = True
self._data = ... |
java | @Override
public AttributeValue_4[] write_read_attributes_4(final AttributeValue_4[] values, final ClntIdent clIdent)
throws MultiDevFailed, DevFailed {
MDC.setContextMap(contextMap);
xlogger.entry();
checkInitialization();
final String[] names = new String[values.length... |
java | public DelimiterWriterFactory addColumnTitle(final String columnTitle) {
final Map<String, Object> columnMapping = this.getColumnMapping();
final List<ColumnMetaData> columnMetaDatas = (List<ColumnMetaData>) columnMapping.get(FPConstants.DETAIL_ID);
final Map<Integer, String> columnIndices = (Ma... |
python | def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Del... |
python | def generateFeatures(numFeatures):
"""Return string features.
If <=62 features are requested, output will be single character
alphanumeric strings. Otherwise, output will be ["F1", "F2", ...]
"""
# Capital letters, lowercase letters, numbers
candidates = ([chr(i+65) for i in xrange(26)] +
[... |
python | def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None:
"""
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with... |
python | def rolling_performances(self, timestamp='one_month'):
''' Filters self.perfs '''
# TODO Study the impact of month choice
# TODO Check timestamp in an enumeration
# TODO Implement other benchmarks for perf computation
# (zipline issue, maybe expected)
if self.metrics:
... |
python | def pickle_load(cls, filepath, spectator_mode=True, remove_lock=False):
"""
Loads the object from a pickle file and performs initial setup.
Args:
filepath: Filename or directory name. It filepath is a directory, we
scan the directory tree starting from filepath and w... |
python | def main():
'''
Simple examples
'''
args = parse_arguments()
if args.askpass:
password = getpass.getpass("Password: ")
else:
password = None
if args.asksudopass:
sudo = True
sudo_pass = getpass.getpass("Sudo password[default ssh password]: ")
if len(s... |
java | public synchronized Pair<PathHandler, Undertow> getServer(int port, String hostName) {
return getServer(port,hostName,null);
} |
java | @Override
public boolean apply(final URI uri) {
if (uri.getHost() == null) throw new IllegalArgumentException("URI \"" + uri + "\" has no host");
// BURL hosts are always lower cased
return uri.getHost().equals(host);
} |
java | public QueryBuilder byAuthor(String author) {
Validate.argumentIsNotNull(author);
queryParamsBuilder.author(author);
return this;
} |
java | private void doRelease() {
try {
in.close();
} catch (Exception ex) {
if (log.isDebugEnabled())
log.debug("FYI", ex);
}
if (in instanceof Releasable) {
// This allows any underlying stream that has the close operation
// dis... |
java | @SafeVarargs
public static void assertEmpty(String message, DataSource... dataSources) throws DBAssertionError {
multipleEmptyStateAssertions(CallInfo.create(message), dataSources);
} |
python | def add_contacts(
self,
contacts: List["pyrogram.InputPhoneContact"]
):
"""Use this method to add contacts to your Telegram address book.
Args:
contacts (List of :obj:`InputPhoneContact <pyrogram.InputPhoneContact>`):
The contact list to be added
... |
python | def main():
"""pyprf_opt_brute entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'p... |
python | def infer_category(self, id):
"""
heuristic to infer a category from an id, e.g. DOID:nnn --> disease
"""
logging.info("Attempting category inference on id={}".format(id))
toks = id.split(":")
idspace = toks[0]
c = None
if idspace == 'DOID':
c=... |
java | public void addRemoveVendor(String source, String name, String value, boolean regex, Confidence confidence) {
removeVendor.add(new EvidenceMatcher(source, name, value, regex, confidence));
} |
java | public static Set<String> getColumnNames(DriverTypeEnum.ConnectionProperties theConnectionProperties, String theTableName) throws SQLException {
DataSource dataSource = Objects.requireNonNull(theConnectionProperties.getDataSource());
try (Connection connection = dataSource.getConnection()) {
return theConnection... |
java | private Map<String, Map<String, List<String>>> transformHighlighting() {
Map<String, Map<String, List<String>>> result = new HashMap<String, Map<String, List<String>>>();
if (m_queryResponse.getHighlighting() != null) {
for (String key : m_queryResponse.getHighlighting().keySet()) {
... |
java | void setErrorStatus(String msg, Exception e) {
this.e = new IOException(msg + " " + (e == null ? "" : e.toString()));
// no more writes will be accepted
this.isDisabled = true;
// close the executor
sendExecutor.shutdown();
LOG.error(msg, e);
} |
java | public Object getControlValue()
{
Object objValue = super.getControlValue();
if (objValue instanceof Boolean)
{
if (((Boolean)objValue).booleanValue())
objValue = Constants.TRUE.toLowerCase();
else
objValue = Constants.FALSE.toLowerCase... |
python | def getTrackedDeviceClass(self, unDeviceIndex):
"""
Returns the device class of a tracked device. If there has not been a device connected in this slot
since the application started this function will return TrackedDevice_Invalid. For previous detected
devices the function will return th... |
python | def transform_point(point, source_crs, target_crs):
""" Maps point form src_crs to tgt_crs
:param point: a tuple `(x, y)`
:type point: (float, float)
:param source_crs: source CRS
:type source_crs: constants.CRS
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: poin... |
python | def _glob_to_sql(self, string):
"""Convert glob-like wildcards to SQL wildcards
* becomes %
? becomes _
% becomes \%
\\ remains \\
\* remains \*
\? remains \?
This also adds a leading and trailing %, unless the pattern begins with
^ or ends with ... |
java | public double learn(double[] x, double[] y, double weight) {
setInput(x);
propagate();
double err = weight * computeOutputError(y);
if (weight != 1.0) {
for (int i = 0; i < outputLayer.units; i++) {
outputLayer.error[i] *= weight;
}
}
... |
java | public String dump() throws RepositoryException {
StringBuilder tmp = new StringBuilder();
QueryTreeDump.dump(this, tmp);
return tmp.toString();
} |
python | def _wait_trigger(self):
"""Called to launch the next request in the queue."""
if _debug: IOQController._debug("_wait_trigger")
# make sure we are waiting
if (self.state != CTRL_WAITING):
raise RuntimeError("not waiting")
# change our state
self.state = CTRL... |
python | def _check_apt_updates(self):
"""
This method will use the 'checkupdates' command line utility
to determine how many updates are waiting to be installed via
'apt list --upgradeable'.
"""
output = str(subprocess.check_output(["apt", "list", "--upgradeable"]))
outpu... |
python | def file_download(self, item_id: str, item_name: str, dir_name: str) -> bool:
"""
Download file from Google Drive
:param item_id:
:param dir_name:
:return:
"""
service = self.__get_service()
request = service.files().get_media(fileId=item_id)
self.... |
python | def parse_compound_file(path, format):
"""Open and parse reaction file based on file extension or given format
Path can be given as a string or a context.
"""
context = FilePathContext(path)
# YAML files do not need to explicitly specify format
format = resolve_format(format, context.filepath... |
python | def btc_make_payment_script( address, segwit=None, **ignored ):
"""
Make a pay-to-address script.
"""
if segwit is None:
segwit = get_features('segwit')
# is address bech32-encoded?
witver, withash = segwit_addr_decode(address)
if witver is not None and withash is not None:
... |
java | @Nonnull
public static LoadedKeyStore loadKeyStore (@Nonnull final IKeyStoreType aKeyStoreType,
@Nullable final String sKeyStorePath,
@Nullable final String sKeyStorePassword)
{
ValueEnforcer.notNull (aKeyStoreType, "KeySt... |
python | async def _receive_packet(self, pkt):
"""Handle incoming packets from the server."""
packet_name = packet.packet_names[pkt.packet_type] \
if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN'
self.logger.info(
'Received packet %s data %s', packet_name,
... |
python | def shuffle(self, times=1):
"""
Shuffles the Stack.
.. note::
Shuffling large numbers of cards (100,000+) may take a while.
:arg int times:
The number of times to shuffle.
"""
for _ in xrange(times):
random.shuffle(self.cards) |
java | private void notifyTTAboutTaskCompletion() {
if (oobHeartbeatOnTaskCompletion) {
synchronized (finishedCount) {
int value = finishedCount.get();
finishedCount.set(value+1);
finishedCount.notifyAll();
}
}
} |
python | def events_login(self):
"""
Get all login events. Uses GET to /events/login interface.
:Returns: (list) Events
"""
# TODO Add paging to this
response = self._get(url.events_logins)
return self._create_response(response).get("events") |
python | def context_info(zap_helper, context_name):
"""Get info about the given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
console.info('ID: {}'.format(info['id']))
console.info('Name: {}'.format(info['name']))
console.info('Authentication type: {}'.forma... |
java | private void quote(final String val) throws IOException {
if (val.indexOf("\"") < 0) {
value(val, "\"");
} else {
value(val, "'");
}
} |
python | def add_item(self, item_id, assessment_part_id):
"""Appends an item to an assessment part.
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: assessment_part_id (osid.id.Id): ``Id`` of the
``AssessmentPart``
raise: AlreadyExists - ``item_id`` already part of
... |
java | public void setBounds(float x, float y, float width, float height) {
setX(x);
setY(y);
setSize(width, height);
} |
python | def setbb(self, x, y):
"""Call this method when point (X,Y) is to be drawn in the
canvas. This methods expands the bounding box to include
this point."""
self.__xmin = min(self.__xmin, max(x, self.__clip_box[0]))
self.__xmax = max(self.__xmax, min(x, self.__clip_box[2]))
... |
java | public void setNow(final long unixTimeStamp) throws IllegalTimePointMovement {
/*
* "now" strongly depends on the TimeUnit used for the timeSeries, as
* well as the bucketSize. If, e.g., the TimeUnit is MINUTES and the
* bucketSize is 5, a unix time stamp representing 01/20/1981 08:0... |
python | def turn_physical_on(self,ro=None,vo=None):
"""
NAME:
turn_physical_on
PURPOSE:
turn on automatic returning of outputs in physical units
INPUT:
ro= reference distance (kpc; can be Quantity)
vo= reference velocity (km/s; can be Quantity)
... |
python | def require_debian_packages(packages: List[str]) -> None:
"""
Ensure specific packages are installed under Debian.
Args:
packages: list of packages
Raises:
ValueError: if any are missing
"""
present = are_debian_packages_installed(packages)
missing_packages = [k for k, v i... |
python | def get_item(self, identifier, item_metadata=None, request_kwargs=None):
"""A method for creating :class:`internetarchive.Item <Item>` and
:class:`internetarchive.Collection <Collection>` objects.
:type identifier: str
:param identifier: A globally unique Archive.org identifier.
... |
java | public void addForwardedField(int sourceField, int destinationField) {
FieldSet fs;
if((fs = this.forwardedFields.get(sourceField)) != null) {
fs.add(destinationField);
} else {
fs = new FieldSet(destinationField);
this.forwardedFields.put(sourceField, fs);
}
} |
java | public int compareTo(final HttpString other) {
if(orderInt != 0 && other.orderInt != 0) {
return signum(orderInt - other.orderInt);
}
final int len = Math.min(bytes.length, other.bytes.length);
int res;
for (int i = 0; i < len; i++) {
res = signum(higher(b... |
python | def prt_txt(prt, data_nts, prtfmt=None, nt_fields=None, **kws):
"""Print list of namedtuples into a table using prtfmt."""
lines = get_lines(data_nts, prtfmt, nt_fields, **kws)
if lines:
for line in lines:
prt.write(line)
else:
sys.stdout.write(" 0 items. NOT WRITING\n") |
java | @Override
public boolean configure(final FeatureContext context) {
// Hibernate configuration.
context.register(new HibernateSessionFactory.Binder());
context.register(new HibernateSessionFactoryFactory.Binder());
context.register(new HibernateServiceRegistryFactory.Binder());
... |
java | public static void initLogging() throws IOException {
sendCommonsLogToJDKLog();
try (InputStream resource = Thread.currentThread().getContextClassLoader().getResourceAsStream("logging.properties")) {
// apply configuration
if(resource != null) {
try {
LogManager.getLogManager().readConfiguration(res... |
java | @Override
public void scrollToPosition(int position) {
mCurrentPendingScrollPosition = position;
mPendingScrollPositionOffset = INVALID_OFFSET;
if (mCurrentPendingSavedState != null) {
mCurrentPendingSavedState.putInt("AnchorPosition", RecyclerView.NO_POSITION);
}
... |
python | def median(array):
"""
Return the median value of a list of numbers.
"""
n = len(array)
if n < 1:
return 0
elif n == 1:
return array[0]
sorted_vals = sorted(array)
midpoint = int(n / 2)
if n % 2 == 1:
return sorted_vals[midpoint]
else:
return (so... |
python | def start_packet_groups(self, clear_time_stamps=True, *ports):
""" Start packet groups on ports.
:param clear_time_stamps: True - clear time stamps, False - don't.
:param ports: list of ports to start traffic on, if empty start on all ports.
"""
port_list = self.set_ports_list(*... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.