query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Returns a single MeasurementGate applied to all the given qubits.
The qubits are measured in the computational basis.
Args:
*qubits: The qubits that the measurement gate should measure.
key: The string key of the measurement. If this is None, it defaults
to a comma-separated list o... | def measure(*qubits: raw_types.Qid,
key: Optional[str] = None,
invert_mask: Tuple[bool, ...] = ()
) -> gate_operation.GateOperation:
"""Returns a single MeasurementGate applied to all the given qubits.
The qubits are measured in the computational basis.
Args:
*q... | csn |
// BuildTriangle returns string representing a triangle shape | func BuildTriangle(sideLength, height float64) string {
halfWidth := sideLength / 2
return fmt.Sprintf("%v,0,%v,%v,0,%v,%v,0", halfWidth, sideLength, height, height, halfWidth)
} | csn |
python plink problems with m command file | def locate(command, on):
"""Locate the command's man page."""
location = find_page_location(command, on)
click.echo(location) | cosqa |
public void add(final String source, final T destination) {
// replace multiple slashes with a single slash.
String path = source.replaceAll("/+", "/");
path = (path.endsWith("/") && path.length() > 1)
? path.substring(0, path.length() - 1) : path;
String[] parts = path.split("/", maxPathParts... | Matcher groupMatcher = GROUP_PATTERN.matcher(part);
if (groupMatcher.matches()) {
groupNames.add(groupMatcher.group(1));
sb.append("([^/]+?)");
} else if (WILD_CARD_PATTERN.matcher(part).matches()) {
sb.append(".*?");
} else {
sb.append(part);
}
sb.append(... | csn_ccr |
Returns the body text in the original charset.
@return string HTML text. | public function returnBody()
{
$body = $this->getBody();
$text = '';
if ($body->hasChildNodes()) {
foreach ($body->childNodes as $child) {
$text .= $this->dom->saveXML($child);
}
}
return Horde_String::convertCharset($text, 'UTF-8', $... | csn |
protected function validateTimestamps(array $payload)
{
$timestamp = $this->timestamp ?: \time();
$checks = [
['exp', $this->leeway /* */ , static::ERROR_TOKEN_EXPIRED, 'Expired'],
['iat', $this->maxAge - $this->leeway, static::ERROR_TOKEN_EXPIRED, 'Expired'],
... | $this->leeway, static::ERROR_TOKEN_NOT_NOW, 'Not now'],
];
foreach ($checks as list($key, $offset, $code, $error)) {
if (isset($payload[$key])) {
$offset += $payload[$key];
$fail = $key === 'nbf' ? $timestamp <= $offset : $timestamp >= $offset;
... | csn_ccr |
Returns a field in a Json object as a long.
@param object the Json Object
@param field the field in the Json object to return
@param defaultValue a default value for the field if the field value is null
@return the Json field value as a long | public static long getLong(JsonObject object, String field, long defaultValue) {
final JsonValue value = object.get(field);
if (value == null || value.isNull()) {
return defaultValue;
} else {
return value.asLong();
}
} | csn |
protected void reportFailure (Throwable caught)
{
java.util.logging.Logger.getLogger(" | PagedWidget").warning("Failure to page: " + caught);
} | csn_ccr |
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained w... | class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
a,b,m=[deque([0]*x) for x in rollMax],[1]*6,1000000007
for x in a: x[-1]=1
for _ in range(n-1):
s=sum(b)%m
for i,x in enumerate(a):
x.append((s-b[i])%m)
b[i]=(b[... | apps |
Returns the number of documents the specified term appears in. | def get_document_frequency(self, term):
"""
Returns the number of documents the specified term appears in.
"""
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
else:
return len(self._terms[term]) | csn |
Adds a script to the page
@param string $content Script
@param string $type Scripting mime (defaults to 'text/javascript')
@return object Document instance of $this to allow chaining | public function addScriptDeclaration($content, $type = 'text/javascript')
{
if (!isset($this->_script[strtolower($type)]))
{
$this->_script[strtolower($type)] = array($content);
}
else
{
$this->_script[strtolower($type)][] = chr(13) . $content;
}
return $this;
} | csn |
// NewSecretService returns a mock SecretService where its methods will return
// zero values. | func NewSecretService() *SecretService {
return &SecretService{
LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) {
return "", fmt.Errorf("not implmemented")
},
GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) {
return nil, fmt.Errorf("not i... | csn |
func (s *ReferenceDataSourceDescription) SetS3ReferenceDataSourceDescription(v *S3ReferenceDataSourceDescription) | *ReferenceDataSourceDescription {
s.S3ReferenceDataSourceDescription = v
return s
} | csn_ccr |
Writes output to stderr.
:arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap
the output. | def err(*output, **kwargs):
"""Writes output to stderr.
:arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap
the output.
"""
output = 'Error: ' + ' '.join([str(o) for o in output])
if kwargs.get('wrap') is not False:
output = '\n'.join(wrap(output, kwargs.get('indent',... | csn |
function picker(iteratees) {
iteratees = iteratees || ['name']
| return _.partial(_.pick, _, iteratees)
} | csn_ccr |
Checks if execpatch has been disabled in config.php | public function write_setting($data) {
global $CFG;
if (!empty($CFG->preventexecpath)) {
if ($this->get_setting() === null) {
// Use default during installation.
$data = $this->get_defaultsetting();
if ($data === null) {
$da... | csn |
Capture order after changing it to shipped
@throws Exception | public function sendorder()
{
parent::sendorder();
/** @var oxOrder $oOrder */
$oOrder = $this->_getContainer()->getObjectFactory()->createOxidObject('oxOrder');
if ($oOrder->load($this->getEditObjectId()) === true
&& $oOrder->getFieldData('oxPaymentType') === 'bestitama... | csn |
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanat... | class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return int(x**0.5) | apps |
to extract qualified name with prefix | public static Set<QualifiedName> extractNames(Expression expression, Set<NodeRef<Expression>> columnReferences)
{
ImmutableSet.Builder<QualifiedName> builder = ImmutableSet.builder();
new QualifiedNameBuilderVisitor(columnReferences).process(expression, builder);
return builder.build();
... | csn |
Add a file to the zip file, or search a file.
@param {string|RegExp} name The name of the file to add (if data is defined),
the name of the file to find (if no data) or a regex to match files.
@param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
@param {Object} o Fil... | function(name, data, o) {
if (arguments.length === 1) {
if (utils.isRegExp(name)) {
var regexp = name;
return this.filter(function(relativePath, file) {
return !file.options.dir && regexp.test(relativePath);
});
}
... | csn |
def handle_response(self, msgtype, msgid, response):
| """Handle a response."""
self._proxy.response(msgid, response) | csn_ccr |
func (b Bar) String() string {
return fmt.Sprintf("%v, %v, | %v\n", b.From, b.To, b.Count)
} | csn_ccr |
def get_extra_info(self, username):
"""Get extra info for the given user.
Raise a ServerError if an error occurs in the request process.
@param username The username for the user who's | info is being accessed.
"""
url = self._get_extra_info_url(username)
return make_request(url, timeout=self.timeout) | csn_ccr |
Gets the dimensionValue value for this ProductBiddingCategoryData.
@return dimensionValue * The dimension value that corresponds to this category. | public com.google.api.ads.adwords.axis.v201809.cm.ProductBiddingCategory getDimensionValue() {
return dimensionValue;
} | csn |
Resolve the url of the dataset when reading latest.xml.
Parameters
----------
catalog_url : str
The catalog url to be resolved | def resolve_url(self, catalog_url):
"""Resolve the url of the dataset when reading latest.xml.
Parameters
----------
catalog_url : str
The catalog url to be resolved
"""
if catalog_url != '':
resolver_base = catalog_url.split('catalog.xml')[0]
... | csn |
def write(self):
"""Construct the response header.
The return value is a list containing the whole response header, with
each line as a list element.
"""
slist = []
slist.append('{}/{}.{} {} {}'.format(
self.protocol,
self... | self.version[1],
self.code,
status_messages[self.code]))
slist.extend(self.write_headers())
slist.append('\r\n')
return slist | csn_ccr |
def parse_paragraph(l, c, last_div_node, last_section_node, line):
"""
Extracts a paragraph node
:param l: The line number (starting from 0)
:param last_div_node: The last div node found
:param last_section_node: The last section node found
:param line: The line string (without indentation)
| :return: The extracted paragraph node
"""
if not line.endswith('.'):
return None
name = line.replace(".", "")
if name.strip() == '':
return None
if name.upper() in ALL_KEYWORDS:
return None
parent_node = last_div_node
if last_section_node is not None:
parent_... | csn_ccr |
Write a list of custom field attributes. | private void writeCustomFields() throws IOException
{
m_writer.writeStartList("custom_fields");
for (CustomField field : m_projectFile.getCustomFields())
{
writeCustomField(field);
}
m_writer.writeEndList();
} | csn |
public function extractTextFromUrl($url, $language, $useDefaultDictionaries)
{
$strURI = Product::$baseProductUri . '/ocr/recognize?url=' . $url . '&language=' . $language . '&useDefaultDictionaries=' . $useDefaultDictionaries;
$signedURI = Utils::sign($strURI);
| $responseStream = Utils::processCommand($signedURI);
$json = json_decode($responseStream);
return $json;
} | csn_ccr |
// SetAfterDrawFunc installs a callback function which is invoked after the root
// primitive was drawn during screen updates.
//
// Provide nil to uninstall the callback function. | func (a *Application) SetAfterDrawFunc(handler func(screen tcell.Screen)) *Application {
a.afterDraw = handler
return a
} | csn |
python sort filenames like windows | def sort_filenames(filenames):
"""
sort a list of files by filename only, ignoring the directory names
"""
basenames = [os.path.basename(x) for x in filenames]
indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])]
return [filenames[x] for x in indexes] | cosqa |
// Main entry point | func Main(module Module, commandModules ...Module) {
app := NewApp(module, commandModules...)
errutil.Trace(app.Run(os.Args))
} | csn |
def regenerate_index_and_spaces
PEROBS.log.warn "Re-generating FlatFileDB index and space files"
@index.open unless @index.is_open?
@index.clear
@space_list.open unless @space_list.is_open?
@space_list.clear
@progressmeter.start('Re-generating database index', @f.size) do |pm|
... | if header.length > 0
@space_list.add_space(header.addr, header.length)
end
discard_damaged_blob(header)
else
@index.insert(header.id, header.addr)
end
else
if header.length > 0
@space_list.add_space(h... | csn_ccr |
// NewLocation creates and returns a Location type. | func NewLocation(msg string, a ...interface{}) Location {
msg = fmt.Sprintf(msg, a...)
return Location{
error: errors.New(msg),
}
} | csn |
python scripts incorporate credentials | def get_login_credentials(args):
"""
Gets the login credentials from the user, if not specified while invoking
the script.
@param args: arguments provided to the script.
"""
if not args.username:
args.username = raw_input("Enter Username: ")
if not args.password:
args.password = getpass.ge... | cosqa |
public void setAttribute(ScoreAttribute sa, Object value) {
if (value == null)
m_attributes.remove(sa.getName());
else
| m_attributes.put(sa.getName(), value);
notifyListeners();
} | csn_ccr |
public function viewLiveAction(Request $request, $locale, $path = null)
{
$request->setLocale($locale);
| return $this->changeViewMode($request, PageInterface::STATUS_PUBLISHED, $path);
} | csn_ccr |
sign up in background.
@return | public Observable<AVUser> signUpInBackground() {
JSONObject paramData = generateChangedParam();
logger.d("signup param: " + paramData.toJSONString());
return PaasClient.getStorageClient().signUp(paramData).map(new Function<AVUser, AVUser>() {
@Override
public AVUser apply(AVUser avUser) throws E... | csn |
Generates and returns documentation for this API endpoint | def documentation(self, base_url=None, api_version=None, prefix=""):
"""Generates and returns documentation for this API endpoint"""
documentation = OrderedDict()
base_url = self.base_url if base_url is None else base_url
overview = self.api.doc
if overview:
documenta... | csn |
Delete a node from the root list.
@param n
the node | private void delete(RootListNode<K, V> n) {
RootListNode<K, V> nPrev = n.prev;
if (nPrev != null) {
nPrev.next = n.next;
} else {
rootList.head = n.next;
}
if (n.next != null) {
n.next.prev = nPrev;
} else {
rootList.tail ... | csn |
Displays a heading 5.
@param array $args The arguments.
@return string Returns the Bootstrap heading 5. | public function bootstrapHeading5Function(array $args = []) {
return $this->bootstrapHeading(5, ArrayHelper::get($args, "content"), ArrayHelper::get($args, "description"), ArrayHelper::get($args, "class"));
} | csn |
// SetBeforeFunc sets the BeforeFunc field for the previously registered "query". | func (db *DB) SetBeforeFunc(query string, f func()) {
db.mu.Lock()
defer db.mu.Unlock()
key := strings.ToLower(query)
r, ok := db.data[key]
if !ok {
db.t.Fatalf("BUG: no query registered for: %v", query)
}
r.BeforeFunc = f
} | csn |
func ListAppendOp(binName string, values ...interface{}) *Operation {
if len(values) == 1 {
return &Operation{opType: _CDT_MODIFY, binName: binName, binValue: ListValue{_CDT_LIST_APPEND, NewValue(values[0])}, encoder: listGenericOpEncoder}
}
return &Operation{opType: | _CDT_MODIFY, binName: binName, binValue: ListValue{_CDT_LIST_APPEND_ITEMS, ListValue(values)}, encoder: listGenericOpEncoder}
} | csn_ccr |
// Parse parses the contents of the supplied reader, writing generated code to
// the supplied writer. Uses filename as the source file for line comments, and
// pkg as the Go package name. | func Parse(w io.Writer, r io.Reader, filename, pkg string) error {
p := &parser{
s: newScanner(r, filename),
w: w,
packageName: pkg,
}
return p.parseTemplate()
} | csn |
how do i write a python dictionary to a csv file | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) | cosqa |
Returns the thrift compiler to use for the given target.
:param target: The target to extract the thrift compiler from.
:type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary`
:returns: The thrift compiler to use.
:rtype: string | def compiler(self, target):
"""Returns the thrift compiler to use for the given target.
:param target: The target to extract the thrift compiler from.
:type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary`
:returns: The thrift compiler to use.
:rtype: string
... | csn |
func ExponentialBuckets(start, factor float64, count int) []float64 {
if count < 1 {
panic("ExponentialBuckets needs a positive count")
}
if start <= 0 {
panic("ExponentialBuckets needs a positive start value")
}
if factor <= 1 {
panic("ExponentialBuckets needs a | factor greater than 1")
}
buckets := make([]float64, count)
for i := range buckets {
buckets[i] = start
start *= factor
}
return buckets
} | csn_ccr |
def register_finders():
"""Register finders necessary for PEX to function properly."""
# If the previous finder is set, then we've already monkeypatched, so skip.
global __PREVIOUS_FINDER
if __PREVIOUS_FINDER:
return
# save previous finder so that it can be restored
previous_finder = _get_finder(zipim... | assert previous_finder, 'This appears to be using an incompatible setuptools.'
# Enable finding zipped wheels.
pkg_resources.register_finder(
zipimport.zipimporter, ChainedFinder.of(pkg_resources.find_eggs_in_zip, find_wheels_in_zip))
# append the wheel finder
_add_finder(pkgutil.ImpImporter, find_whee... | csn_ccr |
Store model in session data so that it can be retrieved faster. | public function memorizeModel()
{
if (!$this->model->loaded()) {
throw $this->exception('Authentication failure', 'AccessDenied');
}
// Don't store password in model / memory / session
$this->model['password'] = null;
unset($this->model->dirty['password']);
... | csn |
// Mimics fmt.Println | func Println(a ...interface{}) (n int, err error) {
return fmt.Fprintln(Stdout, a...)
} | csn |
def replace_constraint(self,name,selectfrac_skip=False,distribution_skip=False):
"""
Re-apply constraint that had been removed
:param name:
Name of constraint to replace
:param selectfrac_skip,distribution_skip: (optional)
Same as :func:`StarPopulation.apply_con... | distribution_skip=distribution_skip)
del hidden_constraints[name]
else:
logging.warning('Constraint {} not available for replacement.'.format(name))
self.hidden_constraints = hidden_constraints | csn_ccr |
def ListAssets(logdir, plugin_name):
"""List all the assets that are available for given plugin in a logdir.
Args:
logdir: A directory that was created by a TensorFlow summary.FileWriter.
plugin_name: A string name of a plugin to list assets for.
Returns:
A string list of available plugin assets. If... | """
plugin_dir = PluginDirectory(logdir, plugin_name)
try:
# Strip trailing slashes, which listdir() includes for some filesystems.
return [x.rstrip('/') for x in tf.io.gfile.listdir(plugin_dir)]
except tf.errors.NotFoundError:
return [] | csn_ccr |
Save config data.
@param string $path
@param string $value
@param string $scope
@param int $scopeId
@return null | public function saveConfigData($path, $value, $scope, $scopeId)
{
$this->resourceConfig->saveConfig(
$path,
$value,
$scope,
$scopeId
);
} | csn |
func (k *InstalledKite) BinPath() string {
return filepath.Join(k.Domain, | k.User, k.Repo, k.Version, "bin", strings.TrimSuffix(k.Repo, ".kite"))
} | csn_ccr |
public final void clear () {
basicHeaderSegment.clear();
headerDigest.reset();
additionalHeaderSegments.clear();
| dataSegment.clear();
dataSegment.flip();
dataDigest.reset();
} | csn_ccr |
Determine leadership by querying the pacemaker Designated Controller | def is_crm_dc():
"""
Determine leadership by querying the pacemaker Designated Controller
"""
cmd = ['crm', 'status']
try:
status = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
if not isinstance(status, six.text_type):
status = six.text_type(status, "utf-8")
... | csn |
Sometime you want to emulate the action of "source" in bash,
settings some environment variables. Here is a way to do it. | def shell_source(script):
"""Sometime you want to emulate the action of "source" in bash,
settings some environment variables. Here is a way to do it."""
pipe = subprocess.Popen(
". %s; env" % script, stdout=subprocess.PIPE, shell=True)
output = pipe.communicate()[0].decode()
env = {}
fo... | csn |
def elements_as_text(self, elems, indent=2):
""" Returns the elems dictionary as formatted plain text. """
assert elems
text = ""
for elename, eledesc in elems.items():
if isinstance(eledesc, dict):
desc_txt = self.elements_as_text(eledesc, indent + 2)
... | assert False, "Only string or dictionary"
ele_txt = "\t{0}{1: <22} {2}".format(' ' * indent, elename,
desc_txt)
text = ''.join([text, ele_txt])
return text | csn_ccr |
public T object(Object object) throws IOException | {
text(stringifierFactory.toString(object));
return (T) this;
} | csn_ccr |
public boolean removeBusHalt(String name) {
Iterator<BusItineraryHalt> iterator = this.validHalts.iterator();
BusItineraryHalt bushalt;
int i = 0;
while (iterator.hasNext()) {
bushalt = iterator.next();
if (name.equals(bushalt.getName())) {
return removeBusHalt(i);
}
++i;
}
iterator = this.... | while (iterator.hasNext()) {
bushalt = iterator.next();
if (name.equals(bushalt.getName())) {
return removeBusHalt(i);
}
++i;
}
return false;
} | csn_ccr |
You will be given two numbers `m,n`. The numbers could span from `0` to `10000`. We can get their product by using binary reduction as show in the table below.
Example (to understand the table please read the description below it)
real value of m(r)
m
n
(r*n)
0
100
15
0
0
50
30
0
1
25
60
60
0
12
120
0
0... | def bin_mul(m,n):
if m < n: return bin_mul(n,m)
if n == 0: return []
res = []
while m > 0:
if m % 2 == 1: res.append(n)
m = m//2; n *=2
return res[::-1] | apps |
Set the legacy Content service object.
@param ContentLegacyService $service | public function setLegacyService(ContentLegacyService $service)
{
$this->legacy = $service;
$this->event()->addListener(StorageEvents::PRE_HYDRATE, [$this, 'hydrateLegacyHandler']);
} | csn |
Return product labels template
@return string | public function getProductLabels($product)
{
$html = '';
if ($this->isProductOnSale($product)) {
if ($this->isShowPercentage() && $this->getSalePercentage($product) > 0) {
$html .= '<span class="sale-label sale-value">'.$this->getSalePercentage($product).'%</span>';
... | csn |
Create message object for sending email
Parameters
----------
from_addr : string
An email address used for 'From' attribute
to_addr : string
An email address used for 'To' attribute
subject : string
An email subject string
body : string
An email body string
e... | def create_message(from_addr, to_addr, subject, body, encoding=None):
"""
Create message object for sending email
Parameters
----------
from_addr : string
An email address used for 'From' attribute
to_addr : string
An email address used for 'To' attribute
subject : string
... | csn |
public function handle(): void
{
$this->comment('Scanning form items..');
$filePaths = $this->helper->getConfigFilesSorted();
$formHolder = [];
foreach ($filePaths as $filePath) {
$file = json_decode(file_get_contents($filePath), true);
| if (isset($file['formData'])) {
$formHolder = array_merge($formHolder, $file['formData']);
}
}
cache()->forget('hc-forms');
cache()->put('hc-forms', $formHolder, now()->addMonth());
$this->info('registered forms: ' . count($formHolder));
$... | csn_ccr |
// MWSpanObserver returns a MWOption that observe the span
// for the server-side span. | func MWSpanObserver(f func(span opentracing.Span, r *http.Request)) MWOption {
return func(options *mwOptions) {
options.spanObserver = f
}
} | csn |
func (h Handle) Type() Type {
if len(h.Readers) == 1 &&
h.Readers[0].Equal(keybase1.PublicUID.AsUserOrTeam()) {
return Public
} else if | len(h.Writers) == 1 && h.Writers[0].IsTeamOrSubteam() {
return SingleTeam
}
return Private
} | csn_ccr |
// NewEndorsersCmd creates a new EndorsersCmd | func NewEndorsersCmd(stub Stub, parser ResponseParser) *EndorsersCmd {
return &EndorsersCmd{
stub: stub,
parser: parser,
}
} | csn |
func (fh FileHeaders) writeTo4(w io.Writer, buf *bytes.Buffer) error {
compressionFlags := make([]byte, 4)
binary.LittleEndian.PutUint32(compressionFlags, fh.CompressionFlags)
if err := writeTo4Header(w, 1, fh.Comment); err != nil {
return err
}
if err := writeTo4Header(w, 2, fh.CipherID); err != nil {
return... | 7, fh.EncryptionIV); err != nil {
return err
}
if err := writeTo4VariantDictionary(w, 11, fh.KdfParameters.RawData); err != nil {
return err
}
if err := writeTo4VariantDictionary(w, 12, fh.PublicCustomData); err != nil {
return err
}
// End of header
return writeTo4Header(w, 0, []byte{0x0D, 0x0A, 0x0D, 0x... | csn_ccr |
def request(self, request):
"""
Send a request to the Kafka broker.
:param bytes request:
The bytes of a Kafka `RequestMessage`_ structure. It must have
a unique (to this connection) correlation ID.
:returns:
`Deferred` which will:
- S... | a Kafka `ResponseMessage`_
- Fail when the connection terminates
.. _RequestMessage:: https://kafka.apache.org/protocol.html#protocol_messages
"""
if self._failed is not None:
return fail(self._failed)
correlation_id = request[4:8]
assert correlation_... | csn_ccr |
Captures scenario or example stats on their AFTER event.
@param Event $event | private function captureScenarioOrExampleStatsOnAfterEvent(Event $event)
{
if (!$event instanceof AfterScenarioTested) {
return;
}
$scenario = $event->getScenario();
$title = $scenario->getTitle();
$path = sprintf('%s:%d', $this->currentFeaturePath, $scenario->ge... | csn |
def _translate_timeperiod(self, timeperiod):
""" method translates given timeperiod to the grouped timeperiod """
if self.time_grouping == 1:
# no translation is performed for identity grouping
return timeperiod
# step 1: tokenize timeperiod into: (year, month, day, hour... | result = '{0}{1}{2}{3:02d}'.format(year, month, day, stem)
elif self.time_qualifier == QUALIFIER_DAILY:
stem = self._do_stem_grouping(timeperiod, int(day))
result = '{0}{1}{2:02d}{3}'.format(year, month, stem, hour)
else: # self.time_qualifier == QUALIFIER_MONTHLY:
... | csn_ccr |
Adds the argument variable as one of the output variable | def add_output_variable(self, var):
"""Adds the argument variable as one of the output variable"""
assert(isinstance(var, Variable))
self.output_variable_list.append(var) | csn |
Find the static part of a glob-path,
split path and return path part
@param {String} str Path/glob string
@returns {String} static path section of glob | function parent(str, { strict = false } = {}) {
str = path.normalize(str).replace(/\/|\\/, '/');
// special case for strings ending in enclosure containing path separator
if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/';
// preserves full path in case of trailing path separator
str += 'a';
do {str = pa... | csn |
Returns database SQL comment for a column. | def get_comment(self, table: str, column: str) -> str:
"""Returns database SQL comment for a column."""
return self.flavour.get_comment(self, table, column) | csn |
private void processElementClipping(GeneratorSingleCluster cluster, Node cur) {
double[] cmin = null, cmax = null;
String minstr = ((Element) cur).getAttribute(ATTR_MIN);
if(minstr != null && minstr.length() > 0) {
cmin = parseVector(minstr);
}
String maxstr = ((Element) cur).getAttribute(ATT... | XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild());
while(iter.hasNext()) {
Node child = iter.next();
if(child.getNodeType() == Node.ELEMENT_NODE) {
LOG.warning("Unknown element in XML specification file: " + child.getNodeName());
}
}
} | csn_ccr |
Nameless conversations will be lost. | def migrator(state):
"""Nameless conversations will be lost."""
cleverbot_kwargs, convos_kwargs = state
cb = Cleverbot(**cleverbot_kwargs)
for convo_kwargs in convos_kwargs:
cb.conversation(**convo_kwargs)
return cb | csn |
public Analysis<SolutionType> setNumRuns(String searchID, int n){
if(!searches.containsKey(searchID)){
throw new UnknownIDException("No search with ID " + searchID + " has been added.");
}
if(n <= 0){
| throw new IllegalArgumentException("Number of runs should be strictly positive.");
}
searchNumRuns.put(searchID, n);
return this;
} | csn_ccr |
def getNeighborProc(self, proc, offset, periodic=None):
"""
Get the neighbor to a processor
@param proc the reference processor rank
@param offset displacement, e.g. (1, 0) for north, (0, -1) for west,...
@param periodic boolean list of True/False values, True if axis is
... | for d in range(self.ndims)]
if periodic is not None and self.decomp is not None:
# apply modulo operation on periodic axes
for d in range(self.ndims):
if periodic[d]:
inds[d] = inds[d] % self.decomp[d]
if self.mit.areIndicesValid(... | csn_ccr |
// Get returns the Block in the underlying Cache with the specified base or a nil
// Block if it does not exist. It updates the gets and misses statistics. | func (s *StatsRecorder) Get(base int64) bgzf.Block {
s.mu.Lock()
s.stats.Gets++
blk := s.Cache.Get(base)
if blk == nil {
s.stats.Misses++
}
s.mu.Unlock()
return blk
} | csn |
Read a JSON file from ``fpath``; raise an exception if it doesn't exist.
:param fpath: path to file to read
:type fpath: str
:return: deserialized JSON
:rtype: dict | def read_json_file(fpath):
"""
Read a JSON file from ``fpath``; raise an exception if it doesn't exist.
:param fpath: path to file to read
:type fpath: str
:return: deserialized JSON
:rtype: dict
"""
if not os.path.exists(fpath):
raise Exception('ERROR: file %s does not exist.' ... | csn |
Iteratively merge documents together to create an hierarchy of clusters.
While hierarchical clustering only returns one element, it still wraps it
in an array to be consistent with the rest of the clustering methods.
@return array An array containing one element which is the resulting dendrogram | public function cluster(TrainingSet $documents, FeatureFactoryInterface $ff)
{
// what a complete waste of memory here ...
// the same data exists in $documents, $docs and
// the only useful parts are in $this->strategy
$docs = $this->getDocumentArray($documents, $ff);
$this-... | csn |
func NewCmdAttach(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
cmd := attach.NewCmdAttach(f, streams)
cmd.Long = | attachLong
cmd.Example = fmt.Sprintf(attachExample, fullName)
return cmd
} | csn_ccr |
Check if actid has already been seen, and if action cache is active, then provide cached result, if any. Return true in this case. | function inward_act_cache(ctxt, data) {
var so = ctxt.options
var meta = data.meta
var actid = meta.id
var private$ = ctxt.seneca.private$
if (actid != null && so.history.active) {
var actdetails = private$.history.get(actid)
if (actdetails) {
private$.stats.act.cache++
var latest = ac... | csn |
function executeAll (cfg) {
console.log(`${clr.DIM+clr.LIGHT_MAGENTA}Package: ${cfg.packageRoot}${clr.RESET}`);
return new Promise((resolve, reject) => {
createObservable(cfg).subscribe({
next ({command, exitCode}) {
if (exitCode == 0)
cfg.log(`${EMIT_COLO... | cfg.log(`just-build ${cfg.tasksToRun.join(' ')} failed. ${command} returned ${exitCode}`);
},
error (err) {
reject(err);
},
complete () {
resolve();
}
});
});
} | csn_ccr |
public function importTranslations($path, $type)
{
$separator = app('config')->get('antares/translations::export.separator');
$content = explode(PHP_EOL, file_get_contents($path));
$list = [];
foreach ($content as $index => $line) {
if ($index == 0) {
... | $insert = [];
foreach ($list as $item) {
if (!isset($item[2]) or ! isset($item[3])) {
continue;
}
try {
$value = iconv('WINDOWS-1250', 'UTF-8', $item[3]);
} catch (Exception... | csn_ccr |
function removeFromAttributeList(sAttribute, sValue) {
var sAttributes = this.attr(sAttribute) || "",
aAttributes = sAttributes.split(" "),
iIndex = aAttributes.indexOf(sValue);
if (iIndex == -1) {
return this;
}
| aAttributes.splice(iIndex, 1);
if (aAttributes.length) {
this.attr(sAttribute, aAttributes.join(" "));
} else {
this.removeAttr(sAttribute);
}
return this;
} | csn_ccr |
API to list all release versions in DBS
:param release_version: List only that release version
:type release_version: str
:param dataset: List release version of the specified dataset
:type dataset: str
:param logical_file_name: List release version of the logical file name
... | def listReleaseVersions(self, release_version='', dataset='', logical_file_name=''):
"""
API to list all release versions in DBS
:param release_version: List only that release version
:type release_version: str
:param dataset: List release version of the specified dataset
... | csn |
marshmallow python calling schema self for a nested field | def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:
"""
Iterate through marshmallow schema fields.
Generates: name, field pairs
"""
for name in sorted(schema.fields.keys()):
field = schema.fields[name]
yield field.dump_to or name, field | cosqa |
func NewOvsdbDriver(bridgeName string, failMode string, vxlanUDPPort int) (*OvsdbDriver, error) {
// Create a new driver instance
d := new(OvsdbDriver)
d.bridgeName = bridgeName
d.vxlanUDPPort = fmt.Sprintf("%d", vxlanUDPPort)
// Connect to OVS
ovs, err := libovsdb.ConnectUnix("")
if err != nil {
log.Fatalf("... | driver, only create the bridge
// if it's not already created
// XXX: revisit if the bridge-name needs to be configurable
brCreated := false
for _, row := range d.cache[bridgeTable] {
if row.Fields["name"] == bridgeName {
brCreated = true
break
}
}
if !brCreated {
err = d.createDeleteBridge(bridgeNa... | csn_ccr |
// You should always use this function to get a new DeleteInstanceGroupParams instance,
// as then you are sure you have configured all required params | func (s *VMGroupService) NewDeleteInstanceGroupParams(id string) *DeleteInstanceGroupParams {
p := &DeleteInstanceGroupParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
} | csn |
def equation_of_time_pvcdrom(dayofyear):
"""
Equation of time from PVCDROM.
`PVCDROM`_ is a website by Solar Power Lab at Arizona State
University (ASU)
.. _PVCDROM: http://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time
Parameters
----------
dayofyear : numeric
Retu... | mean solar time in minutes.
References
----------
[1] Soteris A. Kalogirou, "Solar Energy Engineering Processes and
Systems, 2nd Edition" Elselvier/Academic Press (2009).
See Also
--------
equation_of_time_Spencer71
"""
# day angle relative to Vernal Equinox, typically March 22 (d... | csn_ccr |
// ServoWrite writes the 0-180 degree angle to the specified pin.
// To use it requires installing the "tinker-servo" sketch on your
// Particle device. not just the default "tinker". | func (s *Adaptor) ServoWrite(pin string, angle byte) (err error) {
if _, present := s.servoPins[pin]; !present {
err = s.servoPinOpen(pin)
if err != nil {
return
}
}
params := url.Values{
"params": {fmt.Sprintf("%v,%v", pin, angle)},
"access_token": {s.AccessToken},
}
url := fmt.Sprintf("%v/ser... | csn |
Generates a random nonce which is guaranteed to be unique even if the process's PRNG is
exhausted or compromised.
<p>Internally, this creates a Blake2b instance with the given key, a random 16-byte salt, and a
random 16-byte personalization tag. It then hashes the message and returns the resulting
24-byte digest as th... | public byte[] nonce(byte[] message) {
final byte[] n1 = new byte[16];
final byte[] n2 = new byte[16];
final SecureRandom random = new SecureRandom();
random.nextBytes(n1);
random.nextBytes(n2);
final Blake2bDigest blake2b = new Blake2bDigest(key, NONCE_SIZE, n1, n2);
blake2b.update(message,... | csn |
Returns hydrator required by metadata
@param Metadata $metadata
@return Hydrator | public function getHydrator(Metadata $metadata)
{
if (!isset($this->hydrators[$metadata->className][$metadata->subset]))
{
$hydrator = new Hydrator();
$hydrator
->setStrategyPluginManager($this->strategyPluginManager)
->setMetadata($metadata)
;
$this->hydrators[$metadata->className][$metadata->... | csn |
Get a shortcode callback.
@param string $tag
@return mixed | public function getShortcodeCallback($tag)
{
return isset($this->shortcodes[$tag]) ? $this->shortcodes[$tag] : null;
} | csn |
// NewCacheWithExpiration creates a new data cache | func NewCacheWithExpiration(name string, lifetime time.Duration) *Cache {
return NewCacheWithExpirationNotifier(name, lifetime, nil)
} | csn |
def delete_entry(self, key):
"""Delete an object from the redis table"""
| pipe = self.client.pipeline()
pipe.srem(self.keys_container, key)
pipe.delete(key)
pipe.execute() | csn_ccr |
// Tasks returns a channel on which all tasks are received. | func (s *globalTaskService) Tasks() <-chan *types.Task {
tasks := []*types.Task{}
s.RLock()
for _, v := range s.tasks {
tasks = append(tasks, &v.Task)
}
s.RUnlock()
c := make(chan *types.Task)
go func() {
for _, t := range tasks {
c <- t
}
close(c)
}()
return c
} | csn |
Convert signed hexadecimal to floating value. | def signed_to_float(hex: str) -> float:
"""Convert signed hexadecimal to floating value."""
if int(hex, 16) & 0x8000:
return -(int(hex, 16) & 0x7FFF) / 10
else:
return int(hex, 16) / 10 | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.