query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
def _single_replace(self, to_replace, method, inplace, limit):
"""
Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method
"""
if self.ndim != 1:
raise TypeError('cannot replace {0} with method {1} on a {2}'
... | values = fill_f(result.values, limit=limit, mask=mask)
if values.dtype == orig_dtype and inplace:
return
result = pd.Series(values, index=self.index,
dtype=self.dtype).__finalize__(self)
if inplace:
self._update_inplace(result._data)
return
return r... | csn_ccr |
func (t *Type) GetProperty(name string) Property {
propInterface, ok := t.Properties[name]
| if !ok {
panic(fmt.Errorf("property %v not exist", name))
}
prop := toProperty(name, propInterface)
prop._type = t
return prop
} | csn_ccr |
Returns the status of a particular capture and the total amount refunded
on the capture
@see https://pay.amazon.com/documentation/apireference/201751630#201752060
@param amazon_capture_id [String]
@optional merchant_id [String]
@optional mws_auth_token [String] | def get_capture_details(
amazon_capture_id,
merchant_id: @merchant_id,
mws_auth_token: nil
)
parameters = {
'Action' => 'GetCaptureDetails',
'SellerId' => merchant_id,
'AmazonCaptureId' => amazon_capture_id
}
optional = {
'MWSAuthToken' => mws_au... | csn |
public function updateOperation($id, $counterId, Models\Operation $operation)
{
$resource = 'counter/' . $counterId . '/operation/' . $id;
$response = $this->sendPutRequest($resource, ["operation" => $operation->toArray()]);
| $operationsResponse = new Models\UpdateOperationResponse($response);
return $operationsResponse->getOperation();
} | csn_ccr |
// GetUpgradeSeriesMessages returns all new messages associated with upgrade
// series events. Messages that have already been retrieved once are not
// returned by this method. | func (mm *MachineManagerAPI) GetUpgradeSeriesMessages(args params.UpgradeSeriesNotificationParams) (params.StringsResults, error) {
if err := mm.checkCanRead(); err != nil {
return params.StringsResults{}, err
}
results := params.StringsResults{
Results: make([]params.StringsResult, len(args.Params)),
}
for i,... | csn |
// TxGet allows you to pass in your own bolt transaction to retrieve a value from the bolthold and puts it into result | func (s *Store) TxGet(tx *bolt.Tx, key, result interface{}) error {
storer := newStorer(result)
gk, err := encode(key)
if err != nil {
return err
}
bkt := tx.Bucket([]byte(storer.Type()))
if bkt == nil {
return ErrNotFound
}
value := bkt.Get(gk)
if value == nil {
return ErrNotFound
}
return decode... | csn |
// NewCmdCreatePassthroughRoute is a macro command to create a passthrough route. | func NewCmdCreatePassthroughRoute(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := &CreatePassthroughRouteOptions{
CreateRouteSubcommandOptions: NewCreateRouteSubcommandOptions(streams),
}
cmd := &cobra.Command{
Use: "passthrough [NAME] --service=SERVICE",
Sho... | csn |
public static int sizeOf(int type)
{
switch ( type )
{
case MatDataTypes.miINT8:
return miSIZE_INT8;
case MatDataTypes.miUINT8:
return miSIZE_UINT8;
case MatDataTypes.miINT16:
return miSIZE_INT16;
case Ma... | return miSIZE_UINT32;
case MatDataTypes.miINT64:
return miSIZE_INT64;
case MatDataTypes.miUINT64:
return miSIZE_UINT64;
case MatDataTypes.miDOUBLE:
return miSIZE_DOUBLE;
default:
return 1;
}
... | csn_ccr |
func AlternativesAsExactEqual(o1, o2 *AlternativesAsExactOption) bool { |
if o1 != nil {
return o1.Equal(o2)
}
if o2 != nil {
return o2.Equal(o1)
}
return true
} | csn_ccr |
function setCheckboxState(page, ph, selectorAndState, callback) {
page.evaluate(function (selectorAndState) {
try {
var selector = selectorAndState[0];
var state = selectorAndState[1];
var element = document.querySelector(selector);
element.checked = state;
... | null;
} catch (error) {
return error;
}
}, function (error) {
// do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph);
if (error) {
callback(error, page, ph);
return;
}
... | csn_ccr |
Set the element ID from the path
@param relativePath path
@param id element ID
@return element ID, may be {@code null} | public static URI setElementID(final URI relativePath, final String id) {
String topic = getTopicID(relativePath);
if (topic != null) {
return setFragment(relativePath, topic + (id != null ? SLASH + id : ""));
} else if (id == null) {
return stripFragment(relativePath);
... | csn |
Doctor Kunj installed new software on cyborg Shresth.
This software introduced Shresth to range minimum queries.
Cyborg Shresth thought of T$T$ different problems in each of which you will be given
an array A$A$ of length N$N$ and an array B$B$ of length M$M$. In each of these problems, you have to calculate:
∑mi=1∑mj=... | def f(a,n):
l,r,s1,s2 = [0]*n, [0]*n, [], []
for i in range(n):
count = 1
while(len(s1)>0 and a[i]<s1[-1][0]):
count += s1[-1][1]
s1.pop()
s1.append((a[i],count))
l[i] = count
for i in range(n-1,-1,-1):
count = 1
while(len(s2)>0 and a[i]<=s2[-1][0]):
count... | apps |
handles a file with proper extension such as gif, js, etc.
@param FileInfo $file
@return FileInfo | public function handle($file)
{
if (!$mime = $this->getMimeForEmit($file->getExtension())) {
return $file;
}
if (!$file_loc = $file->getLocation()) {
return $file;
}
$file->setMime($mime);
$file->setFound();
$fp = fopen($file_loc, 'r'... | csn |
Factory method, registers new node. | def register_new_node(suffix_node_id=None):
"""Factory method, registers new node.
"""
node_id = uuid4()
event = Node.Created(originator_id=node_id, suffix_node_id=suffix_node_id)
entity = Node.mutate(event=event)
publish(event)
return entity | csn |
Check to see if the current version of the plugin seems to be a checkout of an external repository.
@param string $component frankenstyle component name
@return false|string | public function plugin_external_source($component) {
$plugininfo = $this->get_plugin_info($component);
if (is_null($plugininfo)) {
return false;
}
$pluginroot = $plugininfo->rootdir;
if (is_dir($pluginroot.'/.git')) {
return 'git';
}
i... | csn |
public static function beansOfType(ApplicationInterface $applicationContext, $class)
{
/**
* @var $objectManager ObjectManagerInterface
*/
$objectManager = $applicationContext->search("ObjectManagerInterface");
$initialContext = new InitialContext();
$initialContext... | if ($descriptor instanceof ComponentDescriptorInterface) {
if (is_subclass_of($descriptor->getClassName(), $class)) {
$beans[$descriptor->getName()] = $initialContext->lookup($descriptor->getName());
}
}
}
return $beans;
} | csn_ccr |
python resize image maintaining aspect ratio | def scale_image(image, new_width):
"""Resizes an image preserving the aspect ratio.
"""
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)
# This scales it wider than tall, since characters are biased
... | cosqa |
Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object. | def build_command_tree(pattern, cmd_params):
"""
Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object.
"""
from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument
if type(pattern) in [Either, Optional, OneOrMore]:
for chil... | csn |
public function insert(string $table) : QueryBuilder
{
$this->_query[] = "INSERT INTO";
| $this->_query[] = "`". $this->sanitize($table) ."`";
return $this;
} | csn_ccr |
Flush the states | public void sendOutState(State<Serializable, Serializable> state,
String checkpointId,
boolean spillState,
String location) {
outputter.sendOutState(state, checkpointId, spillState, location);
} | csn |
test if a particular category has a certain subject | def has_any? subject, &block
found = subjects.include? subject
yield if found && block
found
end | csn |
from mxnet import np, npx
from mxnet.gluon import nn
npx.set_np()
class CenteredLayer(nn.Block):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def forward(self, X):
return X - X.mean()
Y = net(np.random.uniform(size=(4, 8)))
Y.mean()
class MyDense(nn.Block):
def __init__(self, uni... | import torch
import torch.nn.functional as F
from torch import nn
class CenteredLayer(nn.Module):
def __init__(self):
super().__init__()
def forward(self, X):
return X - X.mean()
Y = net(torch.rand(4, 8))
Y.mean()
class MyLinear(nn.Module):
def __init__(self, in_units, units):
super(... | codetrans_dl |
Signal all the matching pipes. | public void match(ByteBuffer data, int size, IMtrieHandler func, XPub pub)
{
assert (data != null);
assert (func != null);
assert (pub != null);
Mtrie current = this;
int idx = 0;
while (true) {
// Signal the pipes attached to this node.
if (... | csn |
func MergeConfig(startingConfig, addition clientcmdapi.Config) (*clientcmdapi.Config, error) {
ret := startingConfig
for requestedKey, value := range addition.Clusters {
ret.Clusters[requestedKey] = value
}
for requestedKey, value := range addition.AuthInfos {
ret.AuthInfos[requestedKey] = value
}
requeste... | next, our job is done
requestedContextNamesToActualContextNames[requestedKey] = existingName
continue
}
requestedContextNamesToActualContextNames[requestedKey] = requestedKey
ret.Contexts[requestedKey] = actualContext
}
if len(addition.CurrentContext) > 0 {
if newCurrentContext, exists := requestedCo... | csn_ccr |
def walk_recursive(f, data):
"""
Recursively apply a function to all dicts in a nested dictionary
:param f: Function to apply
:param data: Dictionary (possibly nested) to recursively apply
function to
:return:
"""
results = {}
if isinstance(data, list):
| return [walk_recursive(f, d) for d in data]
elif isinstance(data, dict):
results = funcy.walk_keys(f, data)
for k, v in data.iteritems():
if isinstance(v, dict):
results[f(k)] = walk_recursive(f, v)
elif isinstance(v, list):
results[f(k)... | csn_ccr |
Get escape flag
@return true | public function getEscape()
{
if (null === $this->_escape) {
if (null !== ($escape = $this->getOption('escape'))) {
$this->setEscape($escape);
$this->removeOption('escape');
} else {
$this->setEscape(true);
}
}
... | csn |
public boolean handleRedirect(int statusCode, HttpHeaders responseHeaders) {
String redirectLocation = responseHeaders.getLocation();
if (getFollowRedirects()
&& HttpStatusCodes.isRedirect(statusCode)
&& redirectLocation != null) {
// resolve the redirect location relative to the current l... | headers.setAuthorization((String) null);
headers.setIfMatch((String) null);
headers.setIfNoneMatch((String) null);
headers.setIfModifiedSince((String) null);
headers.setIfUnmodifiedSince((String) null);
headers.setIfRange((String) null);
return true;
}
return false;
} | csn_ccr |
// outWorker runs in an own goroutine, encoding and sending messages that are
// sent to conn.out. | func (conn *Conn) outWorker() {
for msg := range conn.out {
err := conn.SendMessage(msg)
conn.callsLck.RLock()
if err != nil {
if c := conn.calls[msg.serial]; c != nil {
c.Err = err
c.Done <- c
}
conn.serialLck.Lock()
delete(conn.serialUsed, msg.serial)
conn.serialLck.Unlock()
} else if ... | csn |
Remove the child node at the specified index.
@param int $index
@throws \OutOfRangeException
@return self | public function removeChildAt($index)
{
$node = $this->getChildAt($index);
// re-wire new node and remove
$node->node_parent = null;
$node->node_childIndex = null;
array_splice($this->node_children, $index, 1);
// update following child indices
for ($i = $index; $i < count($this->node_children); $i... | csn |
Compute the standard deviation along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number ... | def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the standard deviation along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divis... | csn |
public JCRPath getLocation() throws RepositoryException
{
if (this.location == null)
{
this.location | = session.getLocationFactory().createJCRPath(qpath);
}
return this.location;
} | csn_ccr |
Load a source from the javac state file. | public Source loadSource(Package lastPackage, String l, boolean is_generated) {
Source s = Source.load(lastPackage, l, is_generated);
lastPackage.addSource(s);
sources.put(s.name(), s);
return s;
} | csn |
URL-encode a string ID in url path formatting. | public static String urlEncodeId(String id) throws InvalidRequestException {
try {
return urlEncode(id);
} catch (UnsupportedEncodingException e) {
throw new InvalidRequestException(String.format(
"Unable to encode `%s` in the url to %s. "
+ "Please contact support@stripe.com for... | csn |
### Description
As hex values can include letters `A` through to `F`, certain English words can be spelled out, such as `CAFE`, `BEEF`, or `FACADE`.
This vocabulary can be extended by using numbers to represent other letters, such as `5EAF00D`, or `DEC0DE5`.
Given a string, your task is to return the decimal sum of al... | def hex_word_sum(s):
return sum(int(w, 16) for w in s.translate(str.maketrans('OS', '05')).split() if set(w) <= set('0123456789ABCDEF')) | apps |
Validates the csrf token in the HTTP request.
This method should be called in the beginning of the request. By default,
POST, PUT and DELETE requests will be validated for a valid CSRF token.
If the request does not provide a valid CSRF token, this method will
kill the script and send a HTTP 400 (bad request) response... | public function validateRequest($throw = false)
{
// Ensure that the actual token is generated and stored
$this->getTrueToken();
if (!$this->isValidatedRequest()) {
return true;
}
if (!$this->validateRequestToken()) {
if ($throw) {
th... | csn |
def boxify(message, border_color=None):
"""Put a message inside a box.
Args:
message (unicode): message to decorate.
border_color (unicode): name of the color to outline the box with.
"""
lines = message.split("\n")
max_width = max(_visual_width(line) for line in lines)
padding... | padding_vertical
]
content_lines = [
"{border}{space}{content}{space}{border}\n".format(
border=colorize(chars["vertical"], color=border_color),
space=chars["empty"] * padding_horizontal,
content=_visual_center(line, max_width),
)
for line in lines
... | csn_ccr |
Validate the current token exists and is still valid | def _selftoken_expired():
'''
Validate the current token exists and is still valid
'''
try:
verify = __opts__['vault'].get('verify', None)
url = '{0}/v1/auth/token/lookup-self'.format(__opts__['vault']['url'])
if 'token' not in __opts__['vault']['auth']:
return True
... | csn |
protected function callRemoteService($serviceName)
{
if (!self::$servicesCopied) {
self::$servicesCopied = true;
$this->copyServicesToShop();
}
$oCurl = new Curl();
$this->setParameter('service', $serviceName);
|
$oCurl->setUrl($this->getTestConfig()->getShopUrl() . '/Services/service.php');
$oCurl->setParameters($this->getParameters());
$sResponse = $oCurl->execute();
if ($oCurl->getStatusCode() >= 300) {
$sResponse = $oCurl->execute();
}
return $this->unserialize... | csn_ccr |
func (os *OverlappingShards) ContainsShard(shardName string) bool {
for _, l := range os.Left {
if l.ShardName() == shardName {
return true
}
}
for _, r | := range os.Right {
if r.ShardName() == shardName {
return true
}
}
return false
} | csn_ccr |
Create a method (**JS**: function) `every` which returns every nth element of an array.
### Usage
With no arguments, `array.every` it returns every element of the array.
With one argument, `array.every(interval)` it returns every `interval`th element.
With two arguments, `array.every(interval, start_index)` it re... | def every(lst, n=1, start=0):
return lst[start::n] | apps |
Run registered callbacks. | def _run_callbacks(self):
"""Run registered callbacks."""
for i in range(len(self._callbacks)):
callback, args = self._callbacks.popleft()
try:
callback(*args)
except Exception:
self._log.exception('Ignoring exception in callback:') | csn |
Returns true if conversion between the sourceType and targetType can be bypassed.
More precisely this method will return true if objects of sourceType can be
converted to the targetType by returning the source object unchanged.
@param sourceType context about the source type to convert from (may be null if source is nu... | public boolean canBypassConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
Assert.notNull(targetType, "The targetType to convert to cannot be null");
if (sourceType == null) {
return true;
}
GenericConverter converter = getConverter(sourceType, targetType);
return (converter == NO_OP_CONVERTER... | csn |
String lastLink() {
if (totalResults == null || currentLimit == 0L) {
return null;
}
Long lastOffset;
if (totalResults % currentLimit == 0L) {
lastOffset = totalResults | - currentLimit;
} else {
// Truncation due to integral division gives floor-like behavior for free.
lastOffset = totalResults / currentLimit * currentLimit;
}
return urlWithUpdatedPagination(lastOffset, currentLimit);
} | csn_ccr |
public void namespaceAfterStartElement(
final String prefix,
final String uri)
throws SAXException
| {
startPrefixMapping(prefix,uri,false);
} | csn_ccr |
Creates a BinaryImage from the depth image. Points where the depth
is greater than threshold are converted to ones, and all other points
are zeros.
Parameters
----------
threshold : float
The depth threshold.
Returns
-------
:obj:`BinaryImage... | def to_binary(self, threshold=0.0):
"""Creates a BinaryImage from the depth image. Points where the depth
is greater than threshold are converted to ones, and all other points
are zeros.
Parameters
----------
threshold : float
The depth threshold.
Re... | csn |
protected function save($key, $value, $isNew = false, $brandId = false, $flag = null)
{
try {
DB::transaction(function () use ($key, $value, $isNew, $brandId, $flag) {
$name = str_replace('acl_antares/', '', $key);
if (str_contains($key, 'acl_antares')) {
... | + ['status' => ($flag === 'active')]);
if (!$model->save()) {
throw new ComponentNotSavedException('Unable to save primary module configuration');
}
}
});
} catch (Exception $e) {
Log::emergency($e);
... | csn_ccr |
Issue multiple POST requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
data - None, a dict or string, or a list of dicts and strings representing the data body.
to_json - A bool... | def multi_post(self, urls, query_params=None, data=None, to_json=True, send_as_file=False):
"""Issue multiple POST requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
data - None, a ... | csn |
public static boolean isValidAccessorName(String accessorName) {
if (accessorName.startsWith("get") || accessorName.startsWith("is") || accessorName.startsWith("set")) {
int prefixLength = | accessorName.startsWith("is") ? 2 : 3;
return accessorName.length() > prefixLength;
};
return false;
} | csn_ccr |
def AddPorts(self,ports):
"""Create one or more port access policies.
Include a list of dicts with protocol, port, and port_to (optional - for range) keys.
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
.AddPorts([{'protocol': 'TCP', 'port': '80' },
{'protocol': 'UDP', 'port': '100... | port in ports:
if 'port_to' in port: self.ports.append(Port(self,port['protocol'],port['port'],port['port_to']))
else: self.ports.append(Port(self,port['protocol'],port['port']))
return(self.Update()) | csn_ccr |
def make_folium_polyline(edge, edge_color, edge_width, edge_opacity, popup_attribute=None):
"""
Turn a row from the gdf_edges GeoDataFrame into a folium PolyLine with
attributes.
Parameters
----------
edge : GeoSeries
a row from the gdf_edges GeoDataFrame
edge_color : string
... | lon,lat
# so we have to flip them around
locations = list([(lat, lon) for lon, lat in edge['geometry'].coords])
# if popup_attribute is None, then create no pop-up
if popup_attribute is None:
popup = None
else:
# folium doesn't interpret html in the html argument (weird), so can't
... | csn_ccr |
function replaceOne(coll, filter, doc, options, callback) {
// Set single document update
options.multi = false;
// Execute update
updateDocuments(coll, filter, doc, options, (err, r) => {
if (callback == null) return;
if (err && callback) return callback(err);
if (r == null) return callback(null, ... | should be `r.result.upserted[0]._id`
: null;
r.upsertedCount =
Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
r.matchedCount =
Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
r.ops = [doc];
if (callback... | csn_ccr |
def _get_csv_cells_gen(self, line):
"""Generator of values in a csv line"""
digest_types = self.digest_types
for j, value in enumerate(line):
if self.first_line:
digest_key = None
digest = lambda x: x.decode(self.encoding)
else:
... | except IndexError:
digest_key = digest_types[0]
digest = Digest(acceptable_types=[digest_key],
encoding=self.encoding)
try:
digest_res = digest(value)
if digest_res == "\b":
di... | csn_ccr |
A list of all web properties on this account. You may
select a specific web property using its name, its id
or an index.
```python
account.webproperties[0]
account.webproperties['UA-9234823-5']
account.webproperties['debrouwere.org']
``` | def webproperties(self):
"""
A list of all web properties on this account. You may
select a specific web property using its name, its id
or an index.
```python
account.webproperties[0]
account.webproperties['UA-9234823-5']
account.webproperties['debrouwer... | csn |
Given a request to reorder, tell us to reorder | def OnReorder(self, event):
"""Given a request to reorder, tell us to reorder"""
column = self.columns[event.GetColumn()]
return self.ReorderByColumn( column ) | csn |
python print tuple elements in one line | def _tuple_repr(data):
"""Return a repr() for a list/tuple"""
if len(data) == 1:
return "(%s,)" % rpr(data[0])
else:
return "(%s)" % ", ".join([rpr(x) for x in data]) | cosqa |
func chunkedGrab(sources []profileSource, fetch plugin.Fetcher, obj plugin.ObjTool, ui plugin.UI, tr http.RoundTripper) (*profile.Profile, plugin.MappingSources, bool, int, error) {
const chunkSize = 64
var p *profile.Profile
var msrc plugin.MappingSources
var save bool
var count int
for start := 0; start < len... |
case chunkP == nil:
continue
case p == nil:
p, msrc, save, count = chunkP, chunkMsrc, chunkSave, chunkCount
default:
p, msrc, chunkErr = combineProfiles([]*profile.Profile{p, chunkP}, []plugin.MappingSources{msrc, chunkMsrc})
if chunkErr != nil {
return nil, nil, false, 0, chunkErr
}
if chu... | csn_ccr |
Adds the specified elements before current set nodes.
@method before
@param {String/Element/Array/tinymce.dom.DomQuery} content Content to add before to each element in set.
@return {tinymce.dom.DomQuery} Current set. | function () {
var self = this;
if (self[0] && self[0].parentNode) {
return domManipulate(self, arguments, function (node) {
this.parentNode.insertBefore(node, this);
});
}
return self;
} | csn |
Get all metadata for a post.
@param \WP_Post $post The post.
@return array | public static function get_all_post_meta( $post ) {
$tags = [
[ 'name' => 'description', 'content' => self::get_post_meta_description( $post ) ],
[ 'property' => 'og:locale', 'content' => get_locale() ],
[ 'property' => 'og:type', 'content' => 'article' ],
[ 'property' => 'og:title', 'content' => s... | csn |
Applying beforeScraping middlewares | function beforeScraping(job, callback) {
return async.applyEachSeries(
this.middlewares.beforeScraping,
job.req,
callback
);
} | csn |
def _run_pipeline(self, multiprocessing):
"""Use pipeline multiprocessing to extract PCAP files."""
if not self._flag_m:
raise UnsupportedCall(f"Extractor(engine={self._exeng})' has no attribute '_run_pipline'")
if not self._flag_q:
self._flag_q = True
warnin... | # reassembly buffers
# preparation
self.record_header()
self._mpfdp[0].put(self._gbhdr.length)
# extraction
while True:
# check EOF
if self._mpkit.eof:
self._update_eof()
break
# check counter
if ... | csn_ccr |
Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries.
Example 1:
Input: arr = [1,3,4,8], queries = [[0,1]... | from itertools import accumulate
class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
xors = [0]
for a in arr:
xors.append(a^xors[-1])
return [xors[i]^xors[j+1] for i,j in queries]
| apps |
This is function for de-standarization of input series.
**Args:**
* `xs` : standardized input (1 dimensional array)
* `offset` : offset to add (float).
* `scale` : scale (float).
**Returns:**
* `x` : original (destandardised) series | def standardize_back(xs, offset, scale):
"""
This is function for de-standarization of input series.
**Args:**
* `xs` : standardized input (1 dimensional array)
* `offset` : offset to add (float).
* `scale` : scale (float).
**Returns:**
* `x` : original (destandardised) ser... | csn |
Respond to the FLUSHALL command. | function execute(req, res) {
// TODO: ensure a conflict is triggered on all watched keys
this.store.flushall();
res.send(null, Constants.OK);
} | csn |
Create an HTTP request of the specified method to a url.
@param string $url
@param string $method
@param array $parameter
@param array $option
@return object | public static function request($url, $method = 'GET', array $parameter = [], array $option = [])
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_FOLLOWLOCAT... | csn |
def load(self):
"""Fetches the MAL media page and sets the current media's attributes.
:rtype: :class:`.Media`
:return: current media object.
"""
| media_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id)).text
self.set(self.parse(utilities.get_clean_dom(media_page)))
return self | csn_ccr |
json to a table view in python | def index():
""" Display productpage with normal user and test user buttons"""
global productpage
table = json2html.convert(json = json.dumps(productpage),
table_attributes="class=\"table table-condensed table-bordered table-hover\"")
return render_template('index.html', ... | cosqa |
Fills given field with given value
:param field_name: name of field to fill
:param field_value: value with which to fill field | def fill_form_field(self, field_name, field_value):
"""Fills given field with given value
:param field_name: name of field to fill
:param field_value: value with which to fill field
"""
self.browser.execute_script(
"document.getElementsByName(\"" + str(
... | csn |
public function getServiceIdsForTag($tag)
{
$serviceIds = [];
foreach ($this->tags as $serviceId => $tags) | {
if (isset($tags[$tag])) {
$serviceIds[$serviceId] = $tags[$tag];
}
}
return $serviceIds;
} | csn_ccr |
// hashSharedSecret Sha-256 hashes the shared secret and returns the first
// HashPrefixSize bytes of the hash. | func hashSharedSecret(sharedSecret *Hash256) *HashPrefix {
// Sha256 hash of sharedSecret
h := sha256.New()
h.Write(sharedSecret[:])
var sharedHash HashPrefix
// Copy bytes to sharedHash
copy(sharedHash[:], h.Sum(nil))
return &sharedHash
} | csn |
A writable stream that acts as a statsd sink for the zither instrument input sources.
@param {Obj} options Statsd client options. See https://github.com/sivy/node-statsd for options.
Additionally you can include sampleRate to control how Statsd samples data.
sampleRate defaults to 1. | function(options) {
options = options || {};
this.host = options.host || 'localhost';
this.port = options.port || 8125;
if (!statsdClients[this.host + ':' + this.port]) {
statsdClients[this.host + ':' + this.port] = new StatsD(options);
}
this.client = statsdClients[this.host + ':' + this.port];
thi... | csn |
def _initialize(self, chain, length):
"""Prepare for tallying. Create a new chain."""
# If this db was loaded from the disk, it may not have its
# tallied | step methods' getfuncs yet.
if self._getfunc is None:
self._getfunc = self.db.model._funs_to_tally[self.name] | csn_ccr |
def signals(self, signals=('QUIT', 'USR1', 'USR2')):
'''Register our signal handler'''
for sig in signals:
| signal.signal(getattr(signal, 'SIG' + sig), self.handler) | csn_ccr |
def compare(self, operand1, operand2):
"""Generates a compare instruction
operandX - index in symbol table
"""
typ = self.symtab.get_type(operand1)
self.free_if_register(operand1)
self.free_if_register(operand2)
|
self.newline_text("CMP{0}\t{1},{2}".format(self.OPSIGNS[typ], self.symbol(operand1), self.symbol(operand2)), True) | csn_ccr |
public function xcontext($message, $closure, $timeout = null)
{
| return $this->_block->context($message, $closure, $timeout, 'exclude');
} | csn_ccr |
def draw_as_points(points, z, options = {})
color = options[:color] || DEFAULT_DRAW_COLOR
scale = options[:scale] || 1.0
shader = options[:shader]
mode = options[:mode] || :default
if shader
shader.enable z
$window.gl z do
shader.image = self
shader.col... | points.each do |x, y|
draw_rot_without_hash x, y, z, 0, 0.5, 0.5, scale, scale, color, mode
end
ensure
shader.disable z if shader
end
end | csn_ccr |
func (s *store) ControllerByAPIEndpoints(endpoints ...string) (*ControllerDetails, string, error) {
releaser, err := s.acquireLock()
if err != nil {
return nil, "", errors.Annotatef(err, "cannot acquire lock file to read controllers")
}
defer releaser.Release()
controllers, err := ReadControllersFile(JujuContro... |
matchEps := set.NewStrings(endpoints...)
for name, ctrl := range controllers.Controllers {
if matchEps.Intersection(set.NewStrings(ctrl.APIEndpoints...)).IsEmpty() {
continue
}
return &ctrl, name, nil
}
return nil, "", errors.NotFoundf("controller with API endpoints %v", endpoints)
} | csn_ccr |
Executes an SQL statement, returning a PDOStatement object or the number of affected rows
@param string $sql The SQL query
@param array $params The SQL parameters
@param array $types The parameter types to bind
@param bool $returnRows Whether returns a PDOStatement object or the number of affected rows
@throws \PDOExc... | public function query($sql, $params = array(), $types = array(), $returnRows = false)
{
// A select query, using slave db if configured
if (!$returnRows && $this->slaveDb) {
/** @var $slaveDb \Wei\Db */
$slaveDb = $this->wei->get($this->slaveDb);
return $slaveDb->... | csn |
def image_to_texture(image):
"""Converts ``vtkImageData`` to a ``vtkTexture``"""
vtex = vtk.vtkTexture()
| vtex.SetInputDataObject(image)
vtex.Update()
return vtex | csn_ccr |
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem. | def convert_to_binary(variables, domains, constraints):
"""
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem.
"""
def wdiff(vars_):
def diff(variables, values):
hidden, other = variables
if hidd... | csn |
Return the SchemaElement for the specified class name, asserting that it exists. | def get_element_by_class_name_or_raise(self, class_name):
"""Return the SchemaElement for the specified class name, asserting that it exists."""
if class_name not in self._elements:
raise InvalidClassError(u'Class does not exist: {}'.format(class_name))
return self._elements[class_n... | csn |
func (mr *MockPinnerMockRecorder) PinnedLeadership() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, | "PinnedLeadership", reflect.TypeOf((*MockPinner)(nil).PinnedLeadership))
} | csn_ccr |
Format a DateTime object as something MySQL will actually accept. | def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str:
"""Format a DateTime object as something MySQL will actually accept."""
# dt = d.strftime("%Y-%m-%d %H:%M:%S")
# ... can fail with e.g.
# ValueError: year=1850 is before 1900; the datetime strftime() methods
# require year... | csn |
public Object getRealValue()
{
if(valueRealSubject != null)
{
return valueRealSubject;
}
else
{
TransactionExt tx = getTransaction();
if((tx != null) && tx.isOpen())
{
prepareValueRealSubject(tx.getB... | finally
{
capsule.destroy();
}
}
else
{
getLog().warn("No tx, no PBKey - can't materialise value with Identity " + getKeyOid());
}
}
}... | csn_ccr |
// FilterMetricName returns true for a metric which matches allow, or if no allow rules are present,
// if it didn't match deny. Returns false otherwise. | func (f *FilteredForwarder) FilterMetricName(metricName string) bool {
denied := false
for _, a := range f.deny {
if a.Match([]byte(metricName)) {
denied = true
break
}
}
found := false
for _, a := range f.allow {
if a.Match([]byte(metricName)) {
denied = false
found = true
break
}
}
retur... | csn |
Drop self.df rows that have only null values,
ignoring certain columns.
Parameters
----------
ignore_cols : list-like
list of column names to ignore for
Returns
---------
self.df : pandas DataFrame | def drop_stub_rows(self, ignore_cols=('specimen',
'sample',
'software_packages',
'num')):
"""
Drop self.df rows that have only null values,
ignoring certain columns.
... | csn |
// SetupLogging configures logging based on choria config directives
// currently only file and console behaviours are supported | func (fw *Framework) SetupLogging(debug bool) (err error) {
fw.log = log.New()
fw.log.Out = os.Stdout
if fw.Config.LogFile != "" {
fw.log.Formatter = &log.JSONFormatter{}
file, err := os.OpenFile(fw.Config.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return fmt.Errorf("Could not se... | csn |
def get_batch_unlock(
end_state: NettingChannelEndState,
) -> Optional[MerkleTreeLeaves]:
""" Unlock proof for an entire merkle tree of pending locks
The unlock proof contains all the merkle tree data, tightly packed, needed by the token
network contract to verify the secret expiry and calculate th... | proof.lock.lockhash: proof.lock
for secrethash, proof in end_state.secrethashes_to_onchain_unlockedlocks.items()
})
ordered_locks = [
lockhashes_to_locks[LockHash(lockhash)]
for lockhash in end_state.merkletree.layers[LEAVES]
]
# Not sure why the cast is needed here. The erro... | csn_ccr |
func WithMaskedPaths(paths []string) SpecOpts {
return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {
| setLinux(s)
s.Linux.MaskedPaths = paths
return nil
}
} | csn_ccr |
func defaultVersionFor(config *Config) *unversioned.GroupVersion {
if config.GroupVersion == nil {
// Clients default to the preferred code API version
// TODO: implement version negotiation (highest version supported by server)
// TODO this drops out when groupmeta is | refactored
copyGroupVersion := latest.GroupOrDie("").GroupVersion
return ©GroupVersion
}
return config.GroupVersion
} | csn_ccr |
Topologically sorts the given module name into the output array.
The resulting array is sorted such that all predecessors of the module
come before the module (and their predecessors before them, and so on).
@param string $currentName The current module name to sort.
@param array $namesToSort The module names yet to... | private function sortModulesDFS($currentName, array &$namesToSort, array &$output)
{
unset($namesToSort[$currentName]);
// Before adding the module itself to the path, add all predecessors.
// Do so recursively, then we make sure that each module is visited
// in the path before any... | csn |
Log start, end, and duration. | def timing(name=''):
"""Log start, end, and duration."""
start = datetime.datetime.now()
timestamp = start.strftime('%H:%M')
tf.logging.info('Starting job [%s] at %s', name, timestamp)
yield
end = datetime.datetime.now()
timestamp = end.strftime('%H:%M')
tf.logging.info('Finished job [%s] at %s', name, ... | csn |
python code to get refresh token on sandbox using oauth | def get_oauth_token():
"""Retrieve a simple OAuth Token for use with the local http client."""
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"])
r = s.get(url=url)
return r.json()["t"] | cosqa |
// UnmarshalJSON implements the JSON Unmarshaller interface. Expects golang duration strings
// such as "1ms", "5s", etc. | func (d *Duration) UnmarshalJSON(b []byte) error {
dur, err := readDuration(string(b))
*d = Duration(dur)
return err
} | csn |
Notify an event to the event dispatcher.
@param string $command The command name
@param array $arguments Args of the command
@param mixed $return Return value of the command
@param int $time Exec time | protected function notifyEvent($command, $arguments, $return, $time = 0)
{
if ($this->eventDispatcher) {
$event = new $this->eventClass();
$event->setCommand($command)
->setArguments($arguments)
->setReturn($return)
->setExecution... | csn |
def post2data(func):
"""Decorator to restore original form values along with their types.
The sole purpose of this decorator is to restore original form values
along with their types stored on client-side under key $$originalJSON.
This in turn prevents the loss of field types when they are passed with
... | """
def wrapper(self, request):
request.DATA = request.POST
if '$$originalJSON' in request.POST:
request.DATA = jsonutils.loads(request.POST['$$originalJSON'])
return func(self, request)
return wrapper | csn_ccr |
def lock(self):
"""Acquire lock for dvc repo."""
try:
self._do_lock()
return
| except LockError:
time.sleep(self.TIMEOUT)
self._do_lock() | csn_ccr |
Returns a checksum based on the IDL that ignores comments and
ordering, but detects changes to types, parameter order,
and enum values. | def get_checksum(self):
"""
Returns a checksum based on the IDL that ignores comments and
ordering, but detects changes to types, parameter order,
and enum values.
"""
arr = [ ]
for elem in self.parsed:
s = elem_checksum(elem)
if s:
... | csn |
configured maximum number of retries. | private void commitMutations(DBTransaction dbTran, long timestamp) {
Map<ByteBuffer, Map<String, List<Mutation>>> colMutMap = CassandraTransaction.getUpdateMap(dbTran, timestamp);
if (colMutMap.size() == 0) {
return;
}
m_logger.debug("Committing {} mutations", CassandraT... | csn |
// NewDirReader creates a new directory reader and prepares to
// fetch the static-set entries | func NewDirReader(ctx context.Context, fetcher blob.Fetcher, dirBlobRef blob.Ref) (*DirReader, error) {
ss := new(superset)
err := ss.setFromBlobRef(ctx, fetcher, dirBlobRef)
if err != nil {
return nil, err
}
if ss.Type != "directory" {
return nil, fmt.Errorf("schema/dirreader: expected \"directory\" schema bl... | csn |
Return HTML element of button
@param string $icon class of icon
@param string $btn class of button
@param array|string $options HTML options for button element
@return string HTML element of button.
@link http://fontawesome.io,
http://getbootstrap.com/css/#buttons | public function button($icon = null, $btn = null, $options = []) {
$result = '';
if (empty($icon)) {
return $result;
}
$title = '';
if ($icon === strip_tags($icon)) {
if ($this->_getClassForElement($icon)) {
$icon .= ' fa-fw';
}
$title = $this->iconTag($icon);
}
if (empty($title)) {
$t... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.