language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def stats(self):
"""
Gets performance statistics and server information
"""
status, _, body = self._request('GET', self.stats_path(),
{'Accept': 'application/json'})
if status == 200:
return json.loads(bytes_to_str(body))
... |
python | def deployment_operations_list(name, resource_group, result_limit=10, **kwargs):
'''
.. versionadded:: 2019.2.0
List all deployment operations within a deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
... |
java | void calcLastPos(RBBINode n) {
if (n == null) {
return;
}
if (n.fType == RBBINode.leafChar ||
n.fType == RBBINode.endMark ||
n.fType == RBBINode.lookAhead ||
n.fType == RBBINode.tag) {
// These are non-empty l... |
java | public String getCustomBundleProperty(String bundleName, String key, String defaultValue) {
return props.getProperty(prefix + PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_PROPERTY + bundleName + key,
defaultValue);
} |
python | def select_arch(self, src):
"""Looks if sources unsupported or untested
from arch else select arch.
"""
arch = self.arch
for item in self.unst:
if item in src:
arch = item
return arch |
java | private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
// Read in the non-transient fields
// (revocationDate, reason, authority)
ois.defaultReadObject();
// Defensively copy the revocation date
revocationDate = new Date(revocationDat... |
python | def get_upsampling_weight(in_channels, out_channels, kernel_size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (kernel_size + 1) // 2
if kernel_size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:kernel_size, :kernel_size]
filt = (1 ... |
python | def tz_path(name):
"""
Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str
"""
if not name:
raise ValueError('Invalid timezone')
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part == os.path.... |
python | def drawQuad(self, quad):
"""Draw a Quad.
"""
q = Quad(quad)
return self.drawPolyline([q.ul, q.ll, q.lr, q.ur, q.ul]) |
python | def subnet2block(subnet):
"""Convert a dotted-quad ip address including a netmask into a tuple
containing the network block start and end addresses.
>>> subnet2block('127.0.0.1/255.255.255.255')
('127.0.0.1', '127.0.0.1')
>>> subnet2block('127/255')
('127.0.0.0', '127.255.255.255')
>>> sub... |
python | def com_google_fonts_check_family_equal_font_versions(ttFonts):
"""Make sure all font files have the same version value."""
all_detected_versions = []
fontfile_versions = {}
for ttFont in ttFonts:
v = ttFont['head'].fontRevision
fontfile_versions[ttFont] = v
if v not in all_detected_versions:
... |
python | def summary(self):
""" Get the entry's summary text """
if self.get('Summary'):
return self.get('Summary')
body, more, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_summary,
body or more) if is_markdown else CallableProxy(None) |
java | public void free()
{
if (m_DependentConverter != null)
{
if (m_DependentConverter.getField() == null)
m_DependentConverter.free(); // Special case, must remove converter
m_DependentConverter = null;
}
super.free();
} |
java | public Document.Calendars.Calendar.ExceptedDays.ExceptedDay createDocumentCalendarsCalendarExceptedDaysExceptedDay()
{
return new Document.Calendars.Calendar.ExceptedDays.ExceptedDay();
} |
python | def ping(self, id):
""" Pings the motor with the specified id.
.. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast.
"""
pp = self._protocol.DxlPingPacket(id)
try:
self._send_packet(pp, error_handler=None)
retu... |
python | def init_app(self, app):
"""Flask application initialization.
The initialization will:
* Set default values for the configuration variables.
* Initialise the Flask mail extension.
* Configure the extension to avoid the email sending in case of debug
or ``MAIL_SUPP... |
python | def _get_item_str(self, res):
"""Return genes in any of these formats:
1. 19264, 17319, 12520, 12043, 74131, 22163, 12575
2. Ptprc, Mif, Cd81, Bcl2, Sash3, Tnfrsf4, Cdkn1a
3. 7: Ptprc, Mif, Cd81, Bcl2, Sash3...
"""
npl = self.pltvars.items_p_line # Numb... |
python | def _prepare_api(self, method, path, access_token, **kw):
'''
Get api url.
'''
headers = None
if access_token:
headers = {'Authorization': 'OAuth2 %s' % access_token}
if '/remind/' in path:
# sina remind api url is different:
return met... |
java | @Override
public DescribeMaintenanceWindowExecutionTasksResult describeMaintenanceWindowExecutionTasks(DescribeMaintenanceWindowExecutionTasksRequest request) {
request = beforeClientExecution(request);
return executeDescribeMaintenanceWindowExecutionTasks(request);
} |
java | public static GetStatusPOptions toGetStatusOptions(ExistsPOptions existsOptions) {
GetStatusPOptions.Builder getStatusOptionsBuilder = GetStatusPOptions.newBuilder();
if (existsOptions.hasCommonOptions()) {
getStatusOptionsBuilder.setCommonOptions(existsOptions.getCommonOptions());
}
if (existsOpt... |
python | def sha1(self):
"""
:return:
The SHA1 hash of the DER-encoded bytes of this name
"""
if self._sha1 is None:
self._sha1 = hashlib.sha1(self.dump()).digest()
return self._sha1 |
python | def total_detection_product_filename_generator(obs_info,nn):
"""
Generate image and sourcelist filenames for total detection products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: proposal_id,
visit_id, instrument, and detector
... |
java | @Override
public void setPoint3d(Point3d point3d) {
logger.debug("Setting point3d: x=" + point3d.x + ", y=" + point3d.y, ", z=" + point3d.z);
super.setPoint3d(point3d);
} |
python | def _BOW_FEATURE_EXTRACTOR(sf, target=None):
"""
Return an SFrame containing a bag of words representation of each column.
"""
if isinstance(sf, dict):
out = _tc.SArray([sf]).unpack('')
elif isinstance(sf, _tc.SFrame):
out = sf.__copy__()
else:
raise ValueError("Unrecogni... |
python | def check_files(filelist,
file_stage_manager=None,
return_found=True,
return_missing=True):
"""Check that all files in a list exist
Parameters
----------
filelist : list
The list of files we are checking for.
file_stage_manager : `fermipy.jo... |
python | def get_folder(self, title):
"""
Retrieve a folder by its title
Usage: C{engine.get_folder(title)}
Note that if more than one folder has the same title, only the first match will be
returned.
"""
for folder in self.configManager.allFolders:
... |
java | public static URL extractArchiveURL(URL jarUrl) throws MalformedURLException {
String urlFile = jarUrl.getFile();
int endIndex = urlFile.indexOf(WAR_URL_SEPARATOR);
if (endIndex != -1) {
// Tomcat's "jar:war:file:...mywar.war*/WEB-INF/lib/myjar.jar!/myentry.txt"
String w... |
python | def update(self, resource, uri=None, force=False, timeout=-1, custom_headers=None, default_values={}):
"""
Makes a PUT request to update a resource when a request body is required.
Args:
resource:
OneView resource dictionary.
uri:
Can be e... |
java | public ListTemplateResponse listTemplate(SmsRequest request) {
checkNotNull(request, "object request should not be null.");
InternalRequest internalRequest = this.createRequest("template", request, HttpMethodName.GET);
return this.invokeHttpClient(internalRequest, ListTemplateResponse.class);
... |
python | def execute(self, js_str, timeout=0, max_memory=0):
""" Exec the given JS value """
wrapped = "(function(){return (%s)})()" % js_str
return self.eval(wrapped, timeout, max_memory) |
java | static Object newInstance (ClassLoader classLoader, String className)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException
{
Class driverClass;
if (classLoader == null) {
driverClass = Class.forName(className);
} else {
dri... |
java | public ExpressRouteCrossConnectionInner updateTags(String resourceGroupName, String crossConnectionName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, crossConnectionName, tags).toBlocking().last().body();
} |
java | public FullyQualifiedNameFQNType createFullyQualifiedNameFQNTypeFromString(EDataType eDataType, String initialValue) {
FullyQualifiedNameFQNType result = FullyQualifiedNameFQNType.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of... |
java | private float unwoundPathSum(final PathPointer unique_path, int unique_depth,
int path_index) {
final float one_fraction = unique_path.get(path_index).one_fraction;
final float zero_fraction = unique_path.get(path_index).zero_fraction;
float next_one_portion = unique_path.get(... |
python | def replace_default_error_messages():
"""
Replace Django's generic error messages with MTP-specific versions
NB: avoid trailing full stops visually, they are added for screen readers in templates
"""
forms.Field.default_error_messages['required'] = _('This field is required')
forms.CharField.def... |
python | def generate_covalent_bond_graph(covalent_bonds):
"""Generates a graph of the covalent bond network described by the interactions.
Parameters
----------
covalent_bonds: [CovalentBond]
List of `CovalentBond`.
Returns
-------
bond_graph: networkx.Graph
A graph of the covalent... |
java | Table SYSTEM_PROCEDURECOLUMNS() {
Table t = sysTables[SYSTEM_PROCEDURECOLUMNS];
if (t == null) {
t = createBlankTable(sysTableHsqlNames[SYSTEM_PROCEDURECOLUMNS]);
// ----------------------------------------------------------------
// required
// -------... |
python | def sam_send(sock, line_and_data):
"""Send a line to the SAM controller, but don't read it"""
if isinstance(line_and_data, tuple):
line, data = line_and_data
else:
line, data = line_and_data, b''
line = bytes(line, encoding='ascii') + b' \n'
# print('-->', line, data)
sock.senda... |
python | def create(self, identifier, friendly_name=values.unset,
proxy_identifier=values.unset, proxy_identifier_sid=values.unset):
"""
Create a new ParticipantInstance
:param unicode identifier: The phone number of the Participant
:param unicode friendly_name: The string that yo... |
python | def get_indices(self, include_aliases=False):
"""
Get a dict holding an entry for each index which exists.
If include_alises is True, the dict will also contain entries for
aliases.
The key for each entry in the dict is the index or alias name. The
value is a dict hold... |
java | @Override
public PutResourceAttributesResult putResourceAttributes(PutResourceAttributesRequest request) {
request = beforeClientExecution(request);
return executePutResourceAttributes(request);
} |
java | public static int readBytesFromOtherInputStream(InputStream is, byte[] targetArray) throws IOException
{
assert targetArray != null;
if (targetArray.length == 0) return 0;
int len;
int off = 0;
while (off < targetArray.length && (len = is.read(targetArray, off, targetArray.le... |
java | protected void setup() throws SlickException {
if (targetDisplayMode == null) {
setDisplayMode(640,480,false);
}
Display.setTitle(game.getTitle());
Log.info("LWJGL Version: "+Sys.getVersion());
Log.info("OriginalDisplayMode: "+originalDisplayMode);
Log.info("TargetDisplayMode: "+targetDisplayM... |
python | def long_to_bytes(N, blocksize=1):
"""Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
such that the return values length is a multiple of ``blo... |
java | private OCSPReq createRequest(
SFPair<Certificate, Certificate> pairIssuerSubject)
{
Certificate issuer = pairIssuerSubject.left;
Certificate subject = pairIssuerSubject.right;
OCSPReqBuilder gen = new OCSPReqBuilder();
try
{
DigestCalculator digest = new SHA1DigestCalculator();
... |
java | public String addSortParams(boolean bIncludeFileName, boolean bForceUniqueKey)
{
String strSort = super.addSortParams(bIncludeFileName, bForceUniqueKey);
if (strSort.length() > 0)
return strSort; // Sort string was specified for this "QueryRecord"
Record stmtTable = this.getR... |
python | def floyd_warshall(weight):
"""All pairs shortest paths by Floyd-Warshall
:param weight: edge weight matrix
:modifies: weight matrix to contain distances in graph
:returns: True if there are negative cycles
:complexity: :math:`O(|V|^3)`
"""
V = range(len(weight))
for k in V:
for... |
python | def add_section(self, section, section_params):
"""
Adds parameters into this ConfigParams under specified section.
Keys for the new parameters are appended with section dot prefix.
:param section: name of the section where add new parameters
:param section_params: new paramete... |
java | private Term getMaxTerm(int i) {
Term maxTerm = terms[i];
if (maxTerm == null) {
return null;
}
Term term = maxTerm;
while ((term = term.next()) != null) {
maxTerm = term;
}
return maxTerm;
} |
python | def do_POST(self): # pylint: disable=g-bad-name
"""Process encrypted message bundles."""
self._IncrementActiveCount()
try:
if self.path.startswith("/upload"):
stats_collector_instance.Get().IncrementCounter(
"frontend_http_requests", fields=["upload", "http"])
logging.err... |
java | public boolean delete(final RegisteredService service) {
val del = new DeleteItemRequest().withTableName(dynamoDbProperties.getTableName())
.withKey(CollectionUtils.wrap(ColumnNames.ID.getColumnName(), new AttributeValue(String.valueOf(service.getId()))));
LOGGER.debug("Submitting delete req... |
java | public static void glColorMask(boolean red, boolean green, boolean blue, boolean alpha)
{
checkContextCompatibility();
nglColorMask(red, green, blue, alpha);
} |
java | public TypeSignature getTypeSignature(Type type) {
FullTypeSignature typeSignature = getFullTypeSignature(type);
if (typeSignature != null) {
return typeSignature;
}
if (type instanceof WildcardType) {
return getTypeArgSignature((WildcardType) type);
}
return null;
} |
python | def control(self) -> Optional[HTMLElement]:
"""Return related HTMLElement object."""
id = self.getAttribute('for')
if id:
if self.ownerDocument:
return self.ownerDocument.getElementById(id)
elif isinstance(id, str):
from wdom.document impor... |
python | def date_time_this_century(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the current century.
:param before_now: include days in current century before today
:param after_now: include days in current... |
java | private final void setExpiration(long expirationInMinutes) {
expirationInMilliseconds = System.currentTimeMillis()+ expirationInMinutes * 60 * 1000;
signature = null;
if (userData != null) {
encryptedBytes = null;
userData.addAttribute("expire", Long.toString(expirationInMillise... |
java | @JSConstructor
public static Scriptable jsConstructor(Context cx, Object[] args,
Function ctorObj,
boolean inNewExpr)
{
File result = new File();
if (args.length == 0 || args[0] == Context.getUndefinedValue()) ... |
java | public final void run() {
_interrupted = null;
_age = 0;
while (true) {
try {
_strategy.observe(_age);
if (_preparation != null) _preparation.run();
_result = execute();
if (_age > 0) {
_reporting.emi... |
java | public static IRing getMostComplexRing(IRingSet ringSet) {
int[] neighbors = new int[ringSet.getAtomContainerCount()];
IRing ring1, ring2;
IAtom atom1, atom2;
int mostComplex = 0, mostComplexPosition = 0;
/* for all rings in this RingSet */
for (int i = 0; i < ringSet.get... |
java | protected List<PType> cloneListType(List<PType> types)
{
List<PType> r = new LinkedList<PType>();
for (PType type : types)
{
r.add(type.clone());
}
return r;
} |
java | public synchronized Address selectDistributedWorkManager(Address own, DistributableWork work)
{
if (trace)
log.tracef("Own: %s, Work: %s", own, work);
/*
TODO
String value = getWorkManager(work);
if (value != null)
{
if (trace)
log.tracef("WorkMan... |
java | private static Collection<String> addOtherClasses(Collection<String> feats, List<? extends CoreLabel> info,
int loc, Clique c) {
String addend = null;
String pAnswer = info.get(loc - 1).get(AnswerAnnotation.class);
String p2Answer = info.get(loc - 2).get(AnswerAnnota... |
java | public void marshall(DescribeConfigurationRecordersRequest describeConfigurationRecordersRequest, ProtocolMarshaller protocolMarshaller) {
if (describeConfigurationRecordersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
... |
python | def clean(self, string, n_cols=None):
"""
Required reading!
http://nedbatchelder.com/text/unipain.html
Python 2 input string will be a unicode type (unicode code points).
Curses will accept unicode if all of the points are in the ascii range.
However, if any of the c... |
python | def _handle_incoming_data(self, conn):
"""
Handle incoming data on socket.
"""
connection = [c for c in self.connections if c.conn == conn][0]
data = conn.recv(1024)
if data:
connection.feed(data)
else:
self.connections.remove(connection) |
python | def run_example(path):
""" Returns returncode of example """
cmd = "{0} {1}".format(sys.executable, path)
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
res = proc.communicate()
if proc.returncode:
print(res[1].decode())
return proc.returncode |
python | def trainingDataDedupe(data, common_key, training_size=50000): # pragma: nocover
'''
Construct training data for consumption by the ActiveLearning
markPairs method from an already deduplicated dataset.
Arguments :
data -- Dictionary of records, where the keys are record_ids and
... |
java | synchronized NewEpochResponseProto newEpoch(
NamespaceInfo nsInfo, long epoch) throws IOException {
checkJournalStorageFormatted();
journalStorage.checkConsistentNamespace(nsInfo);
// if we are storing image too, check consistency as well
if (imageStorage.isFormatted()) {
imageStorage.... |
java | public void init(Record record, DateTimeField field, String mainFilesFieldName)
{
super.init(record);
m_field = field;
if (field != null)
if (field.getRecord() != record)
field.addListener(new FieldRemoveBOnCloseHandler(this));
this.mainFilesFieldName = ma... |
java | public void moveBody (BodyObject source, Place place)
{
// first remove them from their old place
leaveOccupiedPlace(source);
// then send a forced move notification to the body's client
LocationSender.forcedMove(source.getClientObject(), place.placeOid);
} |
java | public static Probe frameProbeFrom(Probe p) throws ProbeSenderException {
Probe fp = null;
try {
fp = new Probe(p.getProbeWrapper().getRespondToPayloadType());
} catch (UnsupportedPayloadType e1) {
throw new ProbeSenderException("Error in creating frame probe.", e1);
}
fp.setHopLimit(p.... |
python | def imgur_role(name, rawtext, text, *_):
"""Imgur ":imgur-title:`a/abc1234`" or ":imgur-description:`abc1234`" rst inline roles.
"Schedules" an API query.
:raises ImgurError: if text has invalid Imgur ID.
:param str name: Role name (e.g. 'imgur-title').
:param str rawtext: Entire role and value m... |
java | public static byte[] encypt(String str, byte[] key) {
byte[] b = null;
try {
SecretKey secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
b = cipher.doFinal(str.getBytes());
... |
java | public String constructName() {
String result = name;
if(dir != null) {
result = dir + "/" + result;
}
if(extension != null) {
result = result + "." + extension;
}
return result;
} |
python | def is_int_vector(l):
r"""Checks if l is a numpy array of integers
"""
if isinstance(l, np.ndarray):
if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):
return True
return False |
java | @Action(
semantics = SemanticsOf.SAFE
)
@ActionLayout(
bookmarking = BookmarkPolicy.AS_ROOT
)
@MemberOrder(sequence = "1")
public List<FullCalendar2WicketToDoItem> notYetComplete() {
final List<FullCalendar2WicketToDoItem> items = notYetCompleteNoUi();
if(item... |
python | def half_duration(self):
"""Half of the duration of the current interval."""
if self._interval is not None:
a, b = self._interval
return (b - a) * .5
else:
return self.interval_duration * .5 |
python | def grad_local_log_likelihood(self, x):
"""
d/dx y^T Cx + y^T d - exp(Cx+d)
= y^T C - exp(Cx+d)^T C
= (y - lmbda)^T C
"""
# Observation likelihoods
lmbda = np.exp(np.dot(x, self.C.T) + np.dot(self.inputs, self.D.T))
return (self.data - lmbda).dot(... |
python | def execute_function(self, func, *nargs, **kwargs):
"""
Execute a function object within the execution context.
@returns The result of the function call.
"""
# makes a copy of the func
import types
fn = types.FunctionType(func.func_code,
... |
python | def convert_to_article(request, entry_id):
"""
This method converts a tip entry to an unpublished article
:param entry_id: Tip entry to convert
:return: redirect to the edit page of the converted tip
"""
def get_entry_author(entry):
if not entry.optional_name:
return 'By Anon... |
java | protected void onDateLongClicked(final DayView dayView) {
if (longClickListener != null) {
longClickListener.onDateLongClick(MaterialCalendarView.this, dayView.getDate());
}
} |
python | def _browse(c):
"""
Open build target's index.html in a browser (using 'open').
"""
index = join(c.sphinx.target, c.sphinx.target_file)
c.run("open {0}".format(index)) |
python | def seq(self):
"""Seq: Get the Seq object from the sequence file, metadata file, or in memory"""
if self.sequence_file:
log.debug('{}: reading sequence from sequence file {}'.format(self.id, self.sequence_path))
tmp_sr = SeqIO.read(self.sequence_path, 'fasta')
return... |
java | public static INDArray asExampleArray(Window window, Word2Vec vec, boolean normalize) {
int length = vec.lookupTable().layerSize();
List<String> words = window.getWords();
int windowSize = vec.getWindow();
Preconditions.checkState(words.size() == vec.getWindow());
INDArray ret = ... |
java | public static int epollBusyWait(FileDescriptor epollFd, EpollEventArray events) throws IOException {
int ready = epollBusyWait0(epollFd.intValue(), events.memoryAddress(), events.length());
if (ready < 0) {
throw newIOException("epoll_wait", ready);
}
return ready;
} |
java | public byte[] getEncoded() throws SshException {
ByteArrayWriter baw = new ByteArrayWriter();
try {
baw.writeString(getAlgorithm());
baw.writeBigInteger(pubkey.getParams().getP());
baw.writeBigInteger(pubkey.getParams().getQ());
baw.writeBigInteger(pubkey.getParams().getG());
baw.writeBigInteger(pub... |
java | static public Date parseGpsTimestamp(String gpsTimestamp) throws Exception {
try {
Matcher matcherTime = patternTime.matcher(gpsTimestamp);
if( matcherTime.matches() ) {
int year = Integer.parseInt( matcherTime.group(1) );
int month = Integer.parseInt( matcherTime.group(2) );
int day = Integer.parse... |
java | @Override
public Object unMarshall(Response<DeleteResponse> response, Class<?> entity) {
try {
consume(response.getResult());
return statusMessage;
} catch (Exception e) {
throw new MappingException(e);
}
} |
java | public void considerDoubleClick(int button, int x, int y) {
if (doubleClickTimeout == 0) {
clickX = x;
clickY = y;
clickButton = button;
doubleClickTimeout = System.currentTimeMillis() + doubleClickDelay;
fireMouseClicked(button, x, y, 1);
} else {
if (clickButton == button) {
if ((Sy... |
java | public static Map<String, Type> matchVariableNames(final Type template, final Type real) {
final Map<TypeVariable, Type> match = matchVariables(template, real);
if (match.isEmpty()) {
return Collections.emptyMap();
}
final Map<String, Type> res = new HashMap<String, Type>();
... |
python | def insert(self, index, key, value):
"""Inserts the key, value pair before the item with the given index."""
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
... |
python | def _send(self):
"""
Take metrics from queue and send it to Datadog API
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.g... |
python | def update(self, report: str = None) -> bool:
"""Updates raw, data, and translations by fetching and parsing the METAR report
Returns True is a new report is available, else False
"""
if report is not None:
self.raw = report
else:
raw = self.service.fetch... |
python | def loglike(self, y, f, n):
r"""
Binomial log likelihood.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
... |
java | @Override
public int getSize()
{
int size = 0;
subscriptionsLock.readLock().lock();
try
{
for(LocalTopicSubscription subscription : subscriptionMap.values())
{
size += subscription.getLocalQueue().getSize();
}
}
finally
{
sub... |
java | public static DMatrixRMaj robustFundamental( List<AssociatedPair> matches ,
List<AssociatedPair> inliers , double inlierThreshold ) {
ConfigRansac configRansac = new ConfigRansac();
configRansac.inlierThreshold = inlierThreshold;
configRansac.maxIterations = 1000;
ConfigFundamental configFundament... |
java | private void notifyConsumer( AbstractMessage message )
{
consumersLock.readLock().lock();
try
{
switch (localConsumers.size())
{
case 0 : return; // Nobody's listening
case 1 :
notifySingleConsumer(localConsumers.get(0),message);
break;
default : // M... |
python | def get_wsgi_headers(self, environ):
"""This is automatically called right before the response is started
and returns headers modified for the given environment. It returns a
copy of the headers from the response with some modifications applied
if necessary.
For example the loc... |
java | @Override
public String indexValue(String name, Object value) {
// Check not null
if (value == null) {
return null;
}
// Parse big decimal
String svalue = value.toString();
BigInteger bi;
try {
bi = new BigInteger(svalue);
} c... |
java | public static void writeCSV(DataObjectModel model, Collection<? extends DataObject> collection, OutputStream os) throws IOException
{
BufferedOutputStream bos = new BufferedOutputStream(os);
OutputStreamWriter osw = new OutputStreamWriter(bos, "ISO-8859-1");
CSVWriter writer = new CSVWri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.