query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Serializes a JSON value to a string.
@param value the value to serialize
@return the serialized value
@throws JSONException | public static String serialize(Value value) throws JSONException {
StringWriter writer = new StringWriter();
Serializer.serialize(value, writer);
return writer.toString();
} | csn |
how to run python unittest cmd | def test(): # pragma: no cover
"""Execute the unit tests on an installed copy of unyt.
Note that this function requires pytest to run. If pytest is not
installed this function will raise ImportError.
"""
import pytest
import os
pytest.main([os.path.dirname(os.path.abspath(__file__))]) | cosqa |
protected InputStream getResourceInputStream(final Resource resource, final String entityId) throws IOException {
LOGGER.debug("Locating metadata resource from input stream.");
if (!resource.exists() || !resource.isReadable()) {
| throw new FileNotFoundException("Resource does not exist or is unreadable");
}
return resource.getInputStream();
} | csn_ccr |
function () {
if (typeof angular == "object" && typeof angular.element == "function") {
this._ngName = this._dataElement().attr("ng-model");
if (typeof this._ngName == "string") {
this._isAngular = true; var that | = this;
this._scope().$watch(this._ngName, function (newValue, oldValue) { that.option("value", newValue); });
}
}
} | csn_ccr |
public function checkNotification($notify) {
if (!is_array($notify)) {
return FALSE;
}
$notifyParams = array();
foreach ($this->notifyFields as $k => $mandatory) {
if (isset($notify[$k])) {
$notifyParams[$k] = $notify[$k];
}
elseif (!isset($notify[$k]) | && $mandatory) {
throw new \Exception('expected notification field ' . $k . ' is missing');
}
}
return $notifyParams;
} | csn_ccr |
Fetch a value from the table. Return |None| if no value matches
the conditions, or the table not found in the database.
:param str select: Attribute for SELECT query
:param str table_name: Table name of executing the query.
:param where: |arg_select_where|
:type where: |arg_wher... | def fetch_value(self, select, table_name, where=None, extra=None):
"""
Fetch a value from the table. Return |None| if no value matches
the conditions, or the table not found in the database.
:param str select: Attribute for SELECT query
:param str table_name: Table name of execu... | csn |
def setup_tmpltbank_workflow(workflow, science_segs, datafind_outs,
output_dir=None, psd_files=None, tags=None,
return_format=None):
'''
Setup template bank section of CBC workflow. This function is responsible
for deciding which of the various templ... | tmplt_banks = setup_tmpltbank_without_frames(workflow, output_dir,
tags=tags, independent_ifos=True,
psd_files=psd_files)
elif tmpltbankMethod == "WORKFLOW_NO_IFO_VARIATION_NODATA":
logging.info("Adding template bank jobs... | csn_ccr |
Returns the division of two gaussian distributions.
Parameters
----------
other: GaussianDistribution
The GaussianDistribution to be divided.
inplace: boolean
If True, modifies the distribution itself, otherwise returns a new
GaussianDistribution obj... | def divide(self, other, inplace=True):
"""
Returns the division of two gaussian distributions.
Parameters
----------
other: GaussianDistribution
The GaussianDistribution to be divided.
inplace: boolean
If True, modifies the distribution itself, o... | csn |
public function remove($name)
{
$context = $this->_context;
if (!$context->started) {
| $this->_start();
}
$context->is_dirty = true;
unset($context->_SESSION[$name]);
} | csn_ccr |
func (q *sessionQueue) sessionManager() {
defer close(q.shutdown)
for {
q.queueCond.L.Lock()
for q.commitQueue.Len() == 0 &&
q.pendingQueue.Len() == 0 {
q.queueCond.Wait()
select {
case <-q.quit:
if q.commitQueue.Len() == 0 &&
q.pendingQueue.Len() == 0 {
q.queueCond.L.Unlock()
re... | requested. If the
// either of the queues still has state updates to send to the
// tower, we may never exit in the above case if we are unable
// to reach the tower for some reason.
select {
case <-q.forceQuit:
return
default:
}
// Initiate a new connection to the watchtower and attempt to
// d... | csn_ccr |
implementing point styles. | private void drawPoints(Canvas canvas, Line line, int lineIndex, int mode) {
pointPaint.setColor(line.getPointColor());
int valueIndex = 0;
for (PointValue pointValue : line.getValues()) {
int pointRadius = ChartUtils.dp2px(density, line.getPointRadius());
final float raw... | csn |
public static GsonBuilder registerAll(GsonBuilder builder)
{
if (builder == null) { throw new NullPointerException("builder cannot be null"); }
registerLocalDate(builder);
| registerLocalDateTime(builder);
registerLocalTime(builder);
registerOffsetDateTime(builder);
registerOffsetTime(builder);
registerZonedDateTime(builder);
registerInstant(builder);
return builder;
} | csn_ccr |
// updateNodeStatus is used to heartbeat and update the status of the node | func (c *Client) updateNodeStatus() error {
start := time.Now()
req := structs.NodeUpdateStatusRequest{
NodeID: c.NodeID(),
Status: structs.NodeStatusReady,
WriteRequest: structs.WriteRequest{Region: c.Region()},
}
var resp structs.NodeUpdateResponse
if err := c.RPC("Node.UpdateStatus", &req, &re... | csn |
func GetFirstLocalAddr() (string, error) {
// get the local addr list
addrList, err := GetNetlinkAddrList()
if err != nil {
return "", err
}
if len(addrList) > | 0 {
return addrList[0], nil
}
return "", errors.New("no address was found")
} | csn_ccr |
Returns all the commerce account user rels.
@return the commerce account user rels | @Override
public List<CommerceAccountUserRel> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | csn |
Notification from DML layer.
@internal to be used from DML layer only. | public static function database_transaction_commited() {
if (self::$dispatching or empty(self::$extbuffer)) {
return;
}
self::$dispatching = true;
self::process_buffers();
self::$dispatching = false;
} | csn |
public function downloadFromCloud()
{
if ($this->owner->CloudStatus === 'Live') {
$bucket = $this->owner->getCloudBucket();
if ($bucket) {
$contents = $bucket->getContents($this->owner);
$path = $this->owner->getFullPath();
Filesy... | // if there was an error and we overwrote the local file with empty or null, it could delete the remote
// file as well. Better to err on the side of not writing locally when we should than that.
if (!empty($contents)) {
file_put_contents($path, $contents);
... | csn_ccr |
Perform minimal validation on the settings form.
@param array $data
@param array $files | public function validation($data, $files) {
$errors = parent::validation($data, $files);
if (isset($data['clustered']) && ($data['clustered'] == 1)) {
// Set servers is required with in cluster mode.
if (!isset($data['setservers'])) {
$errors['setservers'] = get_... | csn |
Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed. | def account(self, account=None):
''' Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed.
'''
for num_of_retries in range(default.max_retry):
if account is None:
account = self.mai... | csn |
public void showText(PdfTextArray text) {
if (state.fontDetails == null)
throw new NullPointerException("Font and size must be set before writing any text");
content.append("[");
ArrayList arrayList = text.getArrayList();
boolean lastWasNumber = false;
for (int k = 0;... | }
else {
if (lastWasNumber)
content.append(' ');
else
lastWasNumber = true;
content.append(((Float)obj).floatValue());
}
}
content.append("]TJ").append_i(separator);
} | csn_ccr |
def components(arg):
"""Converts a dict of components to the format expected by the Google Maps
server.
For example:
c = {"country": "US", "postal_code": "94043"}
convert.components(c)
# 'country:US|postal_code:94043'
:param arg: The component filter.
:type arg: dict
:rtype: bases... | multiple values per type, here we
# expand them into individual key/value items, eg:
# {"country": ["US", "AU"], "foo": 1} -> "country:AU", "country:US", "foo:1"
def expand(arg):
for k, v in arg.items():
for item in as_list(v):
yield "%s:%s" % (k, item)
if isinstanc... | csn_ccr |
def with_git(repo,
target_dir=None,
limit=None,
refspec="HEAD",
clone=True,
rev_list_args=None,
version_filter=lambda version: True):
"""
Decorate a project class with git-based version information.
This adds two attributes to a ... | return []
git("clone", repo, repo_loc)
update_hash(repo_loc)
with local.cwd(repo_loc):
rev_list = git("rev-list", "--abbrev-commit", "--abbrev=10",
refspec, *rev_list_args).strip().split('\n')
latest = git(... | csn_ccr |
Returns whether the menu item is allowed for the user
@param Authenticatable $user In case no user is passed Auth::user() will be used
@return bool | public function isAllowed(Authenticatable $user = null): bool
{
$user = $user ?: Auth::user();
foreach ($this->authorizationStack as $auth) {
if (is_callable($auth)) {
if (!$auth($user)) {
return false;
}
} elseif ($user &&... | csn |
POST Headers on a specified object in the container.
:param uri: ``str``
:param headers: ``dict`` | def _header_poster(self, uri, headers):
"""POST Headers on a specified object in the container.
:param uri: ``str``
:param headers: ``dict``
"""
resp = self.http.post(url=uri, body=None, headers=headers)
self._resp_exception(resp=resp)
return resp | csn |
public function ConditionalQuery( $check, $then, $else )
{
if ($check())
return $then();
$tran = $this->Begin();
if ($check()) // Appeared while we getting lock
return $tran->Rollback();
$ret = $else();
$tran->Commit();
return $ret;
// Execution example:
$this->Conditi... | return db::Query("SELECT count(*) FROM table WHERE id=1")['count'];
},
function ()
{
return db::Query("UPDATE table SET acc=acc+1 WHERE id=1");
},
function ()
{
return db::Query("INSERT INTO table(id) VALUES (1)");
}
);
} | csn_ccr |
public MutableState setStart(MutableState start) {
checkArgument(start.getId() >= 0, "must set id before setting start");
throwIfSymbolTableMissingId(start.getId());
| correctStateWeight(start);
this.start = start;
return start;
} | csn_ccr |
The percentage of explained inertia per principal component. | def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_] | csn |
// ChatInboxSyncStarted implements the chat1.NotifyChatInterface for
// ChatRPC. | func (c *ChatRPC) ChatInboxSyncStarted(
_ context.Context, _ keybase1.UID) error {
return nil
} | csn |
@Override
public <S extends T> Optional<S> findOne(final Example<S> example) {
final ArangoCursor cursor = findAllInternal((Pageable) null, example, new HashMap());
return | cursor.hasNext() ? Optional.ofNullable((S) cursor.next()) : Optional.empty();
} | csn_ccr |
function connectionDelay() {
var delay = self.connectionWait;
if (delay === 0) {
if (self.connectedAt) {
var t = | 1000;
var connectedFor = new Date().getTime() - self.connectedAt;
if (connectedFor < t) {
delay = t - connectedFor;
}
}
}
return delay;
} | csn_ccr |
Python2.4 doesn't have a partition method so we provide
our own that mimics str.partition from later releases.
Split the string at the first occurrence of sep, and return a
3-tuple containing the part before the separator, the separator
itself, and the part after the separator. If the separator is not
... | def _partition(entity, sep):
"""Python2.4 doesn't have a partition method so we provide
our own that mimics str.partition from later releases.
Split the string at the first occurrence of sep, and return a
3-tuple containing the part before the separator, the separator
itself, and the part after the... | csn |
String array implode internal method
@param glue
@param pieces
@return String | public static String implode(String glue, Object[] pieces)
{
if ( pieces == null ) {
return null;
}
StringBuffer sb = new StringBuffer();
for ( Object o : pieces ) {
if ( sb.length() > 0 ) {
sb.append(glue);
}
... | csn |
func (c *ExpireCache) Peek(key interface{}) (value interface{}, ok bool) {
defer c.mutex.Unlock() |
c.mutex.Lock()
if record, hit := c.cache[key]; hit {
return record.Value, true
}
return nil, false
} | csn_ccr |
List all branches. And if exactly 1 found, offer to check it out. | def branches(config, searchstring=""):
"""List all branches. And if exactly 1 found, offer to check it out."""
repo = config.repo
branches_ = list(find(repo, searchstring))
if branches_:
merged = get_merged_branches(repo)
info_out("Found existing branches...")
print_list(branche... | csn |
Timestamp with milliseconds
@return float|int
@throws Exceptions\OutOfSyncException | public function getTimeSleepUntil()
{
if ($this->delay == 0) {
return 0;
}
$query = $this->pdo->prepare(<<<SQL
SELECT
delayUntil,
UNIX_TIMESTAMP()
FROM robotstxt__delay0
WHERE base = :base AND userAgent = :userAgent;
SQL
);
$query->bindValue('base', $this->bas... | csn |
identify if float is null in python | def is_finite(value: Any) -> bool:
"""Return true if a value is a finite number."""
return isinstance(value, int) or (isinstance(value, float) and isfinite(value)) | cosqa |
// FromHex will parse a hex string into this Topic instance | func (t *Topic) FromHex(hex string) error {
bytes, err := hexutil.Decode(hex)
if err != nil || len(bytes) != len(t) {
return NewErrorf(ErrInvalidValue, "Cannot decode topic")
}
copy(t[:], bytes)
return nil
} | csn |
Internal method that serializes object into a dictionary. | def _to_dict(self):
"""
Internal method that serializes object into a dictionary.
"""
data = {
'name': self.name,
'referenceId': self.reference_id,
'shortDescription': self.short_description,
'playlistType': self.type,
'id': sel... | csn |
Create a new group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Group Dampening created | def create_group_dampening(self, group_id, dampening):
"""
Create a new group dampening
:param group_id: Group Trigger id attached to dampening
:param dampening: Dampening definition to be created.
:type dampening: Dampening
:return: Group Dampening created
"""
... | csn |
python3 byte to string] | def ub_to_str(string):
"""
converts py2 unicode / py3 bytestring into str
Args:
string (unicode, byte_string): string to be converted
Returns:
(str)
"""
if not isinstance(string, str):
if six.PY2:
return str(string)
else:
return st... | cosqa |
func RouteOriginal(msg *Message, router Router) error {
return | Route(msg.CloneOriginal(), router)
} | csn_ccr |
400 error handler.
Templates: :template:`400.html`
Context: None | def bad_request(request, template_name='400.html'):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
response = render_in_page(request, template_name)
if response:
return response
try:
template = loader.get_template(template_name)
except Te... | csn |
Returns true if the page appears to be the index page of an svn repository | def is_svn_page(html):
# type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]]
"""
Returns true if the page appears to be the index page of an svn repository
"""
return (re.search(r'<title>[^<]*Revision \d+:', html) and
re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I... | csn |
def loadfile(path, mode=None, filetype=None, **kwargs):
"""Loads the given file using the appropriate InferenceFile class.
If ``filetype`` is not provided, this will try to retreive the ``filetype``
from the file's ``attrs``. If the file does not exist yet, an IOError will
be raised if ``filetype`` is ... | str, optional
Force the file to be loaded with the given class name. This must be
provided if creating a new file.
Returns
-------
filetype instance
An open file handler to the file. The class used for IO with the file
is determined by the ``filetype`` keyword (if provided)... | csn_ccr |
public function get($docId)
{
return $this->montage->request(
'get',
| $this->montage->url('document-detail', $this->schema->name, $docId)
);
} | csn_ccr |
def check_node_overlap!
node_to_positions = {}
each_node do |node|
node.proper_range.each do |position|
if node_to_positions[position]
already = node_to_positions[position]
puts "There is a proper_range overlap between #{node} and #{already}"
puts "Overl... | #{already.proper_range & node.proper_range}"
binding.pry
end
node_to_positions[position] = node
end
end
end | csn_ccr |
Initialize the factory
@param routes [Hanami::Router] a routes set
@return [Hanami::Routes] the factory
@since 0.1.0
@api private
Return a relative path for the given route name
@param name [Symbol] the route name
@param args [Array,nil] an optional set of arguments that is passed down
to the wrapped rout... | def path(name, *args)
Utils::Escape::SafeString.new(@routes.path(name, *args))
end | csn |
def me_url(provider, params=nil)
connection.build_url(options[:me_url].sub(/:provider/, | provider), params).
to_s
end | csn_ccr |
Did you know that the people of America eat around 100 acres of pizza per day ? Having read this fact on internet, two chefs from the Elephant city, Arjuna and Bhima are set to make pizza popular in India. They organized a social awareness camp, where N people ( other than these two ) sit around a large pizza. To make ... | a= [0, 0, 1, 1, 2, 0, 3, 1, 1, 0, 3, 3, 2, 2, 4, 0, 5, 2, 2, 3, 3, 0, 1, 1, 3, 0, 2, 1, 1, 0, 4, 5, 2, 7, 4, 0, 1, 1, 2, 0, 3, 1, 1, 0, 3, 3, 2, 2, 4, 4, 5, 5, 2, 3, 3, 0, 1, 1, 3, 0, 2, 1, 1, 0, 4, 5, 3, 7, 4, 8, 1, 1, 2, 0, 3, 1, 1, 0, 3, 3, 2, 2, 4, 4, 5, 5, 9, 3, 3, 0, 1, 1, 3, 0, 2, 1, 1, 0, 4, 5, 3, 7, 4, 8, 1, 1... | apps |
Creates the worker thread pool. | private static void createThreadPool() {
if (nprocs == -1) {
int n = -1;
try {
String env = System.getProperty("smile.threads");
if (env != null) {
n = Integer.parseInt(env);
}
} catch (Exception ex) {
... | csn |
func (b *BackupEngine) Close() { |
C.rocksdb_backup_engine_close(b.c)
b.c = nil
} | csn_ccr |
public static String convertTcpToHttpUrl(String connect) {
String protocol = connect.contains(":" + DOCKER_HTTPS_PORT) ? | "https:" : "http:";
return connect.replaceFirst("^tcp:", protocol);
} | csn_ccr |
Define hoverIntent function | function hoverIntent(hoverEvent) {
// Only continue if tooltip isn't disabled
if(this.disabled || this.destroyed) { return FALSE; }
// Cache the event data
this.cache.event = hoverEvent && $.event.fix(hoverEvent);
this.cache.target = hoverEvent && $(hoverEvent.target);
// Start the event sequence
clearT... | csn |
def read_csv(self, file_path, use_whole_file=False, names=None, skiprows=0,
*args, **kwargs):
"""Read a CSV file in and parse it into Pandas DataFrames. By default,
the first row from the first partition of that data is parsed and used
as the column names for the data from. If n... | else:
# could use .iterows instead?
return iter([pandas.read_csv(sio(in_str), *args, header=None,
names=mynames, **kwargs)])
# If we need to peak at the first partition and determine the column
# names
mynam... | csn_ccr |
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data | def mod_aggregate(low, chunks, running):
'''
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
'''
rules = []
agg_enabled = [
'append',
'insert',
]
if low.get('fun') not ... | csn |
def jitterplot(data, positions=None, ax=None, vert=True, scale=0.1,
**scatter_kwargs):
'''Plots jittered points as a distribution visualizer.
Scatter plot arguments default to: marker='.', c='k', alpha=0.75
Also known as a stripplot.
See also: boxplot, violinplot, beeswarm
'''
if ax is None:... | c='k', alpha=0.75)
kwargs.update(scatter_kwargs)
for pos, y in zip(positions, data):
if scale > 0:
x = np.random.normal(loc=pos, scale=scale, size=len(y))
else:
x = np.zeros_like(y) + pos
if not vert:
x, y = y, x
ax.scatter(x, y, **kwargs)
return plt.show | csn_ccr |
public static function encode_websocket_events($events)
{
$out = '';
foreach ($events as $event) {
if (!is_null($event->content)) {
$content_length = dechex(strlen($event->content));
$out .= "{$event->type} {$content_length}\r\n" .
| "{$event->content}\r\n";
} else {
$out .= "{$event->type}\r\n";
}
}
return $out;
} | csn_ccr |
public function down(array $migrationData, $fields = [])
{
$this->guardAction($migrationData['action']);
$opposites = [
'delete' => 'create',
| 'create' => 'delete',
'remove' => 'add',
'add' => 'remove'
];
$method = $opposites[$migrationData['action']] . 'Factory';
return $this->$method($migrationData, $fields);
} | csn_ccr |
Checks if a property can be accessed.
@param $property <String>
@access protected
@return <Boolean> | protected function isAccessible(String $property) : Bool
{
if (in_array($property, $this->accessibleProperties())) {
return true;
}
return false;
} | csn |
Registers the child traits with the generated File Descriptor.
@param TraitReflector[] $traits
@param FileDescriptor $fileDescriptor
@return void | protected function addTraits($traits, $fileDescriptor)
{
foreach ($traits as $trait) {
$traitDescriptor = $this->getBuilder()->buildDescriptor($trait);
if ($traitDescriptor) {
$traitDescriptor->setLocation($fileDescriptor, $trait->getLineNumber());
if ... | csn |
Visibly start the Frame engine | public function start() {
// Don't load db if we don't want it (redo in the future)
if($this->config->exists('database')) {
$this->db = new DB\Connection($this->config);
}
$this->router = new Router($this->klein, $this->config);
} | csn |
def skip_child(self, child, ancestry):
""" get whether or not to skip the specified child """
if child.any(): return True
| for x in ancestry:
if x.choice():
return True
return False | csn_ccr |
func (p *Plugin) listLoggersHandler(formatter *render.Render) http.HandlerFunc | {
return func(w http.ResponseWriter, req *http.Request) {
formatter.JSON(w, http.StatusOK, p.listLoggers())
}
} | csn_ccr |
def ok_check(function, *args, **kwargs):
'''Ensure that the response body is OK'''
req = function(*args, **kwargs)
| if req.content.lower() != 'ok':
raise ClientException(req.content)
return req.content | csn_ccr |
private static function getInfoByBranch($campaign, $branchId, $activities) {
$connection = \Drupal::service('database');
/** @var \Drupal\Core\Database\Query\Select $query */
$query = $connection->select('openy_campaign_member', 'm');
$query->join('openy_campaign_member_campaign', 'mc', 'm.id = mc.mem... | // Get main activity for each MemberCampaign and collect result array.
$resultInfo = [];
foreach ($memberCampaignsInfo as &$mcData) {
// Get only members who tracked activities on site.
if (!empty($mcData['activity_visits'])) {
$mcData['main_activity'] = array_search(max($mcData['activity... | csn_ccr |
public function listReportRoute()
{
$this->setTitleListReportRoute();
$this->setBreadcrumbListReportRoute();
$this->setFilterListReportRoute();
$this->setPagerListReportRoute();
| $this->setData('routes', (array) $this->getListReportRoute());
$this->setData('permissions', $this->getPermissionsReportRole());
$this->outputListReportRoute();
} | csn_ccr |
Validates the virtual machine | def validate
super
validates_presence_of :name, :os_type_id, :memory_size, :vram_size, :cpu_count
validates_numericality_of :memory_balloon_size, :monitor_count
validates_inclusion_of :accelerate_3d_enabled, :accelerate_2d_video_enabled, :teleporter_enabled, :in => [true, false]
if !erro... | csn |
This callback is used if async | function done () {
that.fetchQueue.stopFetching(key, arguments);
that.store(key, arguments, callback);
} | csn |
def write_outro (self):
"""Write end of check message."""
self.writeln(u"<br/>")
self.write(_("That's it.")+" ")
if self.stats.number >= 0:
self.write(_n("%d link checked.", "%d links checked.",
self.stats.number) % self.stats.number)
self.w... |
self.writeln(_("Stopped checking at %(time)s (%(duration)s)") %
{"time": strformat.strtime(self.stoptime),
"duration": strformat.strduration_long(duration)})
self.writeln(u'</blockquote><br/><hr><small>'+
configuration.HtmlAppInfo+u"<br/>")
self.w... | csn_ccr |
Set up the disruptor service to have a single consumer which aggregates the data. | @PostConstruct
public void start() {
threadFactory = Executors.defaultThreadFactory();
disruptor = new Disruptor<>(Registration.FACTORY,
ringSize,
threadFactory,
ProducerType.MULTI,
new BlockingWaitStrategy());
disruptor.handleE... | csn |
Returns an array list of peers that implement the given protocol version or better. | public List<Peer> findPeersOfAtLeastVersion(long protocolVersion) {
lock.lock();
try {
ArrayList<Peer> results = new ArrayList<>(peers.size());
for (Peer peer : peers)
if (peer.getPeerVersionMessage().clientVersion >= protocolVersion)
results.a... | csn |
Handle a string with an annotation handler
@param s the String to process
@param ah the annotation handler to use. | public static void handle(String s, AnnotationHandler ah) {
Map<String, Map<String, String>> l = new LinkedHashMap<String, Map<String, String>>();
Matcher m = annPattern.matcher(s);
while (m.find()) {
// for (int i = 1; i <= m.groupCount(); i++) {
// System.out.println(... | csn |
Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. | def submit(self, data, runtime_dir, argv):
"""Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
"""
logger.debug(__(
"Connector '{}' running for Data with id {} ({}).",
self.__class__.__mod... | csn |
Get a GObject property.
The value of the property is converted to a Python value. | def get(self, name):
"""Get a GObject property.
The value of the property is converted to a Python value.
"""
logger.debug('VipsObject.get: name = %s', name)
pspec = self._get_pspec(name)
if pspec is None:
raise Error('Property not found.')
gtype =... | csn |
Gets the generic table columns.
@param array $columns The columns.
@return array The generic columns. | protected function getGenericColumns(array $columns)
{
$genericColumns = array();
foreach ($columns as $column) {
$genericColumns[] = $this->getGenericColumn($column);
}
return $genericColumns;
} | csn |
Output the results to stdout.
TODO: add AMPQ support for efficiency | def output_results(results, metric, options):
"""
Output the results to stdout.
TODO: add AMPQ support for efficiency
"""
formatter = options['Formatter']
context = metric.copy() # XXX might need to sanitize this
try:
context['dimension'] = list(metric['Dimensions'].values())[0]
... | csn |
@Nonnull
public ApiFuture<DocumentReference> add(@Nonnull final Map<String, Object> fields) {
final DocumentReference documentReference = document();
ApiFuture<WriteResult> createFuture = documentReference.create(fields);
| return ApiFutures.transform(
createFuture,
new ApiFunction<WriteResult, DocumentReference>() {
@Override
public DocumentReference apply(WriteResult writeResult) {
return documentReference;
}
});
} | csn_ccr |
lambda function python read in file | def lambda_from_file(python_file):
"""
Reads a python file and returns a awslambda.Code object
:param python_file:
:return:
"""
lambda_function = []
with open(python_file, 'r') as f:
lambda_function.extend(f.read().splitlines())
return awslambda.Code(ZipFile=(Join('\n', lambda_f... | cosqa |
Load and evaluate a GCL expression from a string. | def loads(s, filename=None, loader=None, implicit_tuple=True, env={}, schema=None):
"""Load and evaluate a GCL expression from a string."""
ast = reads(s, filename=filename, loader=loader, implicit_tuple=implicit_tuple)
if not isinstance(env, framework.Environment):
# For backwards compatibility we accept an ... | csn |
Convert current string to 'Title Case'
Example:
'hello world example' -> 'Hello World Example'
@return \BuildR\Utils\StringObject | public function toTitleCase() {
$returnValue = mb_convert_case((string) $this->toLower(), MB_CASE_TITLE);
return $this->createClone($returnValue);
} | csn |
python gaussian distribution pdf | def EvalGaussianPdf(x, mu, sigma):
"""Computes the unnormalized PDF of the normal distribution.
x: value
mu: mean
sigma: standard deviation
returns: float probability density
"""
return scipy.stats.norm.pdf(x, mu, sigma) | cosqa |
private static boolean collectOverriddenMethods(MethodDeclaration md,
/* Nullable */ List<Method> overriddenMethods) {
final MethodSymbolData sdata = md.getSymbolData();
if (sdata == null || isStatic(sdata.getMethod()) || isPrivate(sdata.getMethod())) {
return false;
} e... | if (types != null && !types.isEmpty()) {
if (types.get(0) instanceof Class) {
returnType = (Class<?>) types.get(0);
}
}
if (matchesReturnAndParameters(foundMetho... | csn_ccr |
def set_option(self, option, value):
"""
Set a plugin option in configuration file.
Note: Use sig_option_changed to call it from widgets of the
| same or another plugin.
"""
CONF.set(self.CONF_SECTION, str(option), value) | csn_ccr |
Return all FirewallRule objects based on a server instance or uuid. | def get_firewall_rules(self, server):
"""
Return all FirewallRule objects based on a server instance or uuid.
"""
server_uuid, server_instance = uuid_and_instance(server)
url = '/server/{0}/firewall_rule'.format(server_uuid)
res = self.get_request(url)
return [
... | csn |
func isValidExecContainerAction(action *kops.ExecContainerAction) error {
action.Image = strings.TrimSpace(action.Image)
if action.Image == "" {
return | errors.New("the image for the hook exec action not set")
}
return nil
} | csn_ccr |
public static function get(string $key)
{
$encodedValue = @file_get_contents(self::determineDabaseFilePathFor($key));
if ($encodedValue === false) {
| return null;
}
return Json::decode($encodedValue);
} | csn_ccr |
func Migrate(x *xorm.Engine) error {
if err := x.Sync(new(Version)); err != nil {
return fmt.Errorf("sync: %v", err)
}
currentVersion := &Version{ID: 1}
has, err := x.Get(currentVersion)
if err != nil {
return fmt.Errorf("get: %v", err)
} else if !has {
// If the version record does not exist we think
//... | once. To verify, you should see some migration traces.
3. Once it starts web server successfully, stop it.
4. Now it's time to put back the release archive you originally intent to upgrade.
5. Enjoy!
In case you're stilling getting this notice, go through instructions again until it disappears.`)
return nil
}
if... | csn_ccr |
from mxnet import np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
class Residual(nn.Block):
def __init__(self, num_channels, use_1x1conv=False, strides=1, **kwargs):
super().__init__(**kwargs)
self.conv1 = nn.Conv2D(num_channels, kernel_size=3, padding=1, strides=strides... | import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
class Residual(nn.Module):
def __init__(self, input_channels, num_channels, use_1x1conv=False, strides=1):
super().__init__()
self.conv1 = nn.Conv2d(input_channels, num_channels, kernel_size=3, paddin... | codetrans_dl |
func (r *rpcHandler) forwardServer(server *serverParts, method string, args interface{}, reply interface{}) error {
// Handle a missing server
if server == nil {
return errors.New("must be given a valid server address")
| }
return r.connPool.RPC(r.config.Region, server.Addr, server.MajorVersion, method, args, reply)
} | csn_ccr |
// SetRunConfigurationDescription sets the RunConfigurationDescription field's value. | func (s *ApplicationConfigurationDescription) SetRunConfigurationDescription(v *RunConfigurationDescription) *ApplicationConfigurationDescription {
s.RunConfigurationDescription = v
return s
} | csn |
python create matrix from angle axis rotation | def create_rot2d(angle):
"""Create 2D rotation matrix"""
ca = math.cos(angle)
sa = math.sin(angle)
return np.array([[ca, -sa], [sa, ca]]) | cosqa |
public ValidatorContext<D, O> handleWith(final ResultHandler<O>... resultHandlers) {
if (resultHandlers | != null) {
Collections.addAll(registeredResultHandlers, resultHandlers);
}
return this;
} | csn_ccr |
Export the data associated to this block to an XML node.
@param \SimpleXMLElement $node the parent node where we'll append the XML node to
@param string $exportType set to 'full' to export cache and custom style settings too | public function export($node, $exportType = 'full')
{
if (!$this->isAliasOfMasterCollection() || (($this->c instanceof Page) && $this->c->isMasterCollection())) {
// We have the OR up here so that master collections that you have duplicated from other
// master collections export pro... | csn |
// floatsToEmpties converts a float slice to a slice of the empty interface. | func floatsToEmpties(arr []float64) []interface{} {
ret := make([]interface{}, len(arr))
for i, f := range arr {
ret[i] = f
}
return ret
} | csn |
def _process_list(self, l):
"""
Processes a list of widget names.
If any name is between `` then it is supposed to be a regex.
"""
if hasattr(self, l):
t = getattr(self, l)
def proc(inp):
w = inp.strip()
if w.startswith('... | for u in [m.group() for m in [r.match(x) for x in dir(self)] if m] if isinstance(getattr(self, u), QObject)]
else:
return [w]
return list(set([y for x in map(proc, t.split(',')) for y in x]))
return [] | csn_ccr |
func (f *Flag) IsMulti() bool {
if f.value.Kind() == reflect.Slice {
| return true
}
return false
} | csn_ccr |
func LexSubQuery(l *Lexer) StateFn {
//u.Debugf("LexSubQuery '%v'", l.PeekX(10))
l.SkipWhiteSpaces()
r := l.Peek()
if l.IsEnd() {
return nil
}
if r == ')' {
l.Next()
l.Emit(TokenRightParenthesis)
return nil
}
/*
TODO: this is a hack because the LexDialect from above should be recursive,
ie su... | LexConditionalClause
case "from":
l.ConsumeWord(word)
l.Emit(TokenFrom)
l.Push("LexSubQuery", LexSubQuery)
l.Push("LexConditionalClause", LexConditionalClause)
return LexTableReferences
case ";":
return nil
default:
}
l.Push("LexSubQuery", LexSubQuery)
return LexSelectClause
} | csn_ccr |
Show crashlogs status. | def crashlog_status(**kwargs):
"""
Show crashlogs status.
"""
ctx = Context(**kwargs)
ctx.execute_action('crashlog:status', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | csn |
calculate distance between two geo locations python | def _distance(coord1, coord2):
"""
Return the distance between two points, `coord1` and `coord2`. These
parameters are assumed to be (x, y) tuples.
"""
xdist = coord1[0] - coord2[0]
ydist = coord1[1] - coord2[1]
return sqrt(xdist*xdist + ydist*ydist) | cosqa |
protected function getSiteDirs() {
$sites_dir = $this->get('docroot') . '/sites';
$sites = [];
// If BLT's template has not yet been rsynced into the project root, it is
// possible that docroot/sites does not exist.
if (!file_exists($sites_dir)) {
return $sites;
}
$finder = new Find... | ->in($sites_dir)
->directories()
->depth('< 1')
->exclude(['g', 'settings'])
->sortByName();
foreach ($dirs->getIterator() as $dir) {
$sites[] = $dir->getRelativePathname();
}
return $sites;
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.