query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
// WKT returns the Well Known Text representation of the multipolygon | func (mp MultiPolygon) WKT() string {
var result string
switch len(mp.Coordinates) {
case 0:
result = "MULTIPOLYGON EMPTY"
default:
result = fmt.Sprintf("MULTIPOLYGON (%v)", array4ToWKTCoordinates(mp.Coordinates))
}
return result
} | csn |
def _get_private_key(cls, private_key_path, private_key_passphrase):
"""Get Snowflake private key by path or None."""
if private_key_path is None or private_key_passphrase is None:
return None
with open(private_key_path, 'rb') as key:
p_key = serialization.load_pem_priva... | return p_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()) | csn_ccr |
Reads back the list of CAN messages for automatically sending.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int count: The number of cyclic CAN messages to be received.
:return: List of received CAN messages (up to 16, see stru... | def read_cyclic_can_msg(self, channel, count):
"""
Reads back the list of CAN messages for automatically sending.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int count: The number of cyclic CAN messages to be received.... | csn |
Used to retrieve a fieldname for either field or association from a given column.
This method is used in foreign-key as primary-key contexts.
@param string $columnName
@return string
@throws MappingException | public function getFieldForColumn($columnName)
{
if (isset($this->fieldNames[$columnName])) {
return $this->fieldNames[$columnName];
} else {
foreach ($this->associationMappings as $assocName => $mapping) {
if ($this->isAssociationWithSingleJoinColumn($assocNa... | csn |
def near(self, x, y, max_distance=None):
""" Return documents near the given point
"""
expr = {
self : {'$near' : [x, y]}
}
if max_distance is not None:
expr[self]['$maxDistance'] | = max_distance
# if bucket_size is not None:
# expr['$bucketSize'] = max_distance
return QueryExpression(expr) | csn_ccr |
Reports the number of segment splits and merges related to a particular scale operation on a Stream. Both global
and Stream-specific counters are updated.
@param scope Scope.
@param streamName Name of the Stream.
@param splits Number of segment splits in the scale operation.
@param merges Numb... | public static void reportSegmentSplitsAndMerges(String scope, String streamName, long splits, long merges) {
DYNAMIC_LOGGER.updateCounterValue(globalMetricName(SEGMENTS_SPLITS), splits);
DYNAMIC_LOGGER.updateCounterValue(SEGMENTS_SPLITS, splits, streamTags(scope, streamName));
DYNAMIC_LOGGER.upd... | csn |
This method allows the caller to hint that they are about to access many
kernel values for a specific row. The row may be selected out from the
cache into its own location to avoid excess LRU overhead. Giving a
negative index indicates that we are done with the row, and removes it.
This method may be called multiple ti... | protected void accessingRow(int r)
{
if (r < 0)
{
specific_row_cache_row = -1;
specific_row_cache_values = null;
return;
}
if(cacheMode == CacheMode.ROWS)
{
double[] cache = partialCache.get(r);
if (cache ==... | csn |
func (client *Client) GetRouteApplications(routeGUID string, filters ...Filter) ([]Application, Warnings, error) {
request, err := client.newHTTPRequest(requestOptions{
RequestName: internal.GetRouteAppsRequest,
URIParams: map[string]string{"route_guid": routeGUID},
Query: ConvertFilterParameters(filters... | := item.(Application); ok {
fullAppsList = append(fullAppsList, app)
} else {
return ccerror.UnknownObjectInListError{
Expected: Application{},
Unexpected: item,
}
}
return nil
})
return fullAppsList, warnings, err
} | csn_ccr |
Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACEDEVICE
in the Flags parameter ... | def open(self):
"""
Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACED... | csn |
Validates the folder.
@param FolderInterface $folder
@return true|string | private function validateFolder(FolderInterface $folder)
{
$errorList = $this->get('validator')->validate($folder);
if ($errorList->count()) {
return $errorList->get(0)->getMessage();
}
return true;
} | csn |
def DEFINE_string(self, name, default, help, constant=False):
"""A helper for defining string options."""
self.AddOption(
| type_info.String(name=name, default=default or "", description=help),
constant=constant) | csn_ccr |
defines the KEY in the parent report parameters map where to get the subreport parameters map.
@param path where to get the parameter map for the subrerpot.
@return | public SubReportBuilder setParameterMapPath(String path) {
subreport.setParametersExpression(path);
subreport.setParametersMapOrigin(DJConstants.SUBREPORT_PARAMETER_MAP_ORIGIN_PARAMETER);
return this;
} | csn |
The function is used for creating lable with HTML text | def create_label(self, name, justify=Gtk.Justification.CENTER, wrap_mode=True, tooltip=None):
"""
The function is used for creating lable with HTML text
"""
label = Gtk.Label()
name = name.replace('|', '\n')
label.set_markup(name)
label.set_justify(justify)
... | csn |
Detects the format of the given unpacked backup directory
@param string $tempdir the name of the backup directory
@return string one of backup::FORMAT_xxx constants | public static function detect_backup_format($tempdir) {
global $CFG;
require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');
if (convert_helper::detect_moodle2_format($tempdir)) {
return backup::FORMAT_MOODLE;
}
// see if a converter can identi... | csn |
Load a list of records in a context for a user competency.
@param int $usercompetencyid The id of the user competency.
@param context $context Context to filter the evidence list.
@param string $sort The field from the evidence table to sort on.
@param string $order The sort direction
@param int $skip Limitstart.
@par... | public static function get_records_for_usercompetency($usercompetencyid,
\context $context,
$sort = '',
$order = 'ASC',
... | csn |
Wraps HTTP call into a good mould
@param string $method
@param string $endpoint
@param array $data
@return Horntell\Http\Response
@throws Horntell\Errors\* | public function send($method, $endpoint, $data = [])
{
try
{
$request = $this->client->createRequest($method, $endpoint, ['body' => json_encode($data)]);
return new Response($this->client->send($request));
}
catch(GuzzleExceptions\RequestException $e)
{
// pass the exception to a helper method,
/... | csn |
void moveBlockToHead(BlockInfo b) {
blockList = b.listRemove(blockList, this);
| blockList = b.listInsert(blockList, this, -1);
} | csn_ccr |
func decodeLEB128(input []byte) (uint, []byte) {
var num, sz uint
var b byte
for {
b = input[sz]
num |= (uint(b) & payload) << (sz * 7) // concats 7 bits chunks
sz++
| if uint(b)&continuation == 0 || sz == uint(len(input)) {
break
}
}
return num, input[sz:]
} | csn_ccr |
Stores given document, returns raven generated id in callback.
@param {string} db
@param {string} entityName
@param {Object} doc
@param {Function} cb | function (db, entityName, doc, cb) {
request.post({
url: host + 'databases/' + db + '/docs',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Raven-Entity-Name': entityName
},
body: JSON.stringify(doc)
}, function (error, response, resBody) {
if (!error && (response.sta... | csn |
using the restify handler composer, create a middleware on the fly that
re-requires the file on every load executes it.
@private
@function reloadProxy
@param {Object} opts an options object
@param {String} opts.basePath The basepath to resolve source files.
@param {String} opts.method http verb
@param {Object} opts.log... | function reloadProxy(opts, cb) {
assert.object(opts, 'opts');
assert.string(opts.basePath, 'opts.basePath');
assert.optionalString(opts.excludePath, 'opts.excludePath');
assert.string(opts.method, 'opts.method');
assert.object(opts.req, 'opts.req');
assert.object(opts.res, 'opts.res');
asser... | csn |
Create a new instance from an object and some arguments
@function mask
@param {function} obj The basis for the constructor
@param {array} args The arguments to pass to the constructor
@return {object} The new object that has been constructed | function mask( obj ){
if ( Object.create ){
var T = function Masked(){};
T.prototype = obj;
return new T();
}else{
return Object.create( obj );
}
} | csn |
public void addNotIn(String attribute, Query subQuery)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getAlias()));
| addSelectionCriteria(ValueCriteria.buildNotInCriteria(attribute, subQuery, getUserAlias(attribute)));
} | csn_ccr |
public function stream_seek($offset, $whence = SEEK_SET)
{
switch ($whence) {
case SEEK_SET:
$this->currentlyOpenedFile->position($offset);
break;
| case SEEK_CUR:
$this->currentlyOpenedFile->offsetPosition($offset);
break;
case SEEK_END:
$this->currentlyOpenedFile->seekToEnd();
$this->currentlyOpenedFile->offsetPosition($offset);
}
return true;
} | csn_ccr |
Generates configuration file from config specifications | def config(config, skip_defaults):
"""
Generates configuration file from config specifications
"""
configurator = ClickConfigurator(
vodka.plugin,
skip_defaults=skip_defaults
)
configurator.configure(vodka.config.instance, vodka.config.InstanceHandler)
try:
dst = m... | csn |
def get_sources(arxiv_id):
"""
Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401... | \
canonical form.
:returns: A ``TarFile`` object of the sources of the arXiv preprint or \
``None``.
"""
try:
request = requests.get(ARXIV_EPRINT_URL.format(arxiv_id=arxiv_id))
request.raise_for_status()
file_object = io.BytesIO(request.content)
retur... | csn_ccr |
returns the file name of the url.
@param aUrl the url
@return the name of the file | public static Optional<String> getFileName(final String aUrl) {
if (aUrl != null) {
int index = aUrl.lastIndexOf('/');
if (index > 0) {
final String file = aUrl.substring(index + 1);
if (file.contains(".")) {
return Optional.of(file);
}
}
}
ret... | csn |
Query to get the definition 12 063 value if the extension exists
@param srsId
srs id
@return definition or null
@since 1.2.1 | public String getDefinition_12_063(long srsId) {
String definition = null;
if (hasDefinition_12_063()) {
definition = crsWktExtension.getDefinition(srsId);
}
return definition;
} | csn |
public function get_row_attribs($index = null)
{
if ($index === null) {
| $index = $this->rowindex;
}
return $this->rows[$index] ? $this->rows[$index]->attrib : null;
} | csn_ccr |
python mock post request | def requests_post(url, data=None, json=None, **kwargs):
"""Requests-mock requests.post wrapper."""
return requests_request('post', url, data=data, json=json, **kwargs) | cosqa |
public function recPath($pid)
{
if (!isset($this->recPath_cache[$pid])) {
$this->recPath_cache[$pid] = BackendUtility::getRecordPath($pid, | $this->perms_clause, 20);
}
return $this->recPath_cache[$pid];
} | csn_ccr |
public static Scan convertStringToScan(String base64) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(base64));
DataInputStream dis | = new DataInputStream(bis);
Scan scan = new Scan();
scan.readFields(dis);
return scan;
} | csn_ccr |
Defaults to empty string which produces no encoding. | def tag( params )
# TODO: make these method args if possible
tag = params['tag']
attr = params['attr']
cdata = params['cdata']
unless attr.kind_of?( HTML::AutoAttr )
attr = HTML::AutoAttr.new( attr, @sorted )
end
#... | csn |
Determines whether an element is present on the page with no wait
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string used to query the element | def is_present_no_wait(self, locator):
"""
Determines whether an element is present on the page with no wait
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string used to query the element
"""
# first attempt to locate the el... | csn |
@Nonnull
private EChange _queueUniqueWorkItem (@Nonnull final IIndexerWorkItem aWorkItem)
{
ValueEnforcer.notNull (aWorkItem, "WorkItem");
// Check for duplicate
m_aRWLock.writeLock ().lock ();
try
{
if (!m_aUniqueItems.add (aWorkItem))
{
LOGGER.info ("Ignoring work item " +... | ("Queued work item " + aWorkItem.getLogText ());
// Remove the entry from the dead list to avoid spamming the dead list
if (m_aDeadList.getAndRemoveEntry (x -> x.getWorkItem ().equals (aWorkItem)) != null)
LOGGER.info ("Removed the new work item " + aWorkItem.getLogText () + " from the dead list");
... | csn_ccr |
func ValidateEvent(eventCategory EventCategory, event Event) bool {
valid := false
switch eventCategory {
case EventCategoryDefined:
valid = int(event) >= 0 && event < EventDefinedLast
case EventCategoryUndefined:
valid = int(event) >= 0 && event < EventUndefinedLast
case EventCategoryStarted:
valid = int(ev... | EventCategoryStopped:
valid = int(event) >= 0 && event < EventStoppedLast
case EventCategoryShutdown:
valid = int(event) >= 0 && event < EventShutdownLast
case EventCategoryPmsuspended:
valid = int(event) >= 0 && event < EventPMSuspendedLast
}
return valid
} | csn_ccr |
// SetTableRanges sets "KeyRanges" for "kv.Request" by converting "tableRanges"
// to "KeyRanges" firstly. | func (builder *RequestBuilder) SetTableRanges(tid int64, tableRanges []*ranger.Range, fb *statistics.QueryFeedback) *RequestBuilder {
if builder.err != nil {
return builder
}
builder.Request.KeyRanges = TableRangesToKVRanges(tid, tableRanges, fb)
return builder
} | csn |
static function render($view, array $data = []) {
if (file_exists($view)) {
if (is_array($data)) {
foreach ($data as $_data => $_value) {
if (Config::get('security.anti_xss') && is_string($_value)) {
$_value = Text::entities($_value);
... |
if ($file_ext == 'php' || $file_ext == 'phtml') {
include($view);
} else {
readfile($view);
}
$output = ob_get_clean();
return $output;
}
return false;
} | csn_ccr |
public NotificationConfiguration getBucketNotification(String bucketName)
throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException,
InsufficientDataException, IOException, InvalidKeyException, NoResponseException,
XmlPullParserException, ErrorResponseException,... |
HttpResponse response = executeGet(bucketName, null, null, queryParamMap);
NotificationConfiguration result = new NotificationConfiguration();
try {
result.parseXml(response.body().charStream());
} finally {
response.body().close();
}
return result;
} | csn_ccr |
Ping request to check status of elasticsearch host | def ping(self, callback=None, **kwargs):
"""
Ping request to check status of elasticsearch host
"""
self.client.fetch(
self.mk_req('', method='HEAD', **kwargs),
callback = callback
) | csn |
Converts our object from using one coordinate map to another.
NOTE: In some cases this only approximately preserves the
equivalent point values when transforming between coordinate
spaces. | def convert_mapper(self, tomap):
"""
Converts our object from using one coordinate map to another.
NOTE: In some cases this only approximately preserves the
equivalent point values when transforming between coordinate
spaces.
"""
frommap = self.crdmap
if ... | csn |
Limak is a little polar bear.
He is playing a video game and he needs your help.
There is a row with N cells, each either empty or occupied by a soldier, denoted by '0' and '1' respectively.
The goal of the game is to move all soldiers to the right (they should occupy some number of rightmost cells).
The only possible ... | for _ in range(int(input())):
l=list(map(int,input().strip()))
for j in range(len(l)-1,-1,-1):
if l[j]==1:
l.pop()
else:
break
if l.count(1):
time,prev,z,c=0,0,0,0
for j in range(len(l)-1,-1,-1):
if l[j]==0:
z+=1
continue
if prev!=z:
prev=z
c+=1
time+=c+z
print(time)
else:
... | apps |
Force any remaining liquid to dispense. The liquid will be dispensed at
the current location of pipette | async def blow_out(self, mount):
"""
Force any remaining liquid to dispense. The liquid will be dispensed at
the current location of pipette
"""
this_pipette = self._attached_instruments[mount]
if not this_pipette:
raise top_types.PipetteNotAttachedError(
... | csn |
def _redirect(self, args):
"""
asks the client to use a different server
This method redirects the client to another server, based on
the requested virtual host and/or capabilities.
RULE:
When getting the Connection.Redirect method, the client
SHOULD re... | list.
PARAMETERS:
host: shortstr
server to connect to
Specifies the server to connect to. This is an IP
address or a DNS name, optionally followed by a colon
and a port number. If no port number is specified, the
cl... | csn_ccr |
public String linkTo(@javax.annotation.Nonnull final File file) throws | IOException {
return codeFile(file);
} | csn_ccr |
def has_child_bins(self, bin_id):
"""Tests if a bin has any children.
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``bin_id`` has children,
``false`` otherwise
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ... | raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinHierarchySession.has_child_bins
if self._catalog... | csn_ccr |
public void setTimeUnit(com.google.api.ads.admanager.axis.v201808.TimeUnit timeUnit) {
| this.timeUnit = timeUnit;
} | csn_ccr |
public function updateCartObject($cart) {
if (isset($cart->customer_id)) {
$cart->customer_id = (string) $cart->customer_id;
}
// Some ecommerce backends, like hybris, don't save the billing like they
// do with shipping. So if a billing was set we don't want it to be
// overwritten when the ... | // We use it as array internally everywhere, even set as array.
$cart->carrier = (array) $cart->carrier;
// If carrier is with empty structure, we remove it.
if (empty($cart->carrier['carrier_code'])) {
unset($cart->carrier);
}
}
$this->cart = $cart;
$this->updateCart... | csn_ccr |
public void sendRequest(String path, RequestOptions options) throws IOException, JSONException {
String rootUrl;
if (path == null) {
throw new IllegalArgumentException("'path' parameter can't be null.");
}
if (path.indexOf(BMSClient.HTTP_SCHEME) == 0 && path.contains(":")) ... | if(MCATenantId == null){
MCATenantId = BMSClient.getInstance().getBluemixAppGUID();
}
String bluemixRegionSuffix = MCAAuthorizationManager.getInstance().getBluemixRegionSuffix();
if(bluemixRegionSuffix == null){
bluemixRegionSuffix = BMSClient.get... | csn_ccr |
Returns the ImageId to use | def get_imageid(vm_):
'''
Returns the ImageId to use
'''
image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if image.startswith('ami-'):
return image
# a poor man's cache
if not hasattr(get_imageid, 'images'):
get_imageid.images =... | csn |
// processAliasedTable produces a builder subtree for the given AliasedTableExpr.
// If the expression is a subquery, then the primitive will create a table
// for it in the symtab. If the subquery is a route, then we build a route
// primitive with the subquery in the From clause, because a route is more
// versatile ... | func (pb *primitiveBuilder) processAliasedTable(tableExpr *sqlparser.AliasedTableExpr) error {
switch expr := tableExpr.Expr.(type) {
case sqlparser.TableName:
return pb.buildTablePrimitive(tableExpr, expr)
case *sqlparser.Subquery:
spb := newPrimitiveBuilder(pb.vschema, pb.jt)
switch stmt := expr.Select.(type... | csn |
protected function getPageTemplateIcons()
{
$icons = [];
$templates = $this->getContainer()->getParameter('networking_init_cms.page.templates');
foreach ($templates as $key => $template) {
| $icons[$key] = isset($template['icon']) ? $template['icon'] : '';
}
return $icons;
} | csn_ccr |
Set where condition.
@param string $flag
@param string $value
@return $this | public function where($flag, $value = null)
{
if (!in_array(strtolower($flag), static::$searchCriteria)) {
throw new InvalidArgumentException("Invalid where criteria '{$flag}'");
}
$this->where[$flag] = $value;
return $this;
} | csn |
Find a set of tasks.
@param [Hash] datum Hash of filters
@option datum [Integer] :limit max amount of results to return per request
@option datum [Integer] :page page of request
@option datum [String] :group task group
@option datum [String] :class task class
@option datum [Integer] :status Integerish the status ... | def find_tasks(datum = nil)
current_path = '/api/v1/tasks'
pb = SFRest::Pathbuilder.new
@conn.get URI.parse(pb.build_url_query(current_path, datum)).to_s
end | csn |
private Map<SessionStatus, MetricsTimeVaryingInt>
createSessionStatusToMetricsMap() {
Map<SessionStatus, MetricsTimeVaryingInt> m =
new HashMap<SessionStatus, MetricsTimeVaryingInt>();
for (SessionStatus endState : SESSION_END_STATES) {
String | name = endState.toString().toLowerCase() + "_sessions";
m.put(endState, new MetricsTimeVaryingInt(name, registry));
}
return m;
} | csn_ccr |
public function refreshToken() {
if ($this->apiClient->getAccessToken() != null) {
| $dbh = new PDO('sqlite:examples.sqlite');
$this->saveToken($dbh, true, $this->apiClient->getAccessToken());
}
} | csn_ccr |
A helper to create the XML representation of the float style
@param util a util
@param appendable the destination
@param numberStyleName the style name ("currency-style", ...)
@param number the number itslef
@throws IOException if an I/O error occurs | void appendXMLHelper(final XMLUtil util, final Appendable appendable, final String numberStyleName, final CharSequence number) throws IOException {
this.numberStyle.appendXMLHelper(util, appendable, numberStyleName, number);
} | csn |
func (s *AuthServer) AuthenticateWebUser(req AuthenticateUserRequest) (services.WebSession, error) {
if req.Session != nil {
session, err := s.GetWebSession(req.Username, req.Session.ID)
if err != nil {
return nil, trace.AccessDenied("session is invalid or has expired")
}
return session, nil
}
if err := s... |
}
if err := s.UpsertWebSession(req.Username, sess); err != nil {
return nil, trace.Wrap(err)
}
sess, err = services.GetWebSessionMarshaler().GenerateWebSession(sess)
if err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
} | csn_ccr |
how to capitalize first item in list python | def fmt_camel(name):
"""
Converts name to lower camel case. Words are identified by capitalization,
dashes, and underscores.
"""
words = split_words(name)
assert len(words) > 0
first = words.pop(0).lower()
return first + ''.join([word.capitalize() for word in words]) | cosqa |
public function addError(ErrorInterface $error)
{
// create a local copy of the error stack
$errors = $this->errors;
| // append the error to the stack
$errors[] = $error;
// copy the error stack back to the thread context
$this->errors = $errors;
} | csn_ccr |
def delete_project(self, tenant_name, part_name):
"""Delete project on the DCNM.
:param tenant_name: name of project.
:param part_name: name of partition.
"""
res = self._delete_partition(tenant_name, part_name)
if res and res.status_code in self._resp_ok:
LO... | if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s organization in DCNM.", tenant_name)
else:
LOG.error("Failed to delete %(org)s organization in DCNM."
"Response: %(res)s", {'org': tenant_name, 'res': res})
raise dexc.DfaClientReques... | csn_ccr |
Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists | function ( MaterialNode ) {
var mappingType = MaterialNode.MappingInformationType;
var referenceType = MaterialNode.ReferenceInformationType;
if ( mappingType === 'NoMappingInformation' ) {
return {
dataSize: 1,
buffer: [ 0 ],
indices: [ 0 ],
mappingType: 'AllSame',
referenceTyp... | csn |
Parses all PROCHECK files in a directory and returns a Pandas DataFrame of the results
Args:
quality_directory: path to directory with PROCHECK output (.sum files)
Returns:
Pandas DataFrame: Summary of PROCHECK results | def parse_procheck(quality_directory):
"""Parses all PROCHECK files in a directory and returns a Pandas DataFrame of the results
Args:
quality_directory: path to directory with PROCHECK output (.sum files)
Returns:
Pandas DataFrame: Summary of PROCHECK results
"""
# TODO: save as... | csn |
Returns given Type if exception is null, else respective exception is thrown. | public T get()
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException {
if (ex == null) {
return type;
}
if (ex instanceo... | csn |
overrides the visitor capture source lines for the method
@param obj
the method object for the currently parsed method | @Override
public void visitMethod(final Method obj) {
methodName = obj.getName();
if (Values.STATIC_INITIALIZER.equals(methodName) || Values.CONSTRUCTOR.equals(methodName)) {
return;
}
List<String> parms = SignatureUtils.getParameterSignatures(obj.getSignature());
... | csn |
decorator that catches and returns an exception from wrapped function | def capture_exception(fn):
"""decorator that catches and returns an exception from wrapped function"""
def wrapped(*args):
try:
return fn(*args)
except Exception as e:
return e
return wrapped | csn |
Serialize nested HasUID instances to a flat dictionary
**Parameters**:
* **include_class** - If True (the default), the name of the class
will also be saved to the serialized dictionary under key
:code:`'__class__'`
* **save_dynamic** - If True, dynamic properties are writt... | def serialize(self, include_class=True, save_dynamic=False, **kwargs):
"""Serialize nested HasUID instances to a flat dictionary
**Parameters**:
* **include_class** - If True (the default), the name of the class
will also be saved to the serialized dictionary under key
:cod... | csn |
public static function sign(
string $message,
SignatureSecretKey $privateKey,
$encoding = Halite::ENCODE_BASE64URLSAFE
): string {
$signed = \sodium_crypto_sign_detached(
$message,
$privateKey->getRawKeyMaterial()
);
| $encoder = Halite::chooseEncoder($encoding);
if ($encoder) {
return (string) $encoder($signed);
}
return (string) $signed;
} | csn_ccr |
// IsParentDeviceHasChildrenError returns if the given error or its cause is
// ErrParentDeviceHasChildren. | func IsParentDeviceHasChildrenError(err interface{}) bool {
if err == nil {
return false
}
// In case of a wrapped error, check the cause first.
value := err
cause := errors.Cause(err.(error))
if cause != nil {
value = cause
}
_, ok := value.(*ErrParentDeviceHasChildren)
return ok
} | csn |
def out_file_name(out_dir, fname, ext=None):
"""Return path of output file, given a directory, file name and extension.
If fname is a path, it is converted to its basename.
Args:
out_dir (str): path to the directory where output should be written.
fname (str): path to the input file.
... | str: out_dir + fname with extension replaced. If `ext` is `None`, the
original extension is kept.
"""
if ext is None:
return os.path.join(out_dir, os.path.basename(fname))
fname = remove_ext(fname)
return os.path.join(out_dir, '{}.{}'.format(fname, ext)) | csn_ccr |
func Init(r io.ReaderAt) (*FS, error) {
fs := &FS{
r: r,
buf: make([]byte, 1024),
BlockSize: superSize,
}
var super diskSuper
if _, err := fs.read(superOff, 0, &super); err != nil {
return nil, err
}
if super.Magic != superMagic {
return nil, fmt.Errorf("bad magic %#x wanted %#x", super.... | = int(bsize)
fs.NumBlock = int64(super.Nblock)
fs.numGroup = (super.Nblock + super.Blockspergroup - 1) / super.Blockspergroup
fs.g = make([]*diskGroup, fs.numGroup)
fs.inodesPerGroup = super.Inospergroup
fs.blocksPerGroup = super.Blockspergroup
if super.Revlevel >= 1 {
fs.inodeSize = uint32(super.Inosize)
} e... | csn_ccr |
func (rs *retributionStore) IsBreached(chanPoint *wire.OutPoint) (bool, error) {
var found bool
err := rs.db.View(func(tx *bbolt.Tx) error {
retBucket := tx.Bucket(retributionBucket)
| if retBucket == nil {
return nil
}
var chanBuf bytes.Buffer
if err := writeOutpoint(&chanBuf, chanPoint); err != nil {
return err
}
retInfo := retBucket.Get(chanBuf.Bytes())
if retInfo != nil {
found = true
}
return nil
})
return found, err
} | csn_ccr |
Find an instance identified by nb_catalog_tag_key field.
@param mixed $nb_catalog Catalog that owns Catalog Tag
@param string $key Key to search
@return CNabuCatalogTag Returns a valid instance if exists or null if not. | public static function findByKey($nb_catalog, $key)
{
$nb_catalog_id = nb_getMixedValue($nb_catalog, 'nb_catalog_id');
if (is_numeric($nb_catalog_id)) {
$retval = CNabuCatalogTag::buildObjectFromSQL(
'select * '
. 'from nb_catalog_tag '
... | csn |
public function AddMessage($ConversationID = '') {
$this->Form->SetModel($this->ConversationMessageModel);
if (is_numeric($ConversationID) && $ConversationID > 0)
$this->Form->AddHidden('ConversationID', $ConversationID);
if ($this->Form->AuthenticatedPostBack()) {
$Conversati... | if (!is_numeric($LastMessageID))
$LastMessageID = $NewMessageID - 1;
$Session = Gdn::Session();
$MessageData = $this->ConversationMessageModel->GetNew($ConversationID, $LastMessageID);
$this->Conversation = $Conversation;
$this->MessageDa... | csn_ccr |
Select the right file uri scheme according to the operating system | def file_uri(fname):
"""Select the right file uri scheme according to the operating system"""
if os.name == 'nt':
# Local file
if re.search(r'^[a-zA-Z]:', fname):
return 'file:///' + fname
# UNC based path
else:
return 'file://' + fname
else:
... | csn |
Minify CSS files.
@param array $files
@return string minified CSS code | public static function css_files(array $files) {
if (empty($files)) {
return '';
}
$compressed = array();
foreach ($files as $file) {
$content = file_get_contents($file);
if ($content === false) {
$compressed[] = "\n\n/* Cannot read CS... | csn |
public function randomGet( $n = null, $returnContainer = false, $removeFromContainer = false )
{
$n = $n === null ? 1 : (int) $n;
// anything to give?
if( 0 === $containerSize = $this->count() ) {
if( $returnContainer or $n > 1 ) {
return $this->newContainer();
... | // asking for more than we've got?
if( $n <= $containerSize ) {
$keys = array_flip( array_rand( $this->collection, $n ) );
$output->add( array_intersect_key( $this->collection, $keys ) );
if( $removeFromContainer ) {
$this->collect... | csn_ccr |
Creates the template for the migration file.
@return static
@since 1.1.0
@author Eddilbert Macharia (http://eddmash.com) <edd.cowan@gmail.com> | private function getFileTemplate()
{
$content = FormatFileContent::createObject();
$content->addItem('<?php');
$content->addItem(
sprintf(
'/**Migration file generated at %s on %s by PowerOrm(%s)*/',
date('h:m:i'),
date('D, jS F Y')... | csn |
def clear_assessments(self):
"""Clears the assessments.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
|
"""
# Implemented from template for osid.learning.ActivityForm.clear_assets_template
if (self.get_assessments_metadata().is_read_only() or
self.get_assessments_metadata().is_required()):
raise errors.NoAccess()
self._my_map['assessmentIds'] = self._assessment... | csn_ccr |
python check if path is directory or file | def valid_file(path: str) -> bool:
"""
Verifies that a string path actually exists and is a file
:param path: The path to verify
:return: **True** if path exist and is a file
"""
path = Path(path).expanduser()
log.debug("checking if %s is a valid file", path)
return path.exists() and pa... | cosqa |
// InsertBlockPrevNext inserts a new row of the block_chain table. | func InsertBlockPrevNext(db *sql.DB, blockDbID uint64,
hash, prev, next string) error {
rows, err := db.Query(internal.InsertBlockPrevNext, blockDbID, prev, hash, next)
if err == nil {
return rows.Close()
}
return err
} | csn |
Returns the banner comment block, based on the given options
@param {object} options
@param {string} [options.banner] - If set, then this banner will be used exactly as-is
@param {string} [options.template] - A Lodash template that will be compiled to build the banner
@param {string} [options.file] - A file containing... | function getBanner (options) {
if (!options.banner) {
if (typeof options.pkg === "string") {
// Read the package.json file
options.pkg = readJSON(options.pkg);
}
if (!options.template) {
// Read the banner template from a file
options.template = findFile(options.file);
}
... | csn |
def fast_compare(tree1, tree2):
""" This is optimized to compare two AST trees for equality.
It makes several assumptions that are currently true for
AST trees used by rtrip, and it doesn't examine the _attributes.
"""
geta = ast.AST.__getattribute__
work = [(tree1, tree2)]
pop = w... |
type_ = type
list_ = list
while work:
n1, n2 = pop()
try:
f1 = geta(n1, '_fields')
f2 = geta(n2, '_fields')
except exception:
if type_(n1) is list_:
extend(zipl(n1, n2))
continue
if n1 == n2:
... | csn_ccr |
implements the visitor to make sure the class is at least java 1.4 and to reset the opcode stack | @Override
public void visitClassContext(ClassContext classContext) {
try {
JavaClass cls = classContext.getJavaClass();
if (cls.getMajor() >= Const.MAJOR_1_4) {
stack = new OpcodeStack();
regValueType = new HashMap<Integer, State>();
su... | csn |
function createPointerEvaluator(target) {
// Use cache to store already received values.
var cache = {};
return function(pointer) {
if (!isValidJSONPointer(pointer)) {
// If it's not, an exception will be thrown.
throw new ReferenceError(ErrorMessage.INVALID_POINTER);
}
// ... | list is not empty
// and returned value is not an undefined.
while (!_.isUndefined(value) && !_.isUndefined(token = tokensList.pop())) {
// Evaluate the token in current context.
// `getValue()` might throw an exception, but we won't handle it.
value = getValue(value, token);
... | csn_ccr |
Given a list of objects, returns the min value in its appropriate type
also, interprets String as Number and returns appropriately
min(1d,2l,3) == Optional.of(1d)
min("1.0",2l,d) == Optional.of(1.0)
min("a", "b", "c") == Optional.empty()
min([]) == Optional.empty() | public static Optional<Number> min( List<Object> args ) {
if(args == null || args.size() == 0) {
return Optional.empty();
}
Integer minInt = Integer.MAX_VALUE;
Double minDouble = Double.MAX_VALUE;
Long minLong = Long.MAX_VALUE;
boolean found = false;
... | csn |
Submit a runnable. | public <T> Future<T> submit(Runnable runnable, T result) {
return mService.submit(runnable, result);
} | csn |
Drops dataroot and remove test database tables
@throws coding_exception
@return void | public static function drop_site() {
if (!defined('BEHAT_UTIL')) {
throw new coding_exception('This method can be only used by Behat CLI tool');
}
self::reset_dataroot();
self::drop_database(true);
self::drop_dataroot();
} | csn |
func (c *conn) Receive() (*Request, error) {
if d := c.ReadTimeout; d != 0 {
c.SetReadDeadline(time.Now().Add(d))
}
r := &Request{Addr: c.rwc.RemoteAddr(), conn: | c}
_, err := r.ReadFrom(c)
if err != nil {
return nil, err
}
return r, nil
} | csn_ccr |
Convenience method to set the underlying bean instance for a proxy.
@param proxy the proxy instance
@param beanInstance the instance of the bean | public static <T> void setBeanInstance(String contextId, T proxy, BeanInstance beanInstance, Bean<?> bean) {
if (proxy instanceof ProxyObject) {
ProxyObject proxyView = (ProxyObject) proxy;
proxyView.weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean));
}
} | csn |
// commitCircuits persistently adds a circuit to the switch's circuit map. | func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
*CircuitFwdActions, error) {
return s.circuits.CommitCircuits(circuits...)
} | csn |
def mk_complex_format_func(fmt):
"""
Function used internally to generate functions to format complex |
valued data.
"""
fmt = fmt + u"+i" + fmt
def complex_format_func(z):
return fmt % (z.real, z.imag)
return complex_format_func | csn_ccr |
func (c *Client) CreateLogentries(i *CreateLogentriesInput) (*Logentries, error) {
if i.Service == "" {
return nil, ErrMissingService
}
if i.Version == 0 {
return nil, ErrMissingVersion
}
path := fmt.Sprintf("/service/%s/version/%d/logging/logentries", i.Service, i.Version)
resp, err := c.PostForm(path, i, ... | err != nil {
return nil, err
}
var l *Logentries
if err := decodeJSON(&l, resp.Body); err != nil {
return nil, err
}
return l, nil
} | csn_ccr |
Get system.
@throws Exception [[@doctodo exception_description:Exception]]
@return unknown | public function getSystemId()
{
if (!is_null($this->_systemId)) {
return $this->_systemId;
}
preg_match('/' . ucfirst($this->moduleType) . '([A-Za-z]+)\\\Module/', get_class($this), $matches);
if (!isset($matches[1])) {
throw new Exception(get_class($this) . "... | csn |
def _generator_other(self):
"""Generator for `self.filetype` other than file"""
for path in self.paths:
| for root, dnames, fnames in self._walker(path):
yield from self._generator_rebase(dnames, root)
yield from self._generator_rebase(fnames, root) | csn_ccr |
public function getParameter($name)
{
foreach ($this->xmlRoot->parameter as $parameter) {
if ($method['name'] == | $name) {
$moufRefParameter = new MoufXmlReflectionParameter($this, $parameter);
return $moufRefParameter;
}
}
return null;
} | csn_ccr |
public static List<Audit> findByMessage(EntityManager em, String message) {
requireArgument(em != null, "Entity manager cannot be null.");
requireArgument(message != null && !message.isEmpty(), "Message cannot be null or empty.");
TypedQuery<Audit> query = em.createNamedQuery("Audit.findByMessa... | query.setParameter("message", "%" + message + "%");
return query.getResultList();
} catch (Exception ex) {
return new ArrayList<Audit>(0);
}
} | csn_ccr |
Returns an array of prepared languages
@param bool $count
@return array|int | protected function getListLanguage($count = false)
{
$list = $this->language->getList();
$allowed = $this->getAllowedFiltersLanguage();
$this->filterList($list, $allowed, $this->query_filter);
$this->sortList($list, $allowed, $this->query_filter, array('code' => 'asc'));
if... | csn |
public boolean isBye() {
if (message == null) {
return false;
}
| return (((Request) message).getMethod().equals(Request.BYE));
} | csn_ccr |
Enable indexing with almost Numpy-like capabilities.
Implements the following features:
- Usage of general slices and sequences of slices
- Conversion of `Ellipsis` into an adequate number of ``slice(None)``
objects
- Fewer indices than axes by filling up with an `Ellipsis`
- Error checking ... | def normalized_index_expression(indices, shape, int_to_slice=False):
"""Enable indexing with almost Numpy-like capabilities.
Implements the following features:
- Usage of general slices and sequences of slices
- Conversion of `Ellipsis` into an adequate number of ``slice(None)``
objects
- Fe... | csn |
Returns the hostname of the provided url
@param string $url
@return string the hostname parsed from the provided url
@throws \InvalidArgumentException if the url is malformed | public static function getHostname(string $url)
{
$url = UrlHelper::validateUrl($url);
$hostname = parse_url($url, PHP_URL_HOST);
if ($hostname === false) {
throw new InvalidArgumentException("Could not determine hostname, url seems to be invalid: $url");
}
retu... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.