query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
// FromStringAndExt is same as FromString, but adds the file extension to the type. | func FromStringAndExt(t, ext string) (Type, error) {
tp, err := fromString(t)
if err != nil {
return tp, err
}
tp.Suffixes = []string{strings.TrimPrefix(ext, ".")}
return tp, nil
} | csn |
func (rows Rows) Header() (results []string) {
if rows.total > 0 {
if rows.Resource.Config.WithoutHeader {
for i := 0; i <= len(rows.records[0]); i++ {
results | = append(results, strconv.Itoa(i))
}
} else {
return rows.records[0]
}
}
return
} | csn_ccr |
Reads next frame image | protected void readImage() throws IOException {
ix = readShort(); // (sub)image position & size
iy = readShort();
iw = readShort();
ih = readShort();
int packed = in.read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
interlace = ... | csn |
func (c *Connector) TruncateScope(ctx context.Context, scope string) error {
// A better authn story is needed -- an evildoer could just craft a request with a
// bogus owner name and send it directly, bypassing this client.
request := &dosarpc.TruncateScopeRequest{
Name: &scope,
Requester: dosa.GetUsername... | err := c.client.TruncateScope(ctx, request, getHeaders(c.headers)...); err != nil {
if !dosarpc.Dosa_TruncateScope_Helper.IsException(err) {
return errors.Wrap(err, "failed to TruncateScope due to network issue")
}
return errors.Wrap(err, "failed to TruncateScope")
}
return nil
} | csn_ccr |
// FormErr sets "Err_xxx" field in template data. | func (c *Context) FormErr(names ...string) {
for i := range names {
c.Data["Err_"+names[i]] = true
}
} | csn |
public boolean isJava7SwitchExpression(final XSwitchExpression it) {
boolean _xblockexpression = false;
{
final LightweightTypeReference switchType = this.getSwitchVariableType(it);
if ((switchType == null)) {
return false;
}
boolean _isSubtypeOf = switchType.isSubtypeOf(Integer.... | = switchType.isSubtypeOf(Enum.class);
if (_isSubtypeOf_1) {
return true;
}
boolean _isSubtypeOf_2 = switchType.isSubtypeOf(String.class);
if (_isSubtypeOf_2) {
return true;
}
_xblockexpression = false;
}
return _xblockexpression;
} | csn_ccr |
def splitlines(self, keepends=False):
"""Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and True.
| :param bool keepends: Include linebreaks.
"""
return [self.__class__(l) for l in self.value_colors.splitlines(keepends)] | csn_ccr |
static function renderCustomSelect( $args ) {
$defaults = [
'id' => null,
'name' => null,
'value' => '',
'choices' => [],
'multiple' => false,
'disabled' => false,
];
$args = wp_parse_args( $args, $defaults );
$is_custom = false;
if ( ! array_key_exists( $args['value'], $args['choices'] ) ... | $key,
( empty( $key ) && $is_custom ) ? ' selected' : selected( $key, $args['value'], false ),
$label
);
}
printf(
'<select name="%s" id="%s" %s%s>%s</select><br />',
$args['name'],
$args['id'],
( $args['multiple'] ) ? ' multiple' : '',
( ! empty( $args['disabled'] ) ) ? ' disabled' : '... | csn_ccr |
Highlight mask on table when user click on canvas. | def hl_canvas2table(self, canvas, button, data_x, data_y):
"""Highlight mask on table when user click on canvas."""
self.treeview.clear_selection()
# Remove existing highlight
if self.maskhltag:
try:
canvas.delete_object_by_tag(self.maskhltag, redraw=True)
... | csn |
public double falsePositiveRate(EvaluationAveraging averaging) {
int nClasses = confusion().getClasses().size();
if (averaging == EvaluationAveraging.Macro) {
double macroFPR = 0.0;
for (int i = 0; i < nClasses; i++) {
macroFPR += falsePositiveRate(i);
... | 0; i < nClasses; i++) {
fpCount += falsePositives.getCount(i);
tnCount += trueNegatives.getCount(i);
}
return EvaluationUtils.falsePositiveRate(fpCount, tnCount, DEFAULT_EDGE_VALUE);
} else {
throw new UnsupportedOperationException("Unknown av... | csn_ccr |
Instantiates a new event collector. | @PostConstruct
public void init() {
//init Bus and LifeCycle listeners
if (bus != null && sendLifecycleEvent ) {
ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class);
if (null != slcm) {
ServiceListenerImpl svrListener = new... | csn |
Ajax service that tails the log file for the selected worker
@param $worker | public function tail($worker)
{
// Form the path to the file
$file = Model::logPath(urldecode($worker));
if (!file_exists($file)) {
throw new Exception('Log not found: '.$file);
}
$size = 1024 * 100; // in bytes to get
// Read from the end of the file
... | csn |
public function removeSkillRelatedByDependencyId(ChildSkill $skillRelatedByDependencyId)
{
if ($this->getSkillsRelatedByDependencyId()->contains($skillRelatedByDependencyId)) { $skillDependency = new ChildSkillDependency();
$skillDependency->setSkillRelatedByDependencyId($skillRelatedByDependen... | if (null === $this->skillsRelatedByDependencyIdScheduledForDeletion) {
$this->skillsRelatedByDependencyIdScheduledForDeletion = clone $this->collSkillsRelatedByDependencyId;
$this->skillsRelatedByDependencyIdScheduledForDeletion->clear();
}
$this->skills... | csn_ccr |
Get the discount amount for the invoice.
@return string | public function amountOff()
{
if (isset($this->invoice->discount->coupon->amount_off)) {
return $this->formatAmount($this->invoice->discount->coupon->amount_off);
}
return $this->formatAmount(0);
} | csn |
@Deprecated
public static void writeWordVectors(ParagraphVectors vectors, OutputStream stream) {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) {
/*
This method acts similary to w2v csv serialization, except of additional tag ... | = vectors.getWordVectorMatrix(word.getLabel());
for (int j = 0; j < vector.length(); j++) {
builder.append(vector.getDouble(j));
if (j < vector.length() - 1) {
builder.append(" ");
}
}
w... | csn_ccr |
func (m *msg) setMode(md mode) { |
m.LiVnMode = (m.LiVnMode & 0xf8) | uint8(md)
} | csn_ccr |
Create client for making HTTP REST requests
@param [Array, String] urls of server being accessed as array or comma-separated string
@option options [String] :api_version for X-API-Version header
@option options [String] :server_name of server for use in exceptions; defaults to host name
@option options [String] :... | def check_health(host = nil)
begin
@http_client.health_check_proc.call(host || @urls.first)
rescue StandardError => e
if e.respond_to?(:http_code) && RETRY_STATUS_CODES.include?(e.http_code)
raise NotResponding.new("#{@server_name || host} not responding", e)
else
... | csn |
Retrieve the value associated with the given key, blocking as long as necessary.
@param k The key.
@return The value associated with the key.
@throws InterruptedException | public V get(K k) throws InterruptedException {
await(k);
return cache.get(k);
} | csn |
Return links.
@param string|null $relation If specified, return only links with this relation type.
@return Link[]
@since 1.0 | public function getLinks($relation = null)
{
$links = $this->getAllLinks();
if (null === $relation) {
return $links;
}
foreach ($links as $key => $link) {
if ($link->getRelation() !== $relation) {
unset($links[$key]);
}
}
... | csn |
dynamically create documents python mongoegine | def __call__(self, *args, **kwargs):
""" Instanciates a new *Document* from this collection """
kwargs["mongokat_collection"] = self
return self.document_class(*args, **kwargs) | cosqa |
Return a fully-qualified span string. | def span_path(cls, project, trace, span):
"""Return a fully-qualified span string."""
return google.api_core.path_template.expand(
"projects/{project}/traces/{trace}/spans/{span}",
project=project,
trace=trace,
span=span,
) | csn |
def remote_trigger_pull(remote_addr, trg_queue, ignore_listener=False,
protocol=u'jsonrpc'):
'''Write a non-blocking byte to a remote trigger fifo, to cause a triggered
scan'''
if protocol == u'jsonrpc':
try:
| server = Server(remote_addr, encoding=_c.FSQ_CHARSET)
return server.trigger_pull(queue=trg_queue,
ignore_listener=ignore_listener,
trigger=_c.FSQ_TRIGGER)
except Exception, e:
raise FSQRemoteTriggerError(e... | csn_ccr |
// DescribeLoadBalancers is not implemented but is required for interface
// conformance | func (elb *FakeELB) DescribeLoadBalancers(input *elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error) {
panic("Not implemented")
} | csn |
func anyNil(objs ...interface{}) bool {
for _, p := range objs {
if p | == nil {
return true
}
}
return false
} | csn_ccr |
protected function determineLighthouseState(array $values, array $opts)
{
$state = 'success';
foreach ($values as $key => $info) {
$required_score = isset($opts["$key-score"])
? ($opts["$key-score"] <= 100 ? $opts["$key-score"] : 100)
| : 50;
if ($info['score'] < $required_score
&& $info['score'] !== $required_score) {
return 'failure';
}
}
return $state;
} | csn_ccr |
Set a new synchronized start period for legacy time attack mode.
Only available to Admin.
Requires a map restart to be taken into account.
@param int $synch
@param bool $multicall
@return bool
@throws InvalidArgumentException | function setTimeAttackSynchStartPeriod($synch, $multicall = false)
{
if (!is_int($synch)) {
throw new InvalidArgumentException('synch = ' . print_r($synch, true));
}
return $this->execute(ucfirst(__FUNCTION__), array($synch), $multicall);
} | csn |
add url to pool and check limits
@param Url $url
@throws \RuntimeException | public function addUrl(Url $url)
{
if ($this->isFull()) {
throw new \RuntimeException('The urlset limit has been exceeded');
}
$urlXml = $url->toXml();
$this->appendXML($urlXml);
//add unknown custom namespaces
$this->customNamespaces = array_merge($this... | csn |
Starts the slot manager with the given leader id and resource manager actions.
@param newResourceManagerId to use for communication with the task managers
@param newMainThreadExecutor to use to run code in the ResourceManager's main thread
@param newResourceActions to use for resource (de-)allocations | public void start(ResourceManagerId newResourceManagerId, Executor newMainThreadExecutor, ResourceActions newResourceActions) {
LOG.info("Starting the SlotManager.");
this.resourceManagerId = Preconditions.checkNotNull(newResourceManagerId);
mainThreadExecutor = Preconditions.checkNotNull(newMainThreadExecutor);... | csn |
public function getMaxRankArray(ConnectionInterface $con = null)
{
if ($con === null) {
$con = Propel::getConnection(CustomerGroupTableMap::DATABASE_NAME);
}
// shift the objects with a position lower than the one of object
| $this->addSelectColumn('MAX(' . CustomerGroupTableMap::RANK_COL . ')');
$stmt = $this->doSelect($con);
return $stmt->fetchColumn();
} | csn_ccr |
Receive a SAML 2 message sent using the HTTP-Artifact binding.
Throws an exception if it is unable receive the message.
@throws \Exception
@return \SAML2\Message|null The received message. | public function receive() : ?Message
{
if (array_key_exists('SAMLart', $_REQUEST)) {
$artifact = base64_decode($_REQUEST['SAMLart']);
$endpointIndex = bin2hex(substr($artifact, 2, 2));
$sourceId = bin2hex(substr($artifact, 4, 20));
} else {
throw new \... | csn |
The most important method.
Will start the hive engine and listening for requests.
@param Request $request
@param AbstractResponse $response
@param boolean $sendResponse
@return void | public function api($request = null, $response = null, $sendResponse = true)
{
$this->klein->respond('POST', '/authenticate', $this->authenticate);
$this->klein->onHttpError($this->handleError);
// see https://github.com/klein/klein.php/wiki/Sub-Directory-Installation
if ($request =... | csn |
func sliceContains(container []*html.Node, contained *html.Node) bool {
for _, n := range container {
| if nodeContains(n, contained) {
return true
}
}
return false
} | csn_ccr |
Determine if the given monitor is healthy.
@param string $monitor
@return bool | public function isHealthy($monitor)
{
$result = $this->getStatus($monitor);
if (is_null($result)) {
return false;
}
return $result->healthy;
} | csn |
static Node newVarNode(String name, Node value) {
Node lhs = IR.name(name);
| if (value != null) {
lhs.srcref(value);
}
return newVarNode(lhs, value);
} | csn_ccr |
public AddonChange removeAddon(String appName, String addonName) {
| return connection.execute(new AddonRemove(appName, addonName), apiKey);
} | csn_ccr |
// PutOnboardingStatus will update the flag,
// so future onboarding request will be denied. | func (c *Client) PutOnboardingStatus(ctx context.Context, v bool) error {
if v {
return c.db.Update(func(tx *bolt.Tx) error {
return tx.Bucket(onboardingBucket).Put(onboardingKey, []byte{0x1})
})
}
return nil
} | csn |
// SetFileToContents stores the file to contents map for the FakeCommandRunner | func (f *FakeCommandRunner) SetFileToContents(fileToContents map[string]string) {
for k, v := range fileToContents {
f.fileMap.Store(k, v)
}
} | csn |
Generate a unique string | function () {
var text = ''
var regx = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (var idx = 0; idx < 8; idx++) {
text = text + regx.charAt(Math.floor(Math.random() * regx.length))
}
return text
} | csn |
private function convertDocument(\DOMDocument $xml)
{
return | $this->loader->load($xml->saveXML(), [LoaderInterface::FROM_STRING => true]);
} | csn_ccr |
// Delete deletes the workspace temporary directory. | func (w *Workspace) Delete() {
if w.gopath != "" {
os.Setenv("GOPATH", w.gopath)
}
os.RemoveAll(w.Path)
} | csn |
Checks if the given type matches any valid service that implements
appropriate service interfaces.
@param string $category Service category
@param string $type Service type
@return bool | private function serviceExists(string $category, string $type): bool
{
$service_class = $this->convertTypeToServiceClassName($category, $type);
if(is_null($service_class))
return false;
$interfaces = class_implements($service_class);
if($interfaces===false || !is_array($interfaces))
retur... | csn |
private function read(int $position): array
{
$row = pg_fetch_array($this->resource, $position, $this->mode);
foreach ($row as $key => &$value) {
if (PGSQL_ASSOC === $this->mode) {
$value = $this->converters[$this->namesHash[$key]]->input($value);
| } else {
$value = $this->converters[$key]->input($value);
}
}
return $row;
} | csn_ccr |
def fnd_unq_rws(A, return_index=False, return_inverse=False):
"""Find unique rows in 2D array.
Parameters
----------
A : 2d numpy array
Array for which unique rows should be identified.
return_index : bool
Bool to decide whether I is returned.
return_inverse : bool
Bool ... | "array must be 2-dim'l"
B = np.unique(A.view([('', A.dtype)]*A.shape[1]),
return_index=return_index,
return_inverse=return_inverse)
if return_index or return_inverse:
return (B[0].view(A.dtype).reshape((-1, A.shape[1]), order='C'),) \
+ B[1:]
else:
... | csn_ccr |
Instantiates a new Executable object.
The 'param' argument is a named value hash. The following keys are
significant:
:argv - An array of cli arguments (default ARGV)
:opts - executable/function options for use when running 'go'
:stdout, - IO redirection (mostly for unit tests)
:stderr,
:stdin
The... | def exit(ret)
@exit_status = ret
if defined? Rbkb::Cli::TESTING
throw(((ret==0)? :exit_zero : :exit_err), ret)
else
Kernel.exit(ret)
end
end | csn |
def get_tree_size(path):
"""Return total size of all files in directory tree at path."""
size = 0
try:
for entry in scandir.scandir(path):
if entry.is_symlink():
pass
elif entry.is_dir():
| size += get_tree_size(os.path.join(path, entry.name))
else:
size += entry.stat().st_size
except OSError:
pass
return size | csn_ccr |
Initializes a new graph from a given graph context.
@param graphContext graph context
@return new graph | private Graph initNewGraph(GDLParser.GraphContext graphContext) {
Graph g = new Graph();
g.setId(getNewGraphId());
List<String> labels = getLabels(graphContext.header());
g.setLabels(labels.isEmpty() ?
useDefaultGraphLabel ? Collections.singletonList(defaultGraphLabel) : Collections.emptyList()
... | csn |
Returns a list of all methods available in the current entry point | def __system_listMethods(**kwargs):
"""Returns a list of all methods available in the current entry point"""
entry_point = kwargs.get(ENTRY_POINT_KEY)
protocol = kwargs.get(PROTOCOL_KEY)
return registry.get_all_method_names(entry_point, protocol, sort_methods=True) | csn |
public static Response put(String url,
String body,
Map<String, String> query,
| Map<String, String> headers,
int connectTimeOut,
int readTimeOut) throws HttpException {
return execute("PUT", url, body, query, headers, connectTimeOut, readTimeOut);
} | csn_ccr |
Push this request to the front of the line, just to be a jerk. | def resubmit(self, req, keyspace, req_d, retries):
"""
Push this request to the front of the line, just to be a jerk.
"""
self.log('resubmitting %s request' % (req.method,))
self.pushRequest_really(req, keyspace, req_d, retries)
try:
self.request_queue.pending... | csn |
@SuppressWarnings("unchecked")
private SimpleOrderedMap<Object> createSpan(ComponentSpan span,
Boolean encode) throws IOException {
// System.out.println("Create stats span " + span.dataType + " "
// + span.statsType + " " + span.statsItems + " --- " + encode);
SimpleOrderedMap<Object> mtasSpanRespo... | for (SubComponentFunction function : span.functions) {
function.dataCollector.close();
functionDataItem.put(function.key, new MtasSolrMtasResult(
function.dataCollector, new String[] { function.dataType },
new String[] { function.statsType },
new SortedSet[] { funct... | csn_ccr |
def _slice(index, n_samples, margin=None):
"""Return a waveform slice."""
if margin is None:
margin = (0, 0)
assert isinstance(n_samples, (tuple, list))
assert len(n_samples) == 2
before, after = | n_samples
assert isinstance(margin, (tuple, list))
assert len(margin) == 2
margin_before, margin_after = margin
before += margin_before
after += margin_after
index = int(index)
before = int(before)
after = int(after)
return slice(max(0, index - before), index + after, None) | csn_ccr |
There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively.
For each of these bags, you will paint one of the balls red, and paint the other blue.
Afterwards, the 2N balls will be classified according to color.
Then, we will define the foll... | import sys
def input():
return sys.stdin.readline()[:-1]
n = int(input())
d = []
M, m = 0, 10**30
M_of_m, m_of_M = 0, 10**30
for _ in range(n):
x, y = map(int, input().split())
g, l = max(x, y), min(x, y)
d.append([l, g])
M = max(M, g)
m = min(m, l)
M_of_m = max(M_of_m, l)
m_of_M = min(m_of_M, g)
ans1 = (M - m... | apps |
Compute the SAG algorithm to solve the regularized discrete measures
optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1 = b
... | def sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None):
'''
Compute the SAG algorithm to solve the regularized discrete measures
optimal transport max problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\... | csn |
def commit(self):
"""Commits the current transaction."""
if self._transaction_nesting_level == 0:
raise DBALConnectionError.no_active_transaction()
if self._is_rollback_only:
raise DBALConnectionError.commit_failed_rollback_only()
self.ensure_connected()
... | elif self._nest_transactions_with_savepoints:
self.release_savepoint(self._get_nested_transaction_savepoint_name())
self._transaction_nesting_level -= 1
if not self._auto_commit and self._transaction_nesting_level == 0:
self.begin_transaction() | csn_ccr |
func (m *Memory) Update(ctx context.Context, i backend.Item) (*backend.Lease, error) {
if len(i.Key) == 0 {
return nil, trace.BadParameter("missing parameter key")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
if m.tree.Get(&btreeItem{Item: i}) == nil {
return nil, trace.NotFound("key %q is not found", string... | }
if !m.Mirror {
i.ID = m.generateID()
}
event := backend.Event{
Type: backend.OpPut,
Item: i,
}
m.processEvent(event)
if !m.EventsOff {
m.buf.Push(event)
}
return m.newLease(i), nil
} | csn_ccr |
def unpack(str)
str.bytes.reverse.reduce(0) { |s, | c| s * 256 + c }
end | csn_ccr |
func NewOauth2Scopes(in interface{}, context *compiler.Context) (*Oauth2Scopes, error) {
errors := make([]error, 0)
x := &Oauth2Scopes{}
m, ok := compiler.UnpackMap(in)
if !ok {
message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
errors = append(errors, compiler.NewError(context, message))
} else ... | k, ok := compiler.StringValue(item.Key)
if ok {
v := item.Value
pair := &NamedString{}
pair.Name = k
pair.Value = v.(string)
x.AdditionalProperties = append(x.AdditionalProperties, pair)
}
}
}
return x, compiler.NewErrorGroupOrNil(errors)
} | csn_ccr |
python get clipboard contents | def paste(cmd=paste_cmd, stdout=PIPE):
"""Returns system clipboard contents.
"""
return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8') | cosqa |
Wrapper for any type of finish, successful, permanant failure or
temporary failure | def done(item, done_type=None, max_tries=None, ttl=None):
'''Wrapper for any type of finish, successful, permanant failure or
temporary failure'''
if done_type is None or done_type == _c.FSQ_SUCCESS:
return success(item)
return fail(item, fail_type=done_type, max_tries=max_tries, ttl=ttl) | csn |
def setup
ensure_not_in_dest
plugin_manager.conscientious_require
self.converters | = instantiate_subclasses(Bunto::Converter)
self.generators = instantiate_subclasses(Bunto::Generator)
end | csn_ccr |
function () {
var result = 0;
utils.forEach(
this.$.tabs.getControls(),
function (tab){
var w = tab.origWidth() ;
// must add margin and padding of inner | button and outer tab-item
result += w + 18 ;
}
);
return result;
} | csn_ccr |
public static void hiddenFromEncodedString(ProjectFilterSettings result, String s) {
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String categories;
if (bar >= 0) {
categories = | s.substring(0, bar);
} else {
categories = s;
}
StringTokenizer t = new StringTokenizer(categories, LISTITEM_DELIMITER);
while (t.hasMoreTokens()) {
String category = t.nextToken();
result.removeCategory(category);
... | csn_ccr |
<T extends Entity> EntityCollection<T> getMultiRelation(String name) {
| return getMultiRelation(name, true);
} | csn_ccr |
public function getSpi(BindingSessionInterface $session)
{
$spi = $session->get(self::SPI_OBJECT);
if ($spi !== null) {
return $spi;
}
$spiClass = $session->get(SessionParameter::BINDING_CLASS);
if (empty($spiClass) || !class_exists($spiClass)) {
thr... | not implement required CmisInterface!', $spiClass)
);
}
try {
$spi = new $spiClass($session);
} catch (\Exception $exception) {
throw new CmisRuntimeException(
sprintf('Could not create object of type "%s"!', $spiClass),
null,... | csn_ccr |
Move the physical binary data to this SQL parameter row.
This method used the setTimestamp statement method.
@param statement The SQL prepare statement.
@param iType the type of SQL statement.
@param iParamColumn The column in the prepared statement to set the data.
@exception SQLException From SQL calls. | public void getSQLFromField(PreparedStatement statement, int iType, int iParamColumn) throws SQLException
{
if (this.isNull())
{
if ((!this.isNullable())
|| (iType == DBConstants.SQL_SELECT_TYPE)
|| (DBConstants.FALSE.equals(this.getRecord().getTable().get... | csn |
python stop logging for unit tests | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | cosqa |
Insert rows using a single batch query
@param string $table
@param array $rows
@return \PDOStatement|null | protected function insertBatch( $table, $rows ) {
$columns = $this->getColumns( $rows );
if ( empty( $columns ) ) return;
$query = $this->insertHead( $table, $columns );
$lists = $this->valueLists( $rows, $columns );
$query .= implode( ", ", $lists );
$this->onQuery( $... | csn |
private function _readMsoDrawingGroup()
{
$length = self::_GetInt2d($this->_data, $this->_pos + 2);
// get spliced record data
$splicedRecordData = $this->_getSplicedRecordData();
| $recordData = $splicedRecordData['recordData'];
$this->_drawingGroupData .= $recordData;
} | csn_ccr |
List server VirtualNetworkInterfaces
REST: GET /dedicated/server/{serviceName}/virtualNetworkInterface
@param name [required] Filter the value of name property (=)
@param vrack [required] Filter the value of vrack property (=)
@param mode [required] Filter the value of mode property (=)
@param serviceName [required] T... | public ArrayList<String> serviceName_virtualNetworkInterface_GET(String serviceName, OvhVirtualNetworkInterfaceModeEnum mode, String name, String vrack) throws IOException {
String qPath = "/dedicated/server/{serviceName}/virtualNetworkInterface";
StringBuilder sb = path(qPath, serviceName);
query(sb, "mode", mod... | csn |
Setup an HTTP session authorized by OAuth2. | def _setupHttp(self):
"""
Setup an HTTP session authorized by OAuth2.
"""
if self._http == None:
http = httplib2.Http()
self._http = self._credentials.authorize(http) | csn |
// Determine our index in the async peer list. -1 means not present. | func (p *Peer) whichAsync() int {
for i, a := range p.Info().State.Async {
if p.id == a.Meta[p.idKey] {
return i
}
}
return -1
} | csn |
func (s *DurationRange) SetMinSeconds(v int64) *DurationRange {
| s.MinSeconds = &v
return s
} | csn_ccr |
Updates topology
Links are not deleted straightaway but set as "disconnected" | def update(self):
"""
Updates topology
Links are not deleted straightaway but set as "disconnected"
"""
from .link import Link # avoid circular dependency
diff = self.diff()
status = {
'added': 'active',
'removed': 'disconnected',
... | csn |
public function create($owner, $repo, $tree, $base_tree = '')
{
// Build the request path.
$path = '/repos/' . $owner . '/' . $repo . '/git/trees';
| $data = array();
$data['tree'] = $tree;
if ($base_tree)
{
$data['base_tree'] = $base_tree;
}
return $this->processResponse(
$this->client->post($this->fetchUrl($path), json_encode($data)),
201
);
} | csn_ccr |
func (r *Reader) copy(b []byte) (n int) {
n += copy(b, r.buf)
if len(r.buf) >= n {
// If there's still some buffered data left, truncate the buffer
| // and return.
r.buf = r.buf[n:]
}
if len(r.buf) == 0 {
r.done()
}
return
} | csn_ccr |
See comments on writeObject. | private void readObject( ObjectInputStream stream )
throws IOException, ClassNotFoundException
{
if ( _log.isInfoEnabled() ) _log.info( "deserializing ActionServlet " + this );
_configParams = ( Map ) stream.readObject();
} | csn |
private static function create($decoded, Json $json)
{
$json->validate(
$json->decodeFile(PHAR_UPDATE_MANIFEST_SCHEMA),
$decoded
);
$updates = array();
foreach ($decoded as $update) {
$updates[] = new Update(
$update->name,
... | }
usort(
$updates,
function (Update $a, Update $b) {
return Comparator::isGreaterThan(
$a->getVersion(),
$b->getVersion()
);
}
);
return new static($updates);
} | csn_ccr |
protected function _renderGroup($sql)
{
if ($this->_parts[self::FROM] && $this->_parts[self::GROUP]) {
$group = array();
foreach ($this->_parts[self::GROUP] as | $term) {
$group[] = $this->_adapter->quoteIdentifier($term, true);
}
$sql .= ' ' . self::SQL_GROUP_BY . ' ' . implode(",\n\t", $group);
}
return $sql;
} | csn_ccr |
private void DrawPrimitive( DrawEntity e, World w ) throws Exception
{
String oldEntityName = e.getType().getValue();
String id = null;
for (EntityEntry ent : net.minecraftforge.fml.common.registry.ForgeRegistries.ENTITIES)
{
if (ent.getName().equals(oldEntityName))
... | ((EntityLivingBase)entity).prevRotationYawHead = e.getYaw().floatValue();
((EntityLivingBase)entity).rotationYawHead = e.getYaw().floatValue();
((EntityLivingBase)entity).prevRenderYawOffset = e.getYaw().floatValue();
((EntityLivingBase)entity).renderYawOffs... | csn_ccr |
Handles dealing with Represent\Property annotation
@param \ReflectionProperty $property
@param Property $annot
@param \Represent\Context\PropertyContext $context
@param $original
@return PropertyContext | private function handleRepresentProperty(\ReflectionProperty $property, Property $annot, PropertyContext $context, $original)
{
if ($annot->getName()) {
$context->name = $annot->getName();
}
if ($annot->getType()) {
$context->value = $this->propertyHandler->handleTyp... | csn |
function(image, width, height) {
var g;
if (image.tagName === 'CANVAS' && image.width === width
&& image.height === height) {
g = image.getContext('2d');
} else {
var canvas = this._newCanvas(width, height);
canvas.width = width;
| canvas.height = height;
g = canvas.getContext('2d');
g.drawImage(image, 0, 0, width, height);
}
var data = g.getImageData(0, 0, width, height).data;
return data;
} | csn_ccr |
// identityMatches returns true if pod has a valid identity and network identity for a member of set. | func identityMatches(set *apps.StatefulSet, pod *v1.Pod) bool {
parent, ordinal := getParentNameAndOrdinal(pod)
return ordinal >= 0 &&
set.Name == parent &&
pod.Name == getPodName(set, ordinal) &&
pod.Namespace == set.Namespace &&
pod.Labels[apps.StatefulSetPodNameLabel] == pod.Name
} | csn |
// Returns whether the region fully covers the argument region | func (r Region) Covers(r2 Region) bool {
return r.Contains(r2.Begin()) && r2.End() <= r.End()
} | csn |
def image_export(cls, source_path, dest_url, **kwargs):
"""Export the specific image to remote host or local file system """
dest_path = urlparse.urlparse(dest_url).path
if kwargs['remote_host']:
target_path = ':'.join([kwargs['remote_host'], dest_path])
command = ' '.joi... | try:
shutil.copyfile(source_path, dest_path)
except Exception as err:
msg = ("Export image from %(src)s to local file system"
" %(dest)s failed: %(err)s" %
{'src': source_path,
'dest': dest_path,
... | csn_ccr |
public static Dimension rectangleDoubleToDimension(final Rectangle2D.Double rectangle) {
return new Dimension(
| (int) Math.round(rectangle.width),
(int) Math.round(rectangle.height));
} | csn_ccr |
function(playlistId, tracks, options, callback) {
return WebApiRequest.builder(this.getAccessToken())
.withPath('/v1/playlists/' + playlistId + '/tracks')
.withHeaders({ 'Content-Type': 'application/json' })
.withQueryParameters(options) |
.withBodyParameters({
uris: tracks
})
.build()
.execute(HttpManager.post, callback);
} | csn_ccr |
Set the pololu protocol. | def setPololuProtocol(self):
"""
Set the pololu protocol.
"""
self._compact = False
self._log and self._log.debug("Pololu protocol has been set.") | csn |
public static Label createNameValueLabel(final String label, final String... values) {
final String valueStr = StringUtils.arrayToDelimitedString(values, " ");
final Label nameValueLabel = new Label(getBoldHTMLText(label) + valueStr, ContentMode.HTML);
nameValueLabel.setSizeFull();
| nameValueLabel.addStyleName(SPUIDefinitions.TEXT_STYLE);
nameValueLabel.addStyleName("label-style");
return nameValueLabel;
} | csn_ccr |
func (exec *TabletExecutor) Open(ctx context.Context, keyspace string) error {
if !exec.isClosed {
return nil
}
exec.keyspace = keyspace
shardNames, err := exec.wr.TopoServer().GetShardNames(ctx, keyspace)
if err != nil {
return fmt.Errorf("unable to get shard names for keyspace: %s, error: %v", keyspace, err)... | return fmt.Errorf("shard: %s does not have a master", shardName)
}
tabletInfo, err := exec.wr.TopoServer().GetTablet(ctx, shardInfo.MasterAlias)
if err != nil {
return fmt.Errorf("unable to get master tablet info, keyspace: %s, shard: %s, error: %v", keyspace, shardName, err)
}
exec.tablets[i] = tabletI... | csn_ccr |
Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element. | def dropout_mask(x:Tensor, sz:Collection[int], p:float):
"Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element."
return x.new(*sz).bernoulli_(1-p).div_(1-p) | csn |
def update_instance_extent(self, instance, module, operation):
"""Updates a new instance that was added to a module to be complete
if the end token is present in any remaining, overlapping operations.
"""
#Essentially, we want to look in the rest of the statements that are
#part ... | to check the next operation if it is a neighbor
#in line numbers in the buffer.
if noperation.ibuffer[0] - opstack[-1].ibuffer[1] == 1:
(ibuffer, length) = self._find_end_token(end_token, noperation)
cum_length += length
opstack.append(noperation)... | csn_ccr |
// RSAPublicKeyFromPEM decodes a PEM-encoded RSA public key | func RSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
parsed, err := parsePEM(key)
if err != nil {
return nil, err
}
var parsedKey crypto.PublicKey
if parsedKey, err = x509.ParsePKIXPublicKey(parsed); err != nil {
cert, err := x509.ParseCertificate(parsed)
if err != nil {
return nil, ErrNotRSAPub... | csn |
public function cache(){
$args = \func_get_args();
switch(\count($args)){
case 1:
return $this->helper('cache')->read($args[0]);
case 2:
| return $this->helper('cache')->write($args[0], $args[1]);
}
return null;
} | csn_ccr |
Adds the bifurcated consumer to the list of associated consumers.
@param consumer | protected void attachBifurcatedConsumer(BifurcatedConsumerSessionImpl consumer)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "attachBifurcatedConsumer", consumer);
// Create a bifurcated list if required
if (_bifurcatedConsumers == null)
... | csn |
Run a virus scan against a file
@param string $file The name of the file [not full path]
@return boolean | public function isSafe($file)
{
$file = Util::normalizePath($file);
return (bool) $this->adapter->isSafe($file);
} | csn |
def _fields_valid(self, d):
"""Verify that all necessary fields are present
Determine whether the fields parsed represent a host or
service perfdata. If the perfdata is unknown, return False.
If the perfdata does not contain all fields required for that
type, return False. Other... | fields = self.GENERIC_FIELDS + self.HOST_FIELDS
elif datatype == 'SERVICEPERFDATA':
fields = self.GENERIC_FIELDS + self.SERVICE_FIELDS
else:
return False
for field in fields:
if field not in d:
return False
return True | csn_ccr |
Builds the DDL SQL to modify a column
@return string | public function getModifyColumnDDL(PropelColumnDiff $columnDiff)
{
$toColumn = $columnDiff->getToColumn();
$pattern = "
ALTER TABLE %s MODIFY %s;
";
return sprintf($pattern,
$this->quoteIdentifier($toColumn->getTable()->getName()),
$this->getColumnDDL($toColumn)
... | csn |
def _get_view_infos(
self,
trimmed=False):
"""query the sherlock-catalogues database view metadata
"""
self.log.debug('starting the ``_get_view_infos`` method')
sqlQuery = u"""
SELECT v.*, t.description as "master table" FROM crossmatch_catalogues.tcs... | desc
""" % locals()
viewInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
for r in viewInfo:
orow = collections.OrderedDict(s... | csn_ccr |
def _load(self, scale=1.0):
"""Load the SLSTR relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
ncf = Dataset(self.requested_band_filename, 'r')
| wvl = ncf.variables['wavelength'][:] * scale
resp = ncf.variables['response'][:]
self.rsr = {'wavelength': wvl, 'response': resp} | csn_ccr |
public function bulkIndexLocations(array $locations)
{
$documents = array();
foreach ($locations as $location) {
$documents[] = | $this->mapper->mapLocation($location);
}
$this->gateway->bulkIndex($documents);
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.