language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static PreProcessor changePrefix(String from, String to) {
return mkPreProcessorWithMeta((prefix, data, options) -> {
logger.debug("changing prefix at '{}' from '{}' to '{}'", prefix, from, to);
return data.entrySet().stream()
.map(e -> {
... |
python | def decode_list(self, ids):
"""Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integ... |
python | def default_ms_subtable(subtable, name=None, tabdesc=None, dminfo=None):
"""
Creates a default Measurement Set subtable. Any Table Description
elements in tabdesc will overwrite the corresponding element in a default
Measurement Set Table Description (columns, hypercolumns and keywords).
if name is... |
java | protected void setImage(int xsize, int ysize, ByteBuffer buf, Rectangle rect, int bpp) {
int bytespp = bpp / 8;
int bytespl = (int) Math.ceil(xsize * bpp / 8.0);
api.TessBaseAPISetImage(handle, buf, xsize, ysize, bytespp, bytespl);
if (rect != null && !rect.isEmpty()) {
... |
python | def scan(self, data, part):
"""Scan a string.
Parameters
----------
data : `str`
String to scan.
part : `bool`
True if data is partial.
Returns
-------
`generator` of (`str` or `markovchain.scanner.Scanner.END`)
Token ... |
java | void baseOffMeshLinks(MeshTile tile) {
if (tile == null) {
return;
}
long base = getPolyRefBase(tile);
// Base off-mesh connection start points.
for (int i = 0; i < tile.data.header.offMeshConCount; ++i) {
OffMeshConnection con = tile.data.offMeshCons[i]... |
python | def get_certificate_info():
"""
checks app certificate expiry status
"""
if hasattr(settings, 'MIT_WS_CERTIFICATE') and settings.MIT_WS_CERTIFICATE:
mit_ws_certificate = settings.MIT_WS_CERTIFICATE
else:
return {"status": NO_CONFIG}
app_cert = OpenSSL.crypto.load_certificate(
... |
java | public Wrapper setFortune(Fortune value, SetMode mode) {
putWrapped(FIELD_Fortune, Fortune.class, value, mode);
return this;
} |
python | def parse_lemme(self, linea: str, origin: int=0, _deramise: bool=True):
""" Constructeur de la classe Lemme à partir de la ligne linea.
Exemple de linea avec numéro d'éclat:
# cădo|lego|cĕcĭd|cās|is, ere, cecidi, casum|687
# 0 | 1 | 2 | 3 | 4 | 5
... |
java | public List<Command> setPropertyValue(final UUID propertyId, final Object value) throws SynchronizeFXException {
final State state = createCommandList(new WithCommandType() {
@Override
public void invoke(final State state) {
setPropertyValue(propertyId, value, state);
... |
java | public static void close(Iterable<? extends Closeable> closeables)
throws IOException {
IOException first = null;
for (final Closeable c : closeables) {
if (c == null) {
LOG.debug("trying to call .close() on null reference");
continue;
... |
java | private static int arrayMemberHash(final Class<?> componentType, final Object o) {
if (componentType.equals(Byte.TYPE)) {
return Arrays.hashCode((byte[]) o);
}
if (componentType.equals(Short.TYPE)) {
return Arrays.hashCode((short[]) o);
}
if (componentType... |
java | @Conditioned
@Quand("Je mets à jour la date '(.*)-(.*)' avec une '(.*)' date '(.*)'[\\.|\\?]")
@When("I update date '(.*)-(.*)' with a '(.*)' date '(.*)'[\\.|\\?]")
public void updateDate(String page, String elementName, String dateType, String dateOrKey, List<GherkinStepCondition> conditions) throws Tec... |
python | def deserialize_packet_id(packet_id: str) -> dict:
r"""Turn a packet id into individual packet components.
>>> deserialize_packet_id('newkaku_000001_01') == {
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... }
True
>>> deserialize_packet_id('ikeakoppla_... |
python | def process_link(self, env, refnode, has_explicit_title, title, target):
"""This handles some special cases for reference links in .NET
First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```,
where a reference to ``Link`` is created with title ``Title``, causes
problems f... |
java | @Override
public final CustOrder process(final Map<String, Object> pRqVs,
final CustOrder pEntity, final IRequestData pRqDt) throws Exception {
String act = pRqDt.getParameter("act");
if (!("cnc".equals(act) || "pyd".equals(act) || "cls".equals(act))) {
throw new ExceptionWithCode(ExceptionWithCode.... |
python | def logged_query(cr, query, args=None, skip_no_result=False):
"""
Logs query and affected rows at level DEBUG.
:param query: a query string suitable to pass to cursor.execute()
:param args: a list, tuple or dictionary passed as substitution values
to cursor.execute().
:param skip_no_result: I... |
java | public ITrigger getTrigger (final TriggerKey triggerKey) throws SchedulerException
{
validateState ();
return m_aResources.getJobStore ().retrieveTrigger (triggerKey);
} |
java | public static boolean isElementIgnored(final Node received, Set<String> ignoreExpressions, NamespaceContext namespaceContext) {
if (CollectionUtils.isEmpty(ignoreExpressions)) {
return false;
}
/** This is the faster version, but then the ignoreValue name must be
* the full... |
java | public static String formatDateToHRStyle(HR hr, Date date){
if (null == date) {
return "";
}
String style = DateTimeKit.TIME_24HR_STYLE;
if (hr == HR.HR12) {
style = DateTimeKit.TIME_12HR_STYLE;
}
return formatDateToStyle(style, date);
} |
java | static String toNumeral(
NumberSystem numsys,
char zeroDigit,
int number
) {
if (numsys.isDecimal()) {
int delta = zeroDigit - '0';
String standard = Integer.toString(number);
if (delta == 0) {
return standard;
}
... |
python | def networkName(self):
""" :return: the name of the GSM Network Operator to which the modem is connected """
copsMatch = lineMatching(r'^\+COPS: (\d),(\d),"(.+)",{0,1}\d*$', self.write('AT+COPS?')) # response format: +COPS: mode,format,"operator_name",x
if copsMatch:
return copsMatch... |
python | def form_valid(self, form):
if self.__pk:
obj = PurchasesAlbaran.objects.get(pk=self.__pk)
self.request.albaran = obj
form.instance.albaran = obj
form.instance.validator_user = self.request.user
raise Exception("revisar StorageBatch")
"""
bat... |
java | private static Method lookup( String method, String url ) {
String s = method+url;
for( String x : _handlers.keySet() )
if( x.equals(s) ) // TODO: regex
return _handlers.get(x);
return null;
} |
java | public static Object parse(String s) {
try {
return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s);
} catch (Exception e) {
return null;
}
} |
python | def get_subscribe_authorize_url(self, scene, template_id, redirect_url, reserved=None):
"""
构造请求用户授权的url
详情请参阅:
https://mp.weixin.qq.com/wiki?id=mp1500374289_66bvB
:param scene: 订阅场景值,开发者可以填0-10000的整形值,用来标识订阅场景值
:type scene: int
:param template_id: 订阅消息模板ID,登录公众平... |
java | private void setAcceptedLocalCandidate(TransportCandidate bestLocalCandidate) {
for (int i = 0; i < resolver.getCandidateCount(); i++) {
// TODO FIX The EQUAL Sentence
if (resolver.getCandidate(i).getIp().equals(bestLocalCandidate.getIp())
&& resolver.getCandidate(i).... |
java | @SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
Supplier<T> connectionSupplier, GenericObjectPoolConfig<T> config, boolean wrapConnections) {
LettuceAssert.notNull(connectionSupplier, "Connection supplier must not b... |
python | def tobcolz(table, dtype=None, sample=1000, **kwargs):
"""Load data into a bcolz ctable, e.g.::
>>> import petl as etl
>>> table = [('foo', 'bar', 'baz'),
... ('apples', 1, 2.5),
... ('oranges', 3, 4.4),
... ('pears', 7, .1)]
>>> ctbl = etl... |
java | @Override
public Map<String, Object> getBodyParameters() {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userId", this.userId);
params.put("itemId", this.itemId);
params.put("portion", this.portion);
if (this.sessionId!=null) {
params... |
python | def enable(name, start=False, **kwargs):
'''
Start service ``name`` at boot.
Returns ``True`` if operation is successful
name
the service's name
start : False
If ``True``, start the service once enabled.
CLI Example:
.. code-block:: bash
salt '*' service.enable <... |
python | def click_chain(self, selectors_list, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT, spacing=0):
""" This method clicks on a list of elements in succession.
'spacing' is the amount of time to wait between clicks. (sec) """
if self.timeout_multiplier and timeout == se... |
python | def toHierarchy(self, classView, level, stream, lastChild=False):
'''
**Parameters**
``classView`` (bool)
``True`` if generating the Class Hierarchy, ``False`` for File Hierarchy.
``level`` (int)
Recursion level used to determine indentation.
... |
java | @Override
public List<CommerceUserSegmentCriterion> findAll(int start, int end) {
return findAll(start, end, null);
} |
java | public TransformActionBuilder xslt(Resource xsltResource, Charset charset) {
try {
action.setXsltData(FileUtils.readToString(xsltResource, charset));
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read xstl resource", e);
}
return this;
} |
java | @Restricted(DoNotUse.class) // called from newJob view
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
getOwner().checkPermission(Item.CREATE);
if (Ut... |
python | def extend(self, protocol: Union[Iterable[Dict], 'Pipeline']) -> 'Pipeline':
"""Add another pipeline to the end of the current pipeline.
:param protocol: An iterable of dictionaries (or another Pipeline)
:return: This pipeline for fluid query building
Example:
>>> p1 = Pipelin... |
java | public R setTimezone(String timezone) {
mBodyMap.put(BoxUser.FIELD_TIMEZONE, timezone);
return (R) this;
} |
java | public ResultMessage execute(ClientState state) throws RequestValidationException, RequestExecutionException
{
List<PermissionDetails> details = new ArrayList<PermissionDetails>();
if (resource != null && recursive)
{
for (IResource r : Resources.chain(resource))
... |
python | def _get_linewise_report(self):
"""
Returns a report each line of which comprises a pair of an input line
and an error. Unlike in the standard report, errors will appear as many
times as they occur.
Helper for the get_report method.
"""
d = defaultdict(list) # line: [] of errors
for error, lines in s... |
java | protected String convertToPerformanceView(long afterMinusBefore) { // from DfTraceViewUtil.java
if (afterMinusBefore < 0) {
return String.valueOf(afterMinusBefore);
}
long sec = afterMinusBefore / 1000;
final long min = sec / 60;
sec = sec % 60;
final long mi... |
java | public static void setContent(final HttpRequestBase req,
final byte[] content,
final String contentType) throws HttpException {
if (content == null) {
return;
}
if (!(req instanceof HttpEntityEnclosingRequestBase)) {
throw new Http... |
python | def change_filename(filehandle, meta):
"""Changes the filename to reflect the conversion from PDF to JPG.
This method will preserve the original filename in the meta dictionary.
"""
filename = secure_filename(meta.get('filename', filehandle.filename))
basename, _ = os.path.splitext(filename)
met... |
python | def adjacency(tree):
"""
Construct the adjacency matrix of the tree
:param tree:
:return:
"""
dd = ids(tree)
N = len(dd)
A = np.zeros((N, N))
def _adj(node):
if np.isscalar(node):
return
elif isinstance(node, tuple) and len(node) == 2:
A[dd[no... |
java | private void updateCands() {
if (!this.dense) { connectOccs(); }
assert !this.schedule;
this.schedule = true;
if (this.schedule = currentCands().empty()) { for (int idx = 1; idx <= maxvar(); idx++) { touch(idx); } }
this.schedule = true;
touchFixed();
} |
python | def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
try:
while True:
item = queue.get_nowait()
result.append(item)
except: Empty
return result |
java | @Override
public Object getValue(@NonNull String key) {
if (key == null) { throw new IllegalArgumentException("key cannot be null."); }
final int index = indexForColumnName(key);
return index >= 0 ? getValue(index) : null;
} |
java | @SuppressWarnings("RedundantTypeArguments")
public <T> T get(String name) throws ReflectException {
return field(name).<T>get();
} |
java | private void checkGAs(List l)
{
for (final Iterator i = l.iterator(); i.hasNext();)
if (!(i.next() instanceof GroupAddress))
throw new KNXIllegalArgumentException("not a group address list");
} |
java | protected void invokeAuthenticationPostProcessors(final AuthenticationBuilder builder,
final AuthenticationTransaction transaction) {
LOGGER.debug("Invoking authentication post processors for authentication transaction");
val pops = authenticationEve... |
python | def PushItem(self, item, block=True):
"""Pushes an item onto the queue.
Args:
item (object): item to add.
block (Optional[bool]): True to block the process when the queue is full.
Raises:
QueueFull: if the item could not be pushed the queue because it's full.
"""
try:
self.... |
java | public ImageBuffer getRaster(int id)
{
return rasters.get(UtilMath.clamp(id, 0, rasters.size() - 1));
} |
python | def _update_offset_value(self, f, offset, size, value):
'''
Writes "value" into location "offset" in file "f".
'''
f.seek(offset, 0)
if (size == 8):
f.write(struct.pack('>q', value))
else:
f.write(struct.pack('>i', value)) |
python | def resources_update(portal_url, apikey, distributions,
resource_files, generate_new_access_url=None,
catalog_id=None):
"""Sube archivos locales a sus distribuciones correspondientes en el portal
pasado por parámetro.
Args:
portal_url (str)... |
python | def get_std_start_date(self):
""" If the date is custom, return the start datetime with the format %Y-%m-%d %H:%M:%S. Else, returns "". """
first, _ = self._val
if first != datetime.min and first != datetime.max:
return first.strftime("%Y-%m-%d %H:%M:%S")
else:
re... |
java | public ListStacksRequest withStackStatusFilters(StackStatus... stackStatusFilters) {
com.amazonaws.internal.SdkInternalList<String> stackStatusFiltersCopy = new com.amazonaws.internal.SdkInternalList<String>(stackStatusFilters.length);
for (StackStatus value : stackStatusFilters) {
stackStat... |
java | public ApiResponse<Void> getLoginWithHttpInfo(String redirectUri, Boolean includeState) throws ApiException {
com.squareup.okhttp.Call call = getLoginValidateBeforeCall(redirectUri, includeState, null, null);
return apiClient.execute(call);
} |
java | public InputStream getInputStream() throws IOException {
if (null == inputStream) {
if (readFromCache) {
inputStream = new FileInputStream(cacheFile.toFile());
} else {
WriteCacheFileInputStream wis = new WriteCacheFileInputStream(delegate.getInputStream()... |
python | def create_ca(self, name, ca_name='', cert_type=crypto.TYPE_RSA, bits=2048,
alt_names=None, years=5, serial=0, pathlen=0,
overwrite=False):
"""
Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of ... |
java | public static CommerceTaxMethod fetchByGroupId_First(long groupId,
OrderByComparator<CommerceTaxMethod> orderByComparator) {
return getPersistence().fetchByGroupId_First(groupId, orderByComparator);
} |
python | def is_associated_file(self):
# type: () -> bool
'''
A method to determine whether this file is 'associated' with another file
on the ISO.
Parameters:
None.
Returns:
True if this file is associated with another file on the ISO, False
otherwise.... |
python | def get_point_index(point, all_points, eps = 1e-4):
""" Get the index of a point in an array """
inds = np.where(np.linalg.norm(point - all_points, axis=1) < eps)
if inds[0].shape[0] == 0:
return -1
return inds[0][0] |
python | def _dep_changed(self, dep, code_changed=False, value_changed=False):
""" Called when a dependency's expression has changed.
"""
self.changed(code_changed, value_changed) |
java | @Override
public PathImpl schemeWalk(String userPath,
Map<String,Object> attributes,
String filePath,
int offset)
{
if (! isWindows()) {
return super.schemeWalk(userPath, attributes, filePath, offset);
}
String canonicalPa... |
java | public List<Jid> getBlockList()
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
if (blockListCached == null) {
BlockListIQ blockListIQ = new BlockListIQ();
BlockListIQ blockListIQResult = connection().createStanzaCollectorAndSend... |
python | def file_decrypt_from_key_info( sender_key_info, blockchain_id, key_index, hostname, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):
"""
Try to decrypt data with one of the receiver's keys
Return {'status': True} if we succeeded
Return {'error': ..., 'status': Fals... |
python | def createOptimizer(self, params, model):
"""
Create a new instance of the optimizer
"""
lr = params["learning_rate"]
print("Creating optimizer with learning rate=", lr)
if params["optimizer"] == "SGD":
optimizer = optim.SGD(model.parameters(), lr=lr,
momentum=p... |
java | @SuppressWarnings("unchecked")
protected final void initialize(int maxSize) {
size = 0;
int heapSize = maxSize + 1;
heap = (T[]) new Object[heapSize];
this.maxSize = maxSize;
} |
python | def save(self):
"""存储过程
"""
self.client.update(
{
'portfolio_cookie': self.portfolio_cookie,
'user_cookie': self.user_cookie
},
{'$set': self.message},
upsert=True
) |
python | def pivot_table(self, index, columns, values='value',
aggfunc='count', fill_value=None, style=None):
"""Returns a pivot table
Parameters
----------
index: str or list of strings
rows for Pivot table
columns: str or list of strings
colu... |
java | private static WebServiceRefPartialInfo buildPartialInfoFromWebServiceClient(Class<?> serviceInterfaceClass) {
WebServiceClient webServiceClient = serviceInterfaceClass.getAnnotation(WebServiceClient.class);
if (webServiceClient == null) {
return null;
}
String className = s... |
java | public HistogramVisual asVisual()
{
float[] visualCounts = new float[bins.length - 2];
for (int i = 0; i < visualCounts.length; ++i) {
visualCounts[i] = (float) bins[i + 1];
}
return new HistogramVisual(breaks, visualCounts, new float[]{min, max});
} |
java | private void updateArrayOfSetters(ClassOutline co, JCodeModel model) {
JDefinedClass implClass = co.implClass;
List<JMethod> removedMethods = new ArrayList<>();
Iterator<JMethod> iter = implClass.methods().iterator();
while (iter.hasNext()) {
JMethod method = iter.next();
if (method.params(... |
python | def _(mcs, cls_name="Object", with_meta=None):
""" Method to generate real metaclass to be used::
mc = ExtensibleType._("MyClass") # note this line
@six.add_metaclass(mc)
class MyClassBase(object):
pass
:param str cls_name: name ... |
python | def clear(self):
"""Completely clear a Node of all its cached state (so that it
can be re-evaluated by interfaces that do continuous integration
builds).
"""
# The del_binfo() call here isn't necessary for normal execution,
# but is for interactive mode, where we might re... |
python | def _compute_inter_event_std(self, C, C_PGA, pga1100, mag, vs30):
"""
Compute inter event standard deviation, equation 25, page 82.
"""
tau_0 = self._compute_std_0(C['s3'], C['s4'], mag)
tau_b_pga = self._compute_std_0(C_PGA['s3'], C_PGA['s4'], mag)
delta_amp = self._comp... |
java | public void marshall(Dimensions dimensions, ProtocolMarshaller protocolMarshaller) {
if (dimensions == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(dimensions.getQueue(), QUEUE_BINDING);
... |
java | private static final String trimFirstWord(String s) {
s = s.trim();
char[] chars = s.toCharArray();
int firstSpace = -1;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (Character.isWhitespace(c)) {
firstSpace = i;
b... |
java | @Override
public boolean accept(File file) {
return file != null ? match(file.getName(), pattern) : false;
} |
python | def registContact(self, CorpNum, ContactInfo, UserID=None):
""" 담당자 추가
args
CorpNum : 회원 사업자번호
ContactInfo : 담당자 정보, Reference ContactInfo class
UserID : 회원 아이디
return
처리결과. consist of code and message
raise
... |
java | @SuppressWarnings("unchecked")
public static Object convertToCollection(final Object result, final Class collectionType,
final Class targetEntity, final boolean projection) {
final Object converted;
if (collectionType.equals(Iterator.class)) {
... |
java | public void marshall(BatchDescribeSimulationJobRequest batchDescribeSimulationJobRequest, ProtocolMarshaller protocolMarshaller) {
if (batchDescribeSimulationJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocol... |
java | public ScreenParent makeScreen(ScreenLoc itsLocation, ComponentParent parentScreen, int iDocMode, Map<String,Object> properties)
{
ScreenParent screen = null;
if ((iDocMode & ScreenConstants.MAINT_MODE) == ScreenConstants.MAINT_MODE)
{ // This is a little weird... can't directly change thi... |
python | def get_profile_model():
"""
Returns configured user profile model or None if not found
"""
user_profile_module = getattr(settings, 'USER_PROFILE_MODULE', None)
if user_profile_module:
app_label, model_name = user_profile_module.split('.')
return get_model(app_label, model_name)
... |
python | def _detect_encoding(self, source_file):
"""Detect encoding."""
encoding = self._guess(source_file)
# If we didn't explicitly detect an encoding, assume default.
if encoding is None:
encoding = self.default_encoding
return encoding |
java | public static double[] getDoubleData(DataBuffer buf) {
if (buf.allocationMode() == DataBuffer.AllocationMode.HEAP)
return buf.asDouble();
else {
double[] ret = new double[(int) buf.length()];
for (int i = 0; i < buf.length(); i++)
ret[i] = buf.getDoubl... |
java | protected String getIndex() {
try {
return m_configObject.getString(JSON_KEY_INDEX);
} catch (JSONException e) {
if (null == m_baseConfig) {
if (LOG.isInfoEnabled()) {
LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_INDEX_SPECIFIED_0),... |
java | public BufferedImage getImage (ImageKey key, Colorization[] zations)
{
CacheRecord crec = null;
synchronized (_ccache) {
crec = _ccache.get(key);
}
if (crec != null) {
// log.info("Cache hit", "key", key, "crec", crec);
return crec.getImage(zations... |
python | def rgev(xi, mu=0, sigma=1, size=None):
"""
Random generalized extreme value (GEV) variates.
"""
q = np.random.uniform(size=size)
z = flib.gev_ppf(q, xi)
return z * sigma + mu |
python | def launch():
"""Launch the experiment."""
exp = experiment(db.init_db(drop_all=False))
exp.log("Launching experiment...", "-----")
init_db()
exp.recruiter().open_recruitment(n=exp.initial_recruitment_size)
session_psiturk.commit()
session.commit()
return success_response(request_type="... |
python | def logout(lancet, service):
"""Forget saved passwords for the web services."""
if service:
services = [service]
else:
services = ['tracker', 'harvest']
for service in services:
url = lancet.config.get(service, 'url')
key = 'lancet+{}'.format(url)
username = lanc... |
python | def add(self, *args):
"""Add constraints to the model."""
self._constrs.extend(self._moma._prob.add_linear_constraints(*args)) |
python | def create_build_configuration_process(repository, revision, **kwargs):
"""
Create a new BuildConfiguration. BuildConfigurations represent the settings and configuration required to run a build of a specific version of the associated Project's source code.
If a ProductVersion ID is provided, the BuildConfig... |
java | private List<CmsCategory> internalReadSubCategories(CmsObject cms, String rootPath, boolean includeSubCats)
throws CmsException {
List<CmsCategory> categories = new ArrayList<CmsCategory>();
List<CmsResource> resources = cms.readResources(
cms.getRequestContext().removeSiteRoot(rootPath... |
java | public void emphasizePoint( int index )
{
if( dots == null || dots.length < (index - 1) )
return; // impossible !
// if no change, nothing to do
if( emphasizedPoint == index )
return;
// de-emphasize the current emphasized point
if( emphasizedPoint >= 0 )
{
dots[emphasizedPoint].attr( "r", dotNo... |
python | def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None,
fontsize=10, **kwds):
r"""Draw an arithmetic operator."""
if format is None: format = 'k-'
a = size/2.0
x0 = [0, 2.5*a, 0, 0]
y0 = [a, 0, -a, a]
cur_list = [(x0, y0)]
cur_list = rotate_and_traslate(cur_... |
python | def make_module(self, vars=None, shared=False, locals=None):
"""This method works like the :attr:`module` attribute when called
without arguments but it will evaluate the template on every call
rather than caching it. It's also possible to provide
a dict which is then used as context. ... |
java | protected CompensatingTransactionHolderSupport getNewHolder() {
DirContext newCtx = getContextSource().getReadWriteContext();
return new DirContextHolder(
new DefaultCompensatingTransactionOperationManager(
new LdapCompensatingTransactionOperationFactory(
... |
python | def setup_app(self, app, add_context_processor=True): # pragma: no cover
'''
This method has been deprecated. Please use
:meth:`LoginManager.init_app` instead.
'''
warnings.warn('Warning setup_app is deprecated. Please use init_app.',
DeprecationWarning)
... |
java | private static int normalizeInt(int input, int localMax, int maxOutput) {
double ln = Math.log(localMax);
if(input == 0) {
return 0;
} else if(input == 1) {
return 1;
} else {
double iln = Math.log(input);
double pct = iln / ln;
double num = pct * maxOutput;
int idx = (int) num;
// Syste... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.