language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def get_data_filename(filename):
"""Map filename to its actual path.
Parameters
----------
filename : str
Filename to search.
Returns
-------
path : str
Full path to the file in data directory.
"""
global _data_map
if _data_map is None:
_data_map = {}
... |
python | def set(self, name: str, value: Union[str, List[str]]) -> None:
"""
设置 header
"""
self._headers[name] = value |
java | public synchronized void sortResultsByEnergies() throws CDKException {
// System.out.println("\nSort By Energies");
Map<Integer, Map<Integer, Integer>> allEnergyMCS = new TreeMap<Integer, Map<Integer, Integer>>();
Map<Integer, Map<IAtom, IAtom>> allEnergyAtomMCS = new TreeMap<Integer, Ma... |
java | @NonNull
@SuppressWarnings("WeakerAccess")
public SnackbarWrapper appendMessage(@NonNull CharSequence message, @ColorInt int color) {
Spannable spannable = new SpannableString(message);
spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
... |
java | List<T> subList(long from, long to) {
if (fullListSize > 0 && to - from > 0) {
checkRange(from);
// subList takes a [from;to[ range
checkRange(to - 1);
// check if the data of the required sub list are available
assertSubRange(from, to - 1);
... |
java | public Enumeration<String> getElements() {
AttributeNameEnumeration elements = new AttributeNameEnumeration();
elements.addElement(VERSION);
elements.addElement(SERIAL_NUMBER);
elements.addElement(ALGORITHM_ID);
elements.addElement(ISSUER);
elements.addElement(VALIDITY);
... |
python | def select(self, *keys):
"""
指定查询返回结果中只包含某些字段。可以重复调用,每次调用的包含内容都将会被返回。
:param keys: 包含字段名
:rtype: Query
"""
if len(keys) == 1 and isinstance(keys[0], (list, tuple)):
keys = keys[0]
self._select += keys
return self |
python | def run(self, epochs):
"""
Description : Run training for LipNet
"""
best_loss = sys.maxsize
for epoch in trange(epochs):
iter_no = 0
## train
sum_losses, len_losses = self.train_batch(self.train_dataloader)
if iter_no % 20 == 0:
... |
java | public void changeSite(String siteRoot) {
if (!getCmsObject().getRequestContext().getSiteRoot().equals(siteRoot)) {
getCmsObject().getRequestContext().setSiteRoot(siteRoot);
getWorkplaceSettings().setSite(siteRoot);
OpenCms.getSessionManager().updateSessionInfo(getCmsObject(... |
java | private byte[] toJSONStringCompressed() {
String str = toJSONString();
if (str == null || str.length() == 0) {
return new byte[0] ;
}
byte[] outStr;
try {
outStr = compressJSONString(str);
} catch (IOException e) {
throw new RuntimeExce... |
java | public long getColumnCardinality(String schema, String table, Authorizations auths, String family, String qualifier, Collection<Range> colValues)
throws ExecutionException
{
LOG.debug("Getting cardinality for %s:%s", family, qualifier);
// Collect all exact Accumulo Ranges, i.e. single ... |
python | def make_figure(plots):
"""
:param plots: list of pairs (task_name, memory array)
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.grid(True)
ax.set_xlabel('tasks')
ax.set_ylabel('GB')
start = 0
f... |
java | public void close() {
if (this.sock != null)
try {
this.sock_in.close();
this.sock_out.close();
this.sock.close();
this.sock=null;
this.sock_in=null;
this.sock_out=null;
} catch (IOException e) {
}
} |
python | def process_fish(self, limit=None):
"""
Fish give identifiers to the "effective genotypes" that we create.
We can match these by:
Fish = (intrinsic) genotype + set of morpholinos
We assume here that the intrinsic genotypes and their parts
will be processed separately, pr... |
python | def job_tasks(self, job_id, type=None):
"""
With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
... |
python | def get_context_data(self, **kwargs):
"""
We supplement the normal context data by adding our fields and labels.
"""
context = super(SmartView, self).get_context_data(**kwargs)
# derive our field config
self.field_config = self.derive_field_config()
# add our fi... |
java | @Nonnull
public static Price createFromNetAmount (@Nonnull final ICurrencyValue aNetAmount, @Nonnull final IVATItem aVATItem)
{
return new Price (aNetAmount, aVATItem);
} |
java | public static String getDidYouMeanString(Collection<String> available, String it) {
String message = "";
Collection<String> mins = Levenshtein.findSimilar(available, it);
if (mins.size() > 0) {
if (mins.size() == 1) {
message += "Did you mean this?";
} else {
message += "Did you mean one of these... |
python | def _file_not_empty(tmpfile):
"""
Returns True if file exists and it is not empty
to check if it is time to read container ID from cidfile
:param tmpfile: str, path to file
:return: bool, True if container id is written to the file
"""
if os.path.exists(tmpfile):
... |
python | def as_base_types(self):
"""Convert this measurement to a dict of basic types."""
if not self._cached:
# Create the single cache file the first time this is called.
self._cached = {
'name': self.name,
'outcome': self.outcome.name,
}
if self.validators:
self._c... |
java | private void subFormat(int patternCharIndex, int count,
FieldDelegate delegate, StringBuffer buffer,
boolean useDateFormatSymbols)
{
int maxIntCount = Integer.MAX_VALUE;
String current = null;
int beginOffset = buffer.length();
... |
python | def iter_edges(self, cached_content=None):
"""
Iterate over the list of edges of a tree. Each egde is represented as a
tuple of two elements, each containing the list of nodes separated by
the edge.
"""
if not cached_content:
cached_content = self.get_cached_c... |
java | @Override
protected TransactionManager locateTransactionManager() {
try {
return TransactionManagerLocator.INSTANCE.getTransactionManager();
} catch (Exception e) {
throw new HibernateException(e);
}
} |
python | def visit_Compare(self, node):
""" Boolean are possible index.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a < b
... d = b < 3
... |
java | private Status executeIf(Stmt.IfElse stmt, CallStack frame, EnclosingScope scope) {
RValue.Bool operand = executeExpression(BOOL_T, stmt.getCondition(), frame);
if (operand == RValue.True) {
// branch taken, so execute true branch
return executeBlock(stmt.getTrueBranch(), frame, scope);
} else if (stmt.hasF... |
java | public void logProperties(final Logger logger, final String comment) {
logger.info(comment);
for (final String key : getKeySet()) {
logger.info(" key=" + key + " value=" + get(key));
}
} |
java | public static ZoneOffset ofHoursMinutesSeconds(int hours, int minutes, int seconds) {
validate(hours, minutes, seconds);
int totalSeconds = totalSeconds(hours, minutes, seconds);
return ofTotalSeconds(totalSeconds);
} |
python | def wr_xlsx_gos(self, fout_xlsx, **kws_usr):
"""Write an Excel spreadsheet with user GO ids, grouped under broader GO terms."""
# Keyword arguments: control content
desc2nts = self.sortobj.get_desc2nts(**kws_usr)
# Keyword arguments: control xlsx format
self.wr_xlsx_nts(fout_xlsx... |
java | public RandomVariable getMonteCarloWeights(int timeIndex)
{
// Lazy initialization, synchronized for thread safety
synchronized(this) {
if(discreteProcessWeights == null || discreteProcessWeights.length == 0) {
doPrecalculateProcess();
}
}
// Return value of process
return discreteProcessWeights[t... |
java | public void marshall(S3DataSpec s3DataSpec, ProtocolMarshaller protocolMarshaller) {
if (s3DataSpec == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(s3DataSpec.getDataLocationS3(), DATALOCATIONS3_BI... |
python | def _on_mouse_moved(self, event):
""" mouse moved callback """
if event.modifiers() & Qt.ControlModifier:
self._select_word_under_mouse_cursor()
else:
self._remove_decoration()
self.editor.set_mouse_cursor(Qt.IBeamCursor)
self._previous_cursor_star... |
python | def _set_interface_isis(self, v, load=False):
"""
Setter method for interface_isis, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_isis is considered as a private
m... |
java | private static Set<String> getRelationLevelSet(SDocumentGraph graph, String namespace,
Class<? extends SRelation> type) {
Set<String> result = new TreeSet<>();
if (graph != null) {
List<? extends SRelation> edges = null;
if (type == SDominanceRelation.class) {
edges = graph.getDominanceRelations();
... |
python | def generate_roster_pdf(sched_act_ids, include_instructions):
r"""Generates a PDF roster for one or more.
:class:`EighthScheduledActivity`\s.
Args
sched_act_ids
The list of IDs of the scheduled activities to show in the PDF.
include_instructions
Whether instructions... |
python | def array_map(f, ar):
"Apply an ordinary function to all values in an array."
flat_ar = ravel(ar)
out = zeros(len(flat_ar), flat_ar.typecode())
for i in range(len(flat_ar)):
out[i] = f(flat_ar[i])
out.shape = ar.shape
return out |
python | def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
log.exception('disconnected due to exception')
else:
log.info('disconnected because of close/abort.')
if self.disconnect_callback:
self.disconnect_cal... |
python | def probeLine(img, p1, p2, res=100):
"""
Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`.
.. hint:: |probeLine| |probeLine.py|_
"""
line = vtk.vtkLineSource()
line.SetResolution(res)
line.SetPoint1(p1)
line.SetPoint2(p2)
probeFilter = v... |
python | def get_stetson_k(self, mag, avg, err):
"""
Return Stetson K feature.
Parameters
----------
mag : array_like
An array of magnitude.
avg : float
An average value of magnitudes.
err : array_like
An array of magnitude errors.
... |
java | public void setFilters(java.util.Collection<NamespaceFilter> filters) {
if (filters == null) {
this.filters = null;
return;
}
this.filters = new java.util.ArrayList<NamespaceFilter>(filters);
} |
java | private void leftAddNoPredecessor(
GBSNode p,
Object new1,
NodeInsertPoint ip,
InsertNodes point)
{
p.findInsertPointInLeft(new1, i... |
java | public void pushCallbackBeanO(BeanO bean) // d662032
throws CSIException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "pushCallbackBeanO: " + bean);
HandleListInterface hl = bean.reAssociateHandleList();
ivHandleListContext.beginContext(hl... |
java | protected void writeZeroBranchSize(final BitOutputStream out,
final long value, final long max, final Bits bits) throws IOException {
assert 0 <= value;
assert max >= value;
if (SERIALIZATION_CHECKS) {
out.write(SerializationChecks.BeforeCount);
}
if (this.useBinomials) {
Gaussian.fr... |
python | def batch_get_documents(
self,
database,
documents,
mask=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... |
java | protected void zSetData(MithraDataObject data)
{
this.currentData = data;
this.persistenceState = PersistenceState.PERSISTED;
MithraTransaction currentTransaction = MithraManagerProvider.getMithraManager().getCurrentTransaction();
if (currentTransaction != null && zGetPortal()... |
python | def createStream(ssc, kinesisAppName, streamName, endpointUrl, regionName,
initialPositionInStream, checkpointInterval,
storageLevel=StorageLevel.MEMORY_AND_DISK_2,
awsAccessKeyId=None, awsSecretKey=None, decoder=utf8_decoder,
stsAssume... |
java | final ServiceController<?> addRelativePathService(final ServiceTarget serviceTarget, final String pathName, final String path,
final boolean possiblyAbsolute, final String relativeTo) {
if (possiblyAbsolute && AbstractPathService.isAbsoluteUnixOrWindowsPath(... |
python | def merge(iterable1, *args):
"""
Returns an type of iterable1 value, which merged after iterable1 used *args
:exception TypeError: if any parameter type of args not equals type(iterable1)
Example 1:
source = ['a', 'b', 'c']
result = merge(source, [1, 2, 3])
self.assertEqual(res... |
java | private void checkSpaceConstrain(long logFileSize) {
long spaceNeeded;
if (maxRepositorySize > 0) {
synchronized(fileList) {
initFileList(false);
long purgeSize = totalSize + logFileSize - maxRepositorySize;
if (debugLogger.isLoggable(Level.FINE) && LogRepositoryBaseImpl.isDebugEnabled()) {
debu... |
python | def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
Phi(R,z)
... |
python | def take(
self,
indices: Sequence[int],
allow_fill: bool = False,
fill_value: Any = None
) -> ABCExtensionArray:
"""
Take elements from an array.
Parameters
----------
indices : sequence of integers
Indices to be ta... |
python | def xmlrpc_notify(self, app_id, token_or_token_list, aps_dict_or_list):
""" Sends push notifications to the Apple APNS server. Multiple
notifications can be sent by sending pairing the token/notification
arguments in lists [token1, token2], [notification1, notification2].
Arguments:
ap... |
java | public void organizationName_service_exchangeService_account_primaryEmailAddress_protocol_PUT(String organizationName, String exchangeService, String primaryEmailAddress, OvhExchangeAccountProtocol body) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/account/{primary... |
python | def apply_to_model(self, model):
''' Apply this theme to a model.
.. warning::
Typically, don't call this method directly. Instead, set the theme
on the :class:`~bokeh.document.Document` the model is a part of.
'''
model.apply_theme(self._for_class(model.__class... |
java | public void extractFundmental( DMatrixRMaj F21 , DMatrixRMaj F31 ) {
// compute the camera matrices one column at a time
for( int i = 0; i < 3; i++ ) {
DMatrixRMaj T = tensor.getT(i);
GeometryMath_F64.mult(T,e3,temp0);
GeometryMath_F64.cross(e2,temp0,column);
F21.set(0,i,column.x);
F21.set(1,i,col... |
python | def get_thumbpath(self, path, key, format):
"""Return the relative path of the thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail file extension
"""
relpath = os.path.dirname(path)
thumbsdir =... |
python | def _format_quantum(val, unit):
"""
Format a quantity with reasonable units.
:param val: The value (just the value, not a quantity)
:param unit: Unit (something that can be fed to quanta).
:return: A string representation of this quantity.
>>> _format_quantum(3, 'm')
"3 m"
>>> _format_q... |
java | public static WindowOver<Double> regrAvgy(Expression<? extends Number> arg1, Expression<? extends Number> arg2) {
return new WindowOver<Double>(Double.class, SQLOps.REGR_AVGY, arg1, arg2);
} |
python | def nlmsg_put(n, pid, seq, type_, payload, flags):
"""Add a Netlink message header to a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L503
Adds or overwrites the Netlink message header in an existing message object.
Positional arguments:
n -- Netlink message (nl_msg... |
python | def update_firewall_policy(self, firewall_policy, body=None):
"""Updates a firewall policy."""
return self.put(self.firewall_policy_path % (firewall_policy),
body=body) |
python | def minimum_address(self):
"""The minimum address of the data, or ``None`` if the file is empty.
"""
minimum_address = self._segments.minimum_address
if minimum_address is not None:
minimum_address //= self.word_size_bytes
return minimum_address |
python | def _sample_cell(args, cell_body):
"""Implements the BigQuery sample magic for sampling queries
The supported sytanx is:
%%bq sample <args>
[<inline SQL>]
Args:
args: the optional arguments following '%%bq sample'.
cell_body: optional contents of the cell
Returns:
The results of executing t... |
java | public void unsubscribeFromViewEvent(Class<? extends SystemEvent> systemEvent,
SystemEventListener listener) {
if (systemEvent == null) {
throw new NullPointerException();
}
if (listener == null) {
throw new NullPointerException()... |
java | public static String docToString1(Document dom) {
StringWriter sw = new StringWriter();
DOM2Writer.serializeAsXML(dom, sw);
return sw.toString();
} |
java | public static byte[] generateRandomUUIDBytes()
{
if (rand == null)
rand = new SecureRandom();
byte[] buffer = new byte[16];
rand.nextBytes(buffer);
// Set version to 3 (Random)
buffer[6] = (byte) ((buffer[6] & 0x0f) | 0x40);
// Set variant to 2 (IETF)
buffe... |
java | @BetaApi
public final Operation simulateMaintenanceEventInstance(ProjectZoneInstanceName instance) {
SimulateMaintenanceEventInstanceHttpRequest request =
SimulateMaintenanceEventInstanceHttpRequest.newBuilder()
.setInstance(instance == null ? null : instance.toString())
.build();... |
python | async def kickban(self, channel, target, reason=None, range=0):
"""
Kick and ban user from channel.
"""
await self.ban(channel, target, range)
await self.kick(channel, target, reason) |
java | public static void joinUninterruptibly(Thread toJoin,
long timeout, TimeUnit unit) {
Preconditions.checkNotNull(toJoin);
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
... |
python | def stub(base_class=None, **attributes):
"""creates a python class on-the-fly with the given keyword-arguments
as class-attributes accessible with .attrname.
The new class inherits from
Use this to mock rather than stub.
"""
if base_class is None:
base_class = object
members = {
... |
python | def calculate_dates(self, dt):
"""
Given a dt, find that day's close and period start (close - offset).
"""
period_end = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)[1]
# Align the market close time here with the execution time... |
java | public Set<DuracloudUser> getAccountUsers(AccountInfo account) {
DuracloudRightsRepo rightsRepo = repoMgr.getRightsRepo();
List<AccountRights> acctRights =
rightsRepo.findByAccountId(account.getId());
Set<DuracloudUser> users = new HashSet<>();
for (AccountRights rights : a... |
java | public static Class getArrayClass(Class c) {
if (c.getComponentType().isArray())
return getArrayClass(c.getComponentType());
else
return c.getComponentType();
} |
java | public SQLException exceptionWithQuery(String sql, SQLException sqlException,
boolean explicitClosed) {
if (explicitClosed) {
return new SQLException(
"Connection has explicitly been closed/aborted.\nQuery is: " + subQuery(sql),
sqlException.getSQLState(),
sqlException.getE... |
java | private void throwExIntParam(MethodVisitor mv, Class<?> exCls) {
String exSig = Type.getInternalName(exCls);
mv.visitTypeInsn(NEW, exSig);
mv.visitInsn(DUP);
mv.visitLdcInsn("mapping " + this.className + " failed to map field:");
mv.visitVarInsn(ILOAD, 2);
mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer... |
java | private Pair<EnumFacing, Point> getClosest(List<Pair<EnumFacing, Point>> points)
{
double distance = Double.MAX_VALUE;
Pair<EnumFacing, Point> ret = null;
for (Pair<EnumFacing, Point> pair : points)
{
double d = Point.distanceSquared(src, pair.getRight());
if (distance > d)
{
distance = d;
ret... |
java | private boolean checkIfThenConditionsMet(List<Integer> rGroupNumbers, List<Integer[]> distributions) {
for (int outer = 0; outer < rGroupNumbers.size(); outer++) {
int rgroupNum = rGroupNumbers.get(outer);
if (allZeroArray(distributions.get(outer))) {
for (int inner = 0; ... |
python | def stop(self, force=False, wait=False):
"""
Terminate all VMs in this cluster and delete its repository.
:param bool force:
remove cluster from storage even if not all nodes could be stopped.
"""
log.debug("Stopping cluster `%s` ...", self.name)
failed = self... |
python | def login(self, username, password=None, email=None, registry=None, reauth=False, **kwargs):
"""
Login to a Docker registry server.
:param username: User name for login.
:type username: unicode | str
:param password: Login password; may be ``None`` if blank.
:type passwo... |
python | def match_similar(base, items):
"""Get the most similar matching item from a list of items.
@param base: base item to locate best match
@param items: list of items for comparison
@return: most similar matching item or None
"""
finds = list(find_similar(base, items))
if finds:
retur... |
python | def wait_until_element_attribute_is(self, element, attribute, value, timeout=None):
"""Search element and wait until the requested attribute contains the expected value
:param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
:param attribute: attribut... |
python | def send_feature_report(self, data, report_id=0x00):
"""
Send a Feature report to a HID device.
Feature reports are sent over the Control endpoint as a Set_Report
transfer.
Parameters:
data The data to send
Returns:
This function returns the ... |
java | protected void initMembers() {
synchronized (LOCK) {
m_resourceInitHandlers = new ArrayList<I_CmsResourceInit>();
m_requestHandlers = new HashMap<String, I_CmsRequestHandler>();
m_systemInfo = new CmsSystemInfo();
m_exportPoints = Collections.emptySet();
... |
java | public void setFloating(ICalProperty property, boolean enable) {
if (enable) {
floatingProperties.add(property);
} else {
removeIdentity(floatingProperties, property);
}
} |
java | private void sendIdentify(WebSocket websocket) {
ObjectNode identifyPacket = JsonNodeFactory.instance.objectNode()
.put("op", GatewayOpcode.IDENTIFY.getCode());
ObjectNode data = identifyPacket.putObject("d");
String token = api.getPrefixedToken();
data.put("token", token... |
java | public static CommerceAccountOrganizationRel fetchByCommerceAccountId_First(
long commerceAccountId,
OrderByComparator<CommerceAccountOrganizationRel> orderByComparator) {
return getPersistence()
.fetchByCommerceAccountId_First(commerceAccountId,
orderByComparator);
} |
java | private void squaresToPositionList() {
this.positionPatterns.reset();
List<DetectPolygonFromContour.Info> infoList = squareDetector.getPolygonInfo();
for (int i = 0; i < infoList.size(); i++) {
DetectPolygonFromContour.Info info = infoList.get(i);
// The test below has been commented out because the new ex... |
java | private void discoverContent(Activity activity) {
discoveryRepeatCnt_ = 0;
if (discoveredViewList_.size() < cdManifest_.getMaxViewHistorySize()) { // check if max discovery views reached
handler_.removeCallbacks(readContentRunnable);
lastActivityReference_ = new WeakReference<>(a... |
java | private static List<UsbDevice> collect(final UsbDevice device)
{
final List<UsbDevice> l = new ArrayList<>();
if (device.isUsbHub())
getAttachedDevices((UsbHub) device).forEach(d -> l.addAll(collect(d)));
else
l.add(device);
return l;
} |
python | def create_model(self, role=None, image=None, predictor_cls=None, serializer=None, deserializer=None,
content_type=None, accept=None, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT, **kwargs):
"""
Create a model to deploy.
Args:
role (str): The ``ExecutionRole... |
java | public Wife addWifeToFamily(final Family family, final Person person) {
if (family == null || person == null) {
return new Wife();
}
final FamS famS = new FamS(person, "FAMS",
new ObjectId(family.getString()));
final Wife wife = new Wife(family, "Wife",
... |
java | private SerializationPolicy getSerializationPolicy(CmsObject cms) {
boolean online = cms.getRequestContext().getCurrentProject().isOnlineProject();
if (online && (m_serPolicyOnline != null)) {
return m_serPolicyOnline;
} else if (!online && (m_serPolicyOffline != null)) {
... |
java | public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
int index = comboBox.getSelectedIndex();
if ((index >= 0) && (index != month)) {
setMonth(index, false);
}
}
} |
python | def serialize_to_json(result, unpicklable=False):
"""Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserial... |
java | public void setTextRotationAlignment(@Property.TEXT_ROTATION_ALIGNMENT String value) {
PropertyValue propertyValue = textRotationAlignment(value);
constantPropertyUsageMap.put(PROPERTY_TEXT_ROTATION_ALIGNMENT, propertyValue);
layer.setProperties(propertyValue);
} |
python | def to_igraph(self, attribute="weight", **kwargs):
"""Convert to an igraph Graph
Uses the igraph.Graph.Weighted_Adjacency constructor
Parameters
----------
attribute : str, optional (default: "weight")
kwargs : additional arguments for igraph.Graph.Weighted_Adjacency
... |
python | def p_operation_definition4(self, p):
"""
operation_definition : operation_type name selection_set
"""
p[0] = self.operation_cls(p[1])(selections=p[3], name=p[2]) |
python | def _add_text_size_ngrams(self, text_id, size, ngrams):
"""Adds `ngrams`, that are of size `size`, to the data store.
The added `ngrams` are associated with `text_id`.
:param text_id: database ID of text associated with `ngrams`
:type text_id: `int`
:param size: size of n-grams... |
python | def set_proxy(self, proxy):
""" Sets a HTTPS proxy to query the Twitter API
:param proxy: A string of containing a HTTPS proxy \
e.g. ``set_proxy("my.proxy.com:8080")``.
:raises: TwitterSearchException
"""
if isinstance(proxy, str if py3k else basestring):
s... |
python | def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False):
'''
Compares two version numbers. Accepts a custom function to perform the
cmp-style version comparison, otherwise uses version_cmp().
'''
cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,),
'>=': (0, 1), '>': ... |
java | public ServiceFuture<PublicIPPrefixInner> beginUpdateTagsAsync(String resourceGroupName, String publicIpPrefixName, final ServiceCallback<PublicIPPrefixInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateTagsWithServiceResponseAsync(resourceGroupName, publicIpPrefixName), serviceCallback);
... |
python | def estimate(self,param,burn=None,clip=10.0,alpha=0.32):
""" Estimate parameter value and uncertainties """
# FIXME: Need to add age and metallicity to composite isochrone params (currently properties)
if param not in list(self.samples.names) + list(self.source.params) + ['age','metallicity']:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.