language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def setValues(self, values):
"""
Set the tuples in this set. Valid only for non-indexed sets.
Args:
values: A list of tuples or a :class:`~amplpy.DataFrame`.
In the case of a :class:`~amplpy.DataFrame`, the number of indexing
columns of the must be equal to the arit... |
python | def format_values(self):
"""Returns a string with all args and settings and where they came from
(eg. commandline, config file, enviroment variable or default)
"""
source_key_to_display_value_map = {
_COMMAND_LINE_SOURCE_KEY: "Command Line Args: ",
_ENV_VAR_SOURCE... |
java | public Iterator<Row> iterator()
{
if (this.rows != null)
{
return Arrays.asList(this.rows).iterator();
}
else
{
return ConvertibleIteratorUtils.iterateAsRow(this.pbRows.iterator(), this.pbColumnDescriptions);
}
} |
java | public static void main(String[] args){
// -- STRESS TEST THREADS --
Runnable[] tasks = new Runnable[1000];
for(int i=0; i<tasks.length; i++){
final int fI = i;
tasks[i] = new Runnable(){
public void run(){
startTrack("Runnable " + fI);
log(Thread.currentThr... |
java | private Counter<L> probabilityOfRVFDatum(RVFDatum<L, F> example) {
// NB: this duplicate method is needed so it calls the scoresOf method
// with a RVFDatum signature
Counter<L> scores = logProbabilityOfRVFDatum(example);
for (L label : scores.keySet()) {
scores.setCount(label, Math.exp(score... |
java | @Override
public LepResource getResource(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
Objects.requireNonNull(resourceKey, "resourceKey can't be null");
log.debug("Getting LEP resource for key {}", resourceKey);
final Resource scriptResource = getScriptResource(contextsHolde... |
java | public EEnum getUSCBYPSIDEN() {
if (uscbypsidenEEnum == null) {
uscbypsidenEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(76);
}
return uscbypsidenEEnum;
} |
python | def create(self, friendly_name=values.unset, sync_service_sid=values.unset):
"""
Create a new DeploymentInstance
:param unicode friendly_name: A human readable description for this Deployment.
:param unicode sync_service_sid: The unique identifier of the Sync service instance.
... |
python | def verify(self, string_version=None):
"""
Check that the version information is consistent with the VCS
before doing a release. If supplied with a string version,
this is also checked against the current version. Should be
called from setup.py with the declared package version b... |
python | def vote(request, pollId, responseId):
"""Vote for a poll"""
username = request.args.get('ebuio_u_username')
# Remove old votes from the same user on the same poll
curDB.execute('DELETE FROM Vote WHERE username = ? AND responseId IN (SELECT id FROM Response WHERE pollId = ?) ', (username, pollId))
... |
python | def authenticate_eauth(self, load):
'''
Authenticate a user by the external auth module specified in load.
Return True on success or False on failure.
'''
if 'eauth' not in load:
log.warning('Authentication failure of type "eauth" occurred.')
return False
... |
python | def is_birthday(self, dt=None):
"""
Check if its the birthday.
Compares the date/month values of the two dates.
:rtype: bool
"""
if dt is None:
dt = self.now(self.tz)
instance = pendulum.instance(dt)
return (self.month, self.day) == (instanc... |
python | def has_child_families(self, family_id):
"""Tests if a family has any children.
arg: family_id (osid.id.Id): the ``Id`` of a family
return: (boolean) - ``true`` if the ``family_id`` has children,
``false`` otherwise
raise: NotFound - ``family_id`` is not found
... |
python | def StrSuffixOf(suffix, input_string):
"""
Return True if the concrete value of the input_string ends with suffix
otherwise false.
:param suffix: suffix we want to check
:param input_string: the string we want to check
:return : True if the input_string ends with suffix else false
"""
... |
java | @Override
public void setNClob(String parameterName, NClob value) throws SQLException
{
checkClosed();
throw SQLError.noSupport();
} |
java | public static <ElementT> void bubbleDown(
@NonNull ElementT[] elements, int sourceIndex, int targetIndex) {
for (int i = sourceIndex; i < targetIndex; i++) {
swap(elements, i, i + 1);
}
} |
java | private void writeOnDisk(JSONObject plistJSON, File destination)
throws IOException, JSONException {
if (destination.exists()) {
// This is possible if we start with capability "reuseContentAndSettings"
log.info(destination + " already exists. Overwriting data");
}
// make sure the folder... |
java | public CreateGroupRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} |
java | public OkCoinPriceLimit getPriceLimits(CurrencyPair currencyPair, Object... args)
throws IOException {
if (args != null && args.length > 0)
return getFuturesPriceLimits(currencyPair, (FuturesContract) args[0]);
else return getFuturesPriceLimits(currencyPair, futuresContract);
} |
java | protected void setupPushedActionForm(HtmlResponse response) {
response.getPushedFormInfo().ifPresent(formInfo -> {
final String formKey = LastaWebKey.PUSHED_ACTION_FORM_KEY;
VirtualForm form = createPushedActionForm(formInfo, formKey);
runtime.manageActionForm(OptionalThing.o... |
java | private static BeanInfo getBeanInfo(Object bean)
{
try
{
return Introspector.getBeanInfo(bean.getClass());
}
catch (IntrospectionException exception)
{
// TODO: handle exception better?
throw new RuntimeException("Error introspecting bean: " + bean, exception);
}
} |
java | public Set<CurrencyUnit> getCurrencies(CurrencyQuery currencyQuery) {
Set<CurrencyUnit> result = new HashSet<>(CURRENCY_UNITS.size());
if (currencyQuery.get(LocalDateTime.class) != null || currencyQuery.get(LocalDate.class) != null) {
return Collections.emptySet();
}
if (!cur... |
python | def save_scan_plot(self, filename="scan.pdf",
img_format="pdf", coords=None):
"""
Save matplotlib plot of the potential energy surface to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
co... |
python | def _speak_normal_inherit(self, element):
"""
Speak the content of element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
self._visit(element, self._speak_normal)
element.normalize() |
python | def syllabified_str(self, separator="."):
"""
Returns:
str: Syllabified word in string format
Examples:
>>> Word('conseil').syllabified_str()
'con.seil'
You can also specify the separator('.' by default)
>>> Word('sikerly').syllabif... |
python | def getSubOrder(existing):
""" Alpha sort by the full chain of parents. """
alpha = list(zip(*sorted(((k, v['rec']['label']) for k, v in existing.items()), key=lambda a: a[1])))[0]
depths = {}
def getDepth(id_):
if id_ in depths:
return depths[id_]
else:
if id_ in... |
python | def room_temperature(self):
"""Return room temperature for both sides of bed."""
# Check which side is active, if both are return the average
tmp = None
tmp2 = None
for user in self.users:
obj = self.users[user]
if obj.current_values['processing']:
... |
python | def tamper_file(filepath, mode='e', proba=0.03, block_proba=None, blocksize=65535, burst_length=None, header=None):
""" Randomly tamper a file's content """
if header and header > 0:
blocksize = header
tamper_count = 0 # total number of characters tampered in the file
total_size = 0 # total buf... |
python | def add_neighbours(self):
"""
Extends the MOC instance so that it includes the HEALPix cells touching its border.
The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance.
Returns
-------
moc : `~mocpy.moc.MOC`
sel... |
python | def tags_are_valid(subset, superset):
"""Validate tags"""
for key, val in subset.items():
if key in superset and superset[key] != val:
return False
return True |
java | public List<String> expressionsListToResolve()
{
String[] parts = expression.trim().split( "\\s+" );
List<String> expressionsList = new ArrayList<String>();
withDots( expressionsList, parts );
noDots( expressionsList, parts );
asIs( expressionsList, parts );
return ... |
java | public Type getCommonSupertype() throws ClassNotFoundException {
if (commonSupertype != null) {
return commonSupertype;
}
if (isEmpty()) {
// This probably means that we're looking at an
// infeasible exception path.
return TypeFrame.getTopType();... |
java | public static boolean correctOffsetAndLengthToWrite(byte[] b, int off, int len) {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0)
|| ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBound... |
java | public static Map<String, Object> getKvMap(SupportFileTypeEnum supportFileTypeEnum, String fileName)
throws Exception {
DisconfFileTypeProcessor disconfFileTypeProcessor;
//
// 获取数据
//
Map<String, Object> dataMap;
if (supportFileTypeEnum.equals(SupportFileTypeE... |
python | def session(self):
"""Return an instance of Requests Session configured for the ThreatConnect API."""
if self._session is None:
from .tcex_session import TcExSession
self._session = TcExSession(self)
return self._session |
python | def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str:
"""Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set.
"""
session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1]
session_tls_ticket = (... |
java | @javax.annotation.Nonnull
public static byte[] read(@javax.annotation.Nonnull final DataInputStream i, final int s) throws IOException {
@javax.annotation.Nonnull final byte[] b = new byte[s];
int pos = 0;
while (b.length > pos) {
final int read = i.read(b, pos, b.length - pos);
if (0 == read)... |
java | @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static Map<Class<?>, LinkedHashMap<String, Type>> trackRootVariables(
final Class<?> type,
final List<Class<?>> ignoreClasses) {
// leave type variables to track where would they go
final LinkedHashMap<String, T... |
python | def do_edit(self, arg, arguments):
"""
::
Usage:
edit FILENAME
Edits the file with the given name
Arguments:
FILENAME the file to edit
"""
def _create_file(filename):
if not os.path.exists(filename)... |
python | def quaternion_conjugate(quaternion):
"""Return conjugate of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_conjugate(q0)
>>> q1[0] == q0[0] and all(q1[1:] == -q0[1:])
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
numpy.negative(q[1:], q[1:])
re... |
java | private static Vec getColumn(Matrix x)
{
Vec t;
for(int i = 0; i < x.cols(); i++)
{
t = x.getColumn(i);
if(t.dot(t) > 0 )
return t;
}
throw new ArithmeticException("Matrix is essentially zero");
} |
java | public final long[] getTick() {
List<Long> list = (List<Long>)jmo.getField(ControlAccess.BODY_DECISIONEXPECTED_TICK);
long lists[] = new long[list.size()];
for (int i = 0; i < lists.length; i++)
lists[i] = list.get(i).longValue();
return lists;
} |
java | public static <T> T getNotNull( T argument,
String name ) {
isNotNull(argument, name);
return argument;
} |
python | def field_default(colx, table_name, tables_dict):
"takes sqparse2.ColX, Table"
if colx.coltp.type.lower() == 'serial':
x = sqparse2.parse('select coalesce(max(%s),-1)+1 from %s' % (colx.name, table_name))
return sqex.run_select(x, tables_dict, Table)[0]
elif colx.not_null: raise NotImplementedError('todo:... |
python | def process_data(self, block):
"""expects Block from Compressor"""
if hasattr(block, 'send_destinations') and block.send_destinations:
self.fire(events.FileProcessed(block))
self._log_in_db(block)
if self._sent_log_file:
self._log_in_sent_log(block)
... |
java | @Nullable
private static Modifier getTokModifierKind(ErrorProneToken tok) {
switch (tok.kind()) {
case PUBLIC:
return Modifier.PUBLIC;
case PROTECTED:
return Modifier.PROTECTED;
case PRIVATE:
return Modifier.PRIVATE;
case ABSTRACT:
return Modifier.ABSTRACT;
... |
java | public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
return divide(divisor, scale, roundingMode.oldMode);
} |
java | public static void setNoCacheHeaders(HttpServletResponse res) {
res.setHeader(CmsRequestUtil.HEADER_CACHE_CONTROL, CmsRequestUtil.HEADER_VALUE_MAX_AGE + "0");
res.addHeader(CmsRequestUtil.HEADER_CACHE_CONTROL, CmsRequestUtil.HEADER_VALUE_MUST_REVALIDATE);
res.addHeader(CmsRequestUtil.HEADER_CAC... |
java | private static <T> ListenableFuture<T> submitAndAddQueueListener(
ListeningExecutorService executorService, Callable<T> task,
final BlockingQueue<Future<T>> queue) {
final ListenableFuture<T> future = executorService.submit(task);
future.addListener(new Runnable() {
@Override public void run()... |
java | public static byte[] sha512(byte [] message) {
if (!(message!=null && message.length>0))
return null;
byte [] out = new byte[hashLength];
crypto_hash(out, message);
return out;
} |
java | @Override
public boolean removeListener(NotificationListener listenerToRemove) {
// Get the listener that is registered with the delegate and remove it
ArtifactListener delegateListener = this.listenerDelegates.remove(listenerToRemove);
return this.delegateNotifier.removeListener(delegateLis... |
python | def filter(self, filter_func):
"""Return a new SampleCollection containing only samples meeting the filter criteria.
Will pass any kwargs (e.g., field or skip_missing) used when instantiating the current class
on to the new SampleCollection that is returned.
Parameters
--------... |
python | def japan_basin_model(vs30):
"""
Returns the centred z1.0 (mu_z1) based on the Japan model
(equation 12)
"""
coeff = 412.39 ** 2.0
model = (-5.23 / 2.0) * np.log(
((vs30 ** 2.0) + coeff) / ((1360.0 ** 2.0) + coeff)
) - np.log(1000.)
return np.exp(model) |
python | def acquire_account(self, account=None, owner=None):
"""
Acquires the given account. If no account is given, one is chosen
from the default pool.
:type account: Account
:param account: The account that is added.
:type owner: object
:param owner: An optional des... |
python | def search(self, q=None, advanced=False, limit=None, info=False, reset_query=True):
"""Execute a search and return the results, up to the ``SEARCH_LIMIT``.
Arguments:
q (str): The query to execute. **Default:** The current helper-formed query, if any.
There must be some ... |
java | @SuppressWarnings("unchecked")
@Override
public EList<ListOfELong> getCoordIndex() {
return (EList<ListOfELong>) eGet(Ifc4Package.Literals.IFC_TRIANGULATED_FACE_SET__COORD_INDEX, true);
} |
java | protected void childStateChanged(PropertyChangeEvent evt) {
if (FormModel.DIRTY_PROPERTY.equals(evt.getPropertyName())) {
Object source = evt.getSource();
if (source instanceof FieldMetadata) {
FieldMetadata metadata = (FieldMetadata) source;
if (metadata.isDirty()) {
dirtyValueAndFormModels.add(m... |
java | static Token newWithoutOrigin(TokenType tokenType, String debugString, String tokenText) {
return new Token(tokenType, null, tokenText, debugString);
} |
java | public static Properties readProperties(File _file) {
if (_file.exists()) {
try {
return readProperties(new FileInputStream(_file));
} catch (FileNotFoundException _ex) {
LOGGER.info("Could not load properties file: " + _file, _ex);
}
}... |
python | def from_schemafile(cls, schemafile):
"""Create a Flatson instance from a schemafile
"""
with open(schemafile) as f:
return cls(json.load(f)) |
java | public Object get(long key)
{
int hash = (int) (key & mask);
while (true) {
long mapKey = keys[hash];
if (mapKey == key)
return values[hash];
else if (mapKey == DEAD_KEY) {
if ((flags[hash] & DELETED) == 0)
return null;
}
hash = (hash + 1) & mask;
... |
java | private <T extends D6Model> T[] toArray(List<Object> objectList, Class<T> modelClazz) {
if (objectList == null) {
return (T[]) Array.newInstance(modelClazz, 0);
}
final T[] resultObjects = objectList.toArray((T[]) Array.newInstance(modelClazz, 0));
return resultObjects;
} |
java | public AmazonS3 getClient(String region) {
if (region == null) {
throw new IllegalArgumentException("S3 region must be specified");
}
AmazonS3 client = clientsByRegion.get(region);
return client != null ? client : cacheClient(region);
} |
python | def delete(self, path):
"""Wrap the hvac delete call, using the right token for
cubbyhole interactions."""
path = sanitize_mount(path)
val = None
if path.startswith('cubbyhole'):
self.token = self.initial_token
val = super(Client, self).delete(path)
... |
python | def l2traceroute_result_output_l2_hop_results_l2_hop_egress_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
l2traceroute_result = ET.Element("l2traceroute_result")
config = l2traceroute_result
output = ET.SubElement(l2traceroute_re... |
java | @Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
AnnotationVisitor av = super.visitAnnotation(desc, visible);
observedAnnotations.add(Type.getType(desc));
if (desc.equals(INJECTED_TRACE_TYPE.getDescriptor())) {
injectedTraceAnnotationVisitor = ne... |
java | public OpenStackRequest<R> queryString(String queryString) {
if (queryString != null) {
String[] params = queryString.split("&");
for (String param : params) {
String[] s = param.split("=");
if (s[0] != null && s[1] != null) {
queryPara... |
python | def get_settings_list(self):
"""The settings list used for building the cache id."""
return [
self.source,
self.output,
self.kwargs,
self.post_processors,
] |
python | def _attribute(permission='rwd', **kwds):
"""returns one property for each (key,value) pair in kwds;
each property provides the specified level of access(permission):
'r': readable, 'w':writable, 'd':deletable
"""
classname, classdict = class_space()
def _property(attrname, default):
... |
java | public CmsADEConfigData lookupConfiguration(CmsObject cms, String rootPath) {
CmsADEConfigData configData = internalLookupConfiguration(cms, rootPath);
return configData;
} |
java | public static Chart getMSDLineWithConfinedModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double a, double b, double c, double d) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanS... |
python | def injected(self, filename):
""" Return true if the file has already been injected before. """
full_path = os.path.expanduser(filename)
if not os.path.exists(full_path):
return False
with codecs.open(full_path, 'r+', encoding="utf-8") as fh:
contents = fh.read()
... |
java | @Override
public ByteBuffer read(ByteBuffer receiveBuffer) throws IOException {
if (!doHandshake(receiveBuffer))
return null;
if (!initialHSComplete)
throw new IllegalStateException("The initial handshake is not complete.");
if (log.isDebugEnabled()) {
l... |
python | def random(cls, alpha, size):
"""
Generate a random start using expected proportions, alpha.
These are used to parameterise a random draw from a Dirichlet
distribution.
An example, to split a dataset of 20 items into 3 groups of [10,
6, 4] items:
- alpha = [10, 6... |
java | @Override
public CPOptionCategory[] findByGroupId_PrevAndNext(
long CPOptionCategoryId, long groupId,
OrderByComparator<CPOptionCategory> orderByComparator)
throws NoSuchCPOptionCategoryException {
CPOptionCategory cpOptionCategory = findByPrimaryKey(CPOptionCategoryId);
Session session = null;
try {
... |
java | private boolean kNNABOD(Database db, Relation<V> relation, DBIDs ids, WritableDoubleDataStore abodvalues, DoubleMinMax minmaxabod) {
DistanceQuery<V> dq = db.getDistanceQuery(relation, SquaredEuclideanDistanceFunction.STATIC);
KNNQuery<V> knnq = db.getKNNQuery(dq, DatabaseQuery.HINT_OPTIMIZED_ONLY);
boolean... |
python | def get_words_iterable( letters, tamil_only=False ):
""" given a list of UTF-8 letters section them into words, grouping them at spaces """
# correct algorithm for get-tamil-words
buf = []
for idx,let in enumerate(letters):
if not let.isspace():
if istamil(let) or (not tamil_only):
... |
python | def shader_substring(body, stack_frame=1):
"""
Call this method from a function that defines a literal shader string as the "body" argument.
Dresses up a shader string in two ways:
1) Insert #line number declaration
2) un-indents
The line number information can help debug glsl comp... |
java | @Override
public void visitClassContext(final ClassContext context) {
try {
stack = new OpcodeStack();
super.visitClassContext(context);
} finally {
stack = null;
}
} |
java | private String[] getAttributeGroupObjectInterfaces(List<String> parentsName) {
return listToArray(parentsName.stream().map(XsdAsmUtils::firstToUpper).collect(Collectors.toList()), CUSTOM_ATTRIBUTE_GROUP);
} |
java | public boolean invokeEndpoint(final MessageEndpoint endpoint,
final SIBusMessage message, final AbstractConsumerSession session,
final SITransaction transaction, String debugMEName)
throws ResourceAdapterInternalException {
final String methodName = "invokeEndpoint";
... |
python | def multidict_to_dict(d):
"""
Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with
list values
:param d: a MultiDict or MultiValueDict instance
:return: a dict instance
"""
return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d)) |
java | public static int align0(final AffineGapAlignmentScoring<NucleotideSequence> scoring,
final NucleotideSequence seq1, final NucleotideSequence seq2,
final int offset1, final int length1, final int offset2, final int length2,
final int... |
python | def cli(ctx, compatible, forbid_post, generate_hashes, directory,
in_ext, out_ext, header, only_name, upgrade):
"""Recompile"""
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
OPTIONS.update({
'compatible_patterns': compatible,
'forbid_post': set(forbid_post),
... |
python | def mean_squared_error(df, col_true, col_pred=None):
"""
Compute mean squared error of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
... |
java | @Override
public StopSentimentDetectionJobResult stopSentimentDetectionJob(StopSentimentDetectionJobRequest request) {
request = beforeClientExecution(request);
return executeStopSentimentDetectionJob(request);
} |
java | @Deprecated
public StringBuilder writeToBuilder(Bean bean, boolean rootType) {
try {
write(bean, rootType, this.builder);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
return builder;
} |
python | def get_object(self, ObjectClass, id):
""" Retrieve object of type ``ObjectClass`` by ``id``.
| Returns object on success.
| Returns None otherwise.
"""
print('dynamo.get(%s, %s)' % (ObjectClass, str(id)))
resp = self.db.engine.get(ObjectClass, [id])
if resp:
... |
java | public Map<String, Object> toMap(QueryParameters params) {
Map<String, Object> result = null;
if (params != null) {
result = params.toMap();
}
return result;
} |
python | def ctr_geom(geom, masses):
""" Returns geometry shifted to center of mass.
Helper function to automate / encapsulate translation of a geometry to its
center of mass.
Parameters
----------
geom
length-3N |npfloat_| --
Original coordinates of the atoms
masses
length... |
java | @InternalApi
public com.google.bigtable.admin.v2.CreateClusterRequest toProto(String projectId) {
proto.setParent(NameUtil.formatInstanceName(projectId, instanceId));
proto.getClusterBuilder().setLocation(NameUtil.formatLocationName(projectId, zone));
return proto.build();
} |
java | @Override
public boolean isSynchronous() {
if (canBeSynchronous()) {
if (this.canBeAsynchronous()) {
String attr = this.getAttributeValue(PROP_SYNCHRONOUS_RESPONSE);
return (attr!=null && attr.equalsIgnoreCase("true"));
} else return true;
} el... |
java | public static double TruncatedPower(double value, double degree) {
double x = Math.pow(value, degree);
return (x > 0) ? x : 0.0;
} |
python | def calculate_pertubations(self):
""" experimental method to calculate finite difference parameter
pertubations. The pertubation values are added to the
Pst.parameter_data attribute
Note
----
user beware!
"""
self.build_increments()
self.paramet... |
python | def _parse_myinfo(client, command, actor, args):
"""Parse MYINFO and update the Host object."""
_, server, version, usermodes, channelmodes = args.split(None, 5)[:5]
s = client.server
s.host = server
s.version = version
s.user_modes = set(usermodes)
s.channel_modes = set(channelmodes) |
python | def translate_index_to_position(self, index):
"""
Given an index for the text, return the corresponding (row, col) tuple.
(0-based. Returns (0, 0) for index=0.)
"""
# Find start of this line.
row, row_index = self._find_line_start_index(index)
col = index - row_in... |
python | def _get_mixed_actions(labeling_bits, equation_tup, trans_recips):
"""
From a labeling for player 0, a tuple of hyperplane equations of the
polar polytopes, and a tuple of the reciprocals of the translations,
return a tuple of the corresponding, normalized mixed actions.
Parameters
----------
... |
python | async def pull_metrics(self, event_fn, loop=None):
"""
Method called by core.
Should not be overwritten.
"""
if self.lazy and not self.ready:
return None
logger = self.get_logger()
ts = timer()
logger.trace("Waiting for process event")
... |
python | def _reset_seaborn(gallery_conf, fname):
"""Reset seaborn."""
# Horrible code to 'unload' seaborn, so that it resets
# its default when is load
# Python does not support unloading of modules
# https://bugs.python.org/issue9072
for module in list(sys.modules.keys()):
if 'seaborn' in modul... |
python | def protected_resource_view(scopes=None):
"""
View decorator. The client accesses protected resources by presenting the
access token to the resource server.
https://tools.ietf.org/html/rfc6749#section-7
"""
if scopes is None:
scopes = []
def wrapper(view):
def view_wrapper(r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.