query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
python inner join data frames | def _join(verb):
"""
Join helper
"""
data = pd.merge(verb.x, verb.y, **verb.kwargs)
# Preserve x groups
if isinstance(verb.x, GroupedDataFrame):
data.plydata_groups = list(verb.x.plydata_groups)
return data | cosqa |
Clean the search cache based on the index
@param string|StorageMeta|null $meta | protected function clean( $meta = null ) {
//
if( $meta && !( $meta instanceof StorageMeta ) ) {
$meta = $this->getMeta( $meta );
}
// clear the cache
if( !$meta || empty( $meta->token ) ) $this->cache = [];
else foreach( $this->cache as $i => $_ ) {
if( empty( $i ) || $i == $meta... | csn |
public function hasValues()
{
$keys = array_values($this->data[0]);
foreach ($this->data[1] as $key) {
| $this->failIf((!in_array($key, $keys)));
}
} | csn_ccr |
// ClearAll clears the entire cache. To be used when some event results in unknown invalidations.
// Returns self for method chaining. | func (l *Loader) ClearAll() Interface {
l.cacheLock.Lock()
l.cache.Clear()
l.cacheLock.Unlock()
return l
} | csn |
public static function isDate($object)
{
return $object | instanceof \DateTime || (static::isString($object) && strtotime((string)$object) !== false);
} | csn_ccr |
public function comments()
{
if (is_null($this->commentRequests)) {
$this->commentRequests | = new CommentRequests($this->client);
}
return $this->commentRequests;
} | csn_ccr |
private Number getIdColumnData(ResultSet resultSet, ResultSetMetaData metaData, int columnIndex)
throws SQLException {
int typeVal = metaData.getColumnType(columnIndex);
switch (typeVal) {
case Types.BIGINT:
case Types.DECIMAL:
case Types.NUMERIC:
return (Number) resultSet.getLong(columnIndex); |
case Types.INTEGER:
return (Number) resultSet.getInt(columnIndex);
default:
String columnName = metaData.getColumnName(columnIndex);
throw new SQLException(
"Unexpected ID column type " + TypeValMapper.getSqlTypeForTypeVal(typeVal) + " (typeVal "
+ typeVal + ") in column " + columnName ... | csn_ccr |
Set the signer page primary button color.
@param color String hex color code
@throws HelloSignException thrown if the color string is an invalid hex
string | public void setPrimaryButtonColor(String color) throws HelloSignException {
if (white_labeling_options == null) {
white_labeling_options = new WhiteLabelingOptions();
}
white_labeling_options.setPrimaryButtonColor(color);
} | csn |
Validate if the values are validated one by one in order. | def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.sch... | csn |
A proper way to finish execution of AJAX response. Generates JSON
which is returned to frontend.
@param array|jsExpressionable $ajaxec Array of jsExpressionable
@param string $msg General message, typically won't be displayed
@param bool $success Was request successful or not
@r... | public function terminate($ajaxec, $msg = null, $success = true)
{
$this->app->terminate(json_encode(['success' => $success, 'message' => $msg, 'atkjs' => $ajaxec]));
} | csn |
def granulate(options = {})
@request_data = Hash.new
if options[:doc_link]
insert_download_data options
else
file_data = {:doc => options[:file], :filename => options[:filename]}
@request_data.merge! file_data
| end
insert_callback_data options
request = prepare_request :POST, @request_data.to_json
execute_request(request)
end | csn_ccr |
Finds out if a container with name ``container_name`` is running.
:return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise.
:rtype: Optional[docker.models.container.Container] | def container_running(self, container_name):
"""
Finds out if a container with name ``container_name`` is running.
:return: :class:`Container <docker.models.containers.Container>` if it's running, ``None`` otherwise.
:rtype: Optional[docker.models.container.Container]
"""
... | csn |
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
// Should return a error 400 bad request
if ($exception instanceof ValidationException
|| $exception instanceof SyntaxErrorException) {
return;
}
... | return;
}
$data = $this->decorateKnownCases($exception);
if (!is_array($data)) {
$data = [
'code' => $exception->getCode(),
'exceptionClass' => get_class($exception),
'message' => $exception->getMessage()
];
... | csn_ccr |
public function listAction()
{
$calendars = $this->getDoctrine()
->getRepository('CanalTPMttBundle:Calendar')
->findBy(
['customer' => $this->getUser()->getCustomer()],
['id'=>'desc']
);
| return $this->render('CanalTPMttBundle:Calendar:list.html.twig', [
'no_left_menu' => true,
'calendars' => $calendars
]);
} | csn_ccr |
public synchronized void markClean(UUID cfId, ReplayPosition context)
{
if (!cfDirty.containsKey(cfId))
return;
if (context.segment == id)
| markClean(cfId, context.position);
else if (context.segment > id)
markClean(cfId, Integer.MAX_VALUE);
} | csn_ccr |
Command the PCAN driver to reset the bus after an error. | def reset(self):
"""
Command the PCAN driver to reset the bus after an error.
"""
status = self.m_objPCANBasic.Reset(self.m_PcanHandle)
return status == PCAN_ERROR_OK | csn |
def _parse_header_code(self):
"""Extract header information and PDB code."""
code, header = '', ''
if 'OTHERS' in self.df:
header = (self.df['OTHERS'][self.df['OTHERS']['record_name'] ==
'HEADER'])
| if not header.empty:
header = header['entry'].values[0]
s = header.split()
if s:
code = s[-1].lower()
return header, code | csn_ccr |
def find_dongle_port():
"""Convenience method which attempts to find the port where a BLED112 dongle is connected.
This relies on the `pyserial.tools.list_ports.grep method
<https://pyserial.readthedocs.io/en/latest/tools.html#serial.tools.list_ports.grep>`_,
and simply searches for a... | probably only work on Windows at the moment
ports = list(serial.tools.list_ports.grep('Bluegiga'))
if len(ports) == 0:
logger.debug('No Bluegiga-named serial ports discovered')
return None
# just return the first port even if multiple dongles
logger.debug('Found... | csn_ccr |
// WithMetrics is a decorator for admission handlers with a generic observer func. | func WithMetrics(i admission.Interface, observer ObserverFunc, extraLabels ...string) admission.Interface {
return &pluginHandlerWithMetrics{
Interface: i,
observer: observer,
extraLabels: extraLabels,
}
} | csn |
private String getArchiveFilePath() {
if ( archiveFileLock == null ) {
return archiveFilePath;
} else {
synchronized( archiveFileLock ) {
@SuppressWarnings("unused")
| File useArchiveFile = getArchiveFile();
return archiveFilePath;
}
}
} | csn_ccr |
// Update updates the global sql bind cache. | func (h *BindHandle) Update(fullLoad bool) (err error) {
sql := "select original_sql, bind_sql, default_db, status, create_time, update_time, charset, collation from mysql.bind_info"
if !fullLoad {
sql += " where update_time >= \"" + h.lastUpdateTime.String() + "\""
}
// No need to acquire the session context lo... | csn |
Finds option by long name
@param argument long name
@return found option or null if none found | public CommandOption findLong(String argument) {
Assert.notNullOrEmptyTrimmed(argument, "Missing long name!");
Optional<CommandOption> found = options.stream().filter(o -> o.isLong(argument)).findFirst();
return found.orElse(null);
} | csn |
WizardDialog getWizardDialog() {
final WeakReference<WizardDialog> ref = this.wizardDialog;
| return (ref == null) ? null : ref.get();
} | csn_ccr |
Filter the query on the step column
Example usage:
<code>
$query->filterByStep(1234); // WHERE step = 1234
$query->filterByStep(array(12, 34)); // WHERE step IN (12, 34)
$query->filterByStep(array('min' => 12)); // WHERE step > 12
</code>
@param mixed $step The value to use as filter.
Use scalar values for equali... | public function filterByStep($step = null, $comparison = null)
{
if (is_array($step)) {
$useMinMax = false;
if (isset($step['min'])) {
$this->addUsingAlias(FeatureTypeTableMap::STEP, $step['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
... | csn |
public final void annotate(final InputStream inputStream,
final OutputStream outputStream) throws IOException, JDOMException {
BufferedReader breader = new BufferedReader(
new InputStreamReader(inputStream, UTF_8));
BufferedWriter bwriter = new BufferedWriter(
new OutputStreamWriter(outpu... | null;
if (parsedArguments.getString("language") != null) {
lang = parsedArguments.getString("language");
if (!kaf.getLang().equalsIgnoreCase(lang)) {
System.err.println("Language parameter in NAF and CLI do not match!!");
}
} else {
lang = kaf.getLang();
}
Properties pro... | csn_ccr |
python read file and conver to string | def file_to_str(fname):
"""
Read a file into a string
PRE: fname is a small file (to avoid hogging memory and its discontents)
"""
data = None
# rU = read with Universal line terminator
with open(fname, 'rU') as fd:
data = fd.read()
return data | cosqa |
public function setFactory(\Elcodi\Component\Core\Factory\Abstracts\AbstractFactory $factory)
{
| $this->factory = $factory;
return $this;
} | csn_ccr |
Returns the relevant pattern for the given number.
@param string $value
@param string $translationId
@return string | protected function getPattern($value, $translationId)
{
$language = $this->translator->getCurrentLanguage();
if (!isset($this->patterns[$language][$translationId])) {
$this->patterns[$language][$translationId] = $this->parsePattern($this->translator->translate($translationId));
... | csn |
function(stats, callback) {
fs.readFile(file, function(err, data) {
| callback(err, data, stats);
});
} | csn_ccr |
def save_state_recursively(state, base_path, parent_path, as_copy=False):
"""Recursively saves a state to a json file
It calls this method on all its substates.
:param state: State to be stored
:param base_path: Path to the state machine
:param parent_path: Path to the parent state
:param bool... | get_storage_id_for_state(state))
state_path_full = os.path.join(base_path, state_path)
if not os.path.exists(state_path_full):
os.makedirs(state_path_full)
storage_utils.write_dict_to_json(state, os.path.join(state_path_full, FILE_NAME_CORE_DATA))
if not as_copy:
state.file_system_path... | csn_ccr |
Serves index.html as the last resort.
@param {Object} req - request object
@param {Object} res - response object
@param {Function} next - called on handler miss
@param {boolean} local - local mode | function IndexHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
if (!parsedUrl.pathname.startsWith(self.localFilesystemUrl) &&
parsedUrl.pathname !== '/favicon.ico'
) {
/** @type {Asset} */
const indexFile =... | csn |
python levenshtein distance algorithm | def levenshtein_distance_metric(a, b):
""" 1 - farthest apart (same number of words, all diff). 0 - same"""
return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1))) | cosqa |
public static function save( $fileName, $channelData, $itemList, $encoding = "utf-8" )
{
$builder = new XML_RSS_Builder();
$builder->setChannelData( $channelData );
$builder->setItemList( $itemList | );
$xml = $builder->build( $encoding = "utf-8" );
return FS_File_Writer::save( $fileName, $xml );
} | csn_ccr |
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level X such that the sum of all the values of nodes at level X is maximal.
Example 1:
Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Lev... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
stack = [root]
ans = -1000000
result =... | apps |
def get_collection(self, event_collection):
"""
Extracts info about a collection using the Keen IO API. A master key must be set first.
:param event_collection: the name of the collection to retrieve info for
"""
url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url, sel... | self.project_id, event_collection)
headers = utilities.headers(self.read_key)
response = self.fulfill(HTTPMethods.GET, url, headers=headers, timeout=self.get_timeout)
self._error_handling(response)
return response.json() | csn_ccr |
Checks the validity of the asserted password against a ManagedUsers actual hashed password.
@param assertedPassword the clear text password to check
@param user The ManagedUser to check the password of
@return true if assertedPassword matches the expected password of the ManangedUser, false if not
@since 1.0.0 | public static boolean matches(final char[] assertedPassword, final ManagedUser user) {
final char[] prehash = createSha512Hash(assertedPassword);
// Todo: remove String when Jbcrypt supports char[]
return BCrypt.checkpw(new String(prehash), user.getPassword());
} | csn |
private function setupWorkspace()
{
// search spec configuration file.
$config_file_name = $this->runner->getConfigurationFileName();
$dirs = explode(DS, getcwd());
$find = false;
do {
$workspace = join(DS, $dirs);
$config_file_path = $workspace . DS .... | && is_file($config_file_path)) {
$find = true;
break;
}
} while (array_pop($dirs));
if (!$find) $workspace = getcwd();
$this->runner->setWorkspace($workspace);
} | csn_ccr |
public function run()
{
if (is_object($this->connection())) {
try {
$stmt = $this->connection()->prepare($this->schema);
if ($this->checkSchemaExistence) {
return $stmt->rowCount();
} elseif ($return = $stmt->execute()) {
... | } else {
return false;
}
} catch (\PDOException $e) {
throw new \Exception($e->getMessage());
}
}
} | csn_ccr |
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any... | import sys
input = sys.stdin.readline
n,m=list(map(int,input().split()))
ANS=[]
for i in range(1,n//2+1):
for j in range(1,m+1):
sys.stdout.write("".join((str(i)," ",str(j),"\n")))
sys.stdout.write("".join((str(n-i+1)," ",str(m-j+1),"\n")))
if n%2==1:
for j in range(1,m//2+1):
sys.s... | apps |
function (identifier, clientX, clientY) {
/**
* A number uniquely identifying this touch point.
* @type {Number}
* @readonly
*/
this.identifier = identifier;
// Intentionally not documented.
this._clientX = clientX;
... | // Intentionally not documented.
this._clientStartX = clientX;
// Intentionally not documented.
this._clientStartY = clientY;
} | csn_ccr |
%matplotlib inline
import tensorflow as tf
from d2l import tensorflow as d2l
d2l.use_svg_display()
mnist_train, mnist_test = tf.keras.datasets.fashion_mnist.load_data()
len(mnist_train[0]), len(mnist_test[0])
def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5):
figsize = (num_cols * scale, num_rows * ... | %matplotlib inline
import sys
from mxnet import gluon
from d2l import mxnet as d2l
d2l.use_svg_display()
mnist_train = gluon.data.vision.FashionMNIST(train=True)
mnist_test = gluon.data.vision.FashionMNIST(train=False)
len(mnist_train), len(mnist_test)
def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5):
... | codetrans_dl |
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubBook. | def read_epub(name, options=None):
"""
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubB... | csn |
def second_order_score(y, mean, scale, shape, skewness):
""" GAS Laplace Update term potentially using second-order information - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the... |
skewness parameter for the Laplace distribution
Returns
----------
- Adjusted score of the Laplace family
"""
return ((y-mean)/float(scale*np.abs(y-mean))) / (-(np.power(y-mean,2) - np.power(np.abs(mean-y),2))/(scale*np.power(np.abs(mean-y),3))) | csn_ccr |
@SneakyThrows
public static Set<Event> resolveEventViaSingleAttribute(final Principal principal,
final Object attributeValue,
final RegisteredService service,
... | LOGGER.debug("Attribute value [{}] is a single-valued attribute", attributeValue);
if (predicate.test(attributeValue.toString())) {
LOGGER.debug("Attribute value predicate [{}] has matched the [{}]", predicate, attributeValue);
return evaluateEventForProviderInContext(princ... | csn_ccr |
def get_width(self):
"""
Returns the Widget target width.
:return: Widget target width.
:rtype: int
"""
return self.__margin + \
| self.__editor.fontMetrics().width(foundations.strings.to_string(max(1, self.__editor.blockCount()))) | csn_ccr |
Loads a chunk of text.
@param offset The offset into the character buffer to
read the next batch of characters.
@param changeEntity True if the load should change entities
at the end of the entity, otherwise leave
the current entity in place and the entity
boundary will be signaled by the return
value.
@returns... | final boolean load(int offset, boolean changeEntity)
throws IOException {
// read characters
int length = fCurrentEntity.mayReadChunks?
(fCurrentEntity.ch.length - offset):
(DEFAULT_XMLDECL_BUFFER_SIZE);
int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset,
length);
// reset cou... | csn |
Initialize .po file from template
@param string $template
@param string $languages
@return array
@throws ResourceNotFoundException | protected function initializeFromTemplate($template, $languages)
{
$results = array();
$target = dirname($template);
if (!file_exists($template)) {
throw new ResourceNotFoundException("Template not found in: $template\n\nRun 'app/console gettext:bundle:extract' first.");
... | csn |
func TailTables(g Grouping, n int) Grouping {
return | headTailTables(g, n, true)
} | csn_ccr |
func (asl *AuthServerLdap) getGroups(username string) ([]string, error) {
err := asl.Client.Bind(asl.User, asl.Password)
if err != nil {
return nil, err
}
req := ldap.NewSearchRequest(
asl.GroupQuery,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(memberUid=%s)", username),
[]s... | := asl.Client.Search(req)
if err != nil {
return nil, err
}
var groups []string
for _, entry := range res.Entries {
for _, attr := range entry.Attributes {
groups = append(groups, attr.Values[0])
}
}
return groups, nil
} | csn_ccr |
function (guestInstanceId, contents) {
const guest = getGuest(guestInstanceId)
if (!guest) {
throw new Error(`Invalid guestInstanceId: | ${guestInstanceId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error(`Access denied to guestInstanceId: ${guestInstanceId}`)
}
return guest
} | csn_ccr |
Set a not found response. | protected function notFound()
{
// Set the default not found response
$this->response->setContent('File not found');
$this->response->headers->set('content-type', 'text/html');
$this->response->setStatusCode(Response::HTTP_NOT_FOUND);
// Execute the user defined notFound cal... | csn |
public TimeDuration plus(TimeDuration duration) {
return createWithCarry(sec + | duration.getSec(), nanoSec + duration.getNanoSec());
} | csn_ccr |
public static String getResultSetCloseString(int value) {
switch (value) {
case Statement.CLOSE_ALL_RESULTS:
return "CLOSE ALL RESULTS (" + value + ')';
case Statement.CLOSE_CURRENT_RESULT:
return "CLOSE CURRENT RESULT (" + value + ')';
| case Statement.KEEP_CURRENT_RESULT:
return "KEEP CURRENT RESULT (" + value + ')';
}
return "UNKNOWN CLOSE RESULTSET CONSTANT (" + value + ')';
} | csn_ccr |
def _format_function_contracts(func: Callable, prefix: Optional[str] = None) -> List[str]:
"""
Format the preconditions and postconditions of a function given its checker decorator.
:param func: function whose contracts we are describing
:param prefix: prefix to be prepended to the contract directives ... | return []
pps = _preconditions_snapshots_postconditions(checker=checker)
pre_block = _format_preconditions(preconditions=pps.preconditions, prefix=prefix)
old_block = _format_snapshots(snapshots=pps.snapshots, prefix=prefix)
post_block = _format_postconditions(postconditions=pps.postconditions, pref... | csn_ccr |
def next(self, day_of_week=None, keep_time=False):
"""
Modify to the next occurrence of a given day of the week.
If no day_of_week is provided, modify to the next occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime... | is None:
day_of_week = self.day_of_week
if day_of_week < SUNDAY or day_of_week > SATURDAY:
raise ValueError("Invalid day of week")
if keep_time:
dt = self
else:
dt = self.start_of("day")
dt = dt.add(days=1)
while dt.day_of_week ... | csn_ccr |
Helper method to wait for an element with the specified class.
@param $class
@param int $timeout
@throws CannotFindElement
@return $this | protected function waitForElementsWithClass($class, $timeout = 2000)
{
try {
$this->waitForElement('ClassName', $class, $timeout);
} catch (\Exception $e) {
throw new CannotFindElement("Can't find an element with the class name of "
.$class.' within the time p... | csn |
if there are xml configure then add new ones; if not, register it;
@param configList
Collection the configure collection for jdonframework.xml | public void registerAppRoot(String configureFileName) throws Exception {
try {
AppConfigureCollection existedAppConfigureFiles = (AppConfigureCollection) containerWrapper.lookup(AppConfigureCollection.NAME);
if (existedAppConfigureFiles == null) {
xmlcontainerRegistry.registerAppRoot();
existedAppC... | csn |
def writefits(self, filename, clobber=True, trimzero=True,
binned=False, precision=None, hkeys=None):
"""Write the spectrum to a FITS table.
Primary header in EXT 0. ``FILENAME``, ``ORIGIN``, and any
extra keyword(s) from ``hkeys`` will also be added.
Table header an... | last = min(nz[-1] + 2, last)
except IndexError:
pass
# Construct the columns and HDUlist
cw = pyfits.Column(name='WAVELENGTH',
array=wave[first:last],
unit=self.waveunits.name,
forma... | csn_ccr |
// GetDashboardUrl return the html url for a dashboard | func GetDashboardUrl(uid string, slug string) string {
return fmt.Sprintf("%s/d/%s/%s", setting.AppSubUrl, uid, slug)
} | csn |
Returns the Information of a ParsedPage which are selected by the actual configuration | public String getSelectedText( ParsedPage pp ){
if( pp == null ) return null;
StringBuilder sb = new StringBuilder();
levelModifier = pp.getSection(0).getLevel()-1;
if( pageHandling == null ){
if( firstParagraphHandling != null ){
handleContent( pp.getFirstParagraph(), firstParagraphHandling... | csn |
A specialized version of `_.reduceRight` for arrays without support for
iteratee shorthands.
@private
@param {Array} array The array to iterate over.
@param {Function} iteratee The function invoked per iteration.
@param {*} [accumulator] The initial value.
@param {boolean} [initAccum] Specify using the last element of... | function arrayReduceRight(array, iteratee, accumulator, initAccum) {
var length = array.length;
if (initAccum && length) {
accumulator = array[--length];
}
while (length--) {
accumulator = iteratee(accumulator, array[length], length, array);
}
return accumulator;
... | csn |
Returns the property names of the given enum items contained in this
vocabulary.
@param properties
a collection of properties to get the name of, must not be
<code>null</code>
@return the collection of the names of properties in <code>properties</code>. | public Collection<String> getNames(Collection<P> properties)
{
Preconditions.checkNotNull(properties);
return Collections2.transform(properties, new Function<P, String>()
{
@Override
public String apply(P property)
{
return converter.convert(property);
}
});
} | csn |
def get_mesh(self, body_name, **kwargs):
"""Builds Mesh from geom name in the wavefront file. Takes all keyword arguments that Mesh takes."""
body = self.bodies[body_name]
vertices = body['v']
normals = body['vn'] if 'vn' in body else None
texcoords = body['vt'] if 'vt' in body ... | else:
setattr(mesh, key, value)
elif hasattr(value, '__len__'): # iterable materials
mesh.uniforms[key] = value
elif key in ['d', 'illum']: # integer materials
mesh.uniforms[key] = value
... | csn_ccr |
// SetIssuer updates the stored Issuer cert
// and the internal x509 Issuer Name of a certificate.
// The stored Issuer reference is used when adding extensions. | func (c *Certificate) SetIssuer(issuer *Certificate) error {
name, err := issuer.GetSubjectName()
if err != nil {
return err
}
if err = c.SetIssuerName(name); err != nil {
return err
}
c.Issuer = issuer
return nil
} | csn |
// ReallocResource realloc res for containers | func (v *Vibranium) ReallocResource(opts *pb.ReallocOptions, stream pb.CoreRPC_ReallocResourceServer) error {
v.taskAdd("ReallocResource", true)
defer v.taskDone("ReallocResource", true)
ids := opts.GetIds()
if len(ids) == 0 {
return types.ErrNoContainerIDs
}
//这里不能让 client 打断 remove
ch, err := v.cluster.Real... | csn |
Generate a random number in a range.
@param min
@param max
@return the random value in the min/max range | public static double random(double min, double max) {
assert max > min;
return min + Math.random() * (max - min);
} | csn |
Intermediate fetch function
@param string $method The HTTP method
@param string $url The API endpoint
@param string $call The API method to call
@param array $params Additional parameters
@return mixed | private function fetch($method, $url, $call, array $params = array())
{
// Make the API call via the consumer
$response = $this->OAuth->fetch($method, $url, $call, $params);
// Format the response and return
switch ($this->responseFormat) {
case 'json':
... | csn |
func (e *Error) Error() string {
ret, _ := | json.Marshal(e)
return string(ret)
} | csn_ccr |
Tries to guess the mime type.
@param string $guess The path to the file or the file extension
@throws \Narrowspark\MimeType\Exception\FileNotFoundException If the file does not exist
@throws \Narrowspark\MimeType\Exception\AccessDeniedException If the file could not be read
@return null|string The guessed extension ... | public static function guess(string $guess): ?string
{
$guessers = self::getGuessers();
if (\count($guessers) === 0) {
$msg = 'Unable to guess the mime type as no guessers are available';
if (! MimeTypeFileInfoGuesser::isSupported()) {
$msg .= ' (Did you ena... | csn |
def getJournalDeals(self, start=None):
"""Return all journal events from start."""
# 1 - utworzenie aktu zakupowego (deala), 2 - utworzenie formularza pozakupowego (karta platnosci), 3 - anulowanie formularza pozakupowego (karta platnosci), 4 - zakończenie (opłacenie) transakcji przez PzA
if sta... | for i in rc:
events.append({
'allegro_did': i['dealId'],
'deal_status': i['dealEventType'],
'transaction_id': i['dealTransactionId'],
'time': i['dealEventTime'],
'event_id': i['dealEventId'],
... | csn_ccr |
Checks property on existence and several options
@param {string} property Property name
@param {object} options Checking options (writable, readable, method, params)
@param {boolean} throwError if true throws errors, if false return result of check
@returns {boolean} Check result
@this {clazz|object} | function(property, options, throwError) {
throwError = !_.isUndefined(throwError) ? throwError : true;
var that = this;
try {
if (!this.__hasProperty(property)) {
throw 'Property "' + property + '" does not exists!';
}
... | csn |
def parse_value(self):
"""
Turn the value of an incoming dataset into a hydra-friendly value.
"""
try:
if self.value is None:
log.warning("Cannot parse dataset. No value specified.")
return None
# attr_data.value is a dictionar... | log.info("[Dataset.parse_value] Parsing %s (%s)", data, type(data))
return HydraObjectFactory.valueFromDataset(self.type, self.value, self.get_metadata_as_dict())
except Exception as e:
log.exception(e)
raise HydraError("Error parsing value %s: %s"%(self.value, e... | csn_ccr |
func findField(curr value, minSuperDepth int, f string) (bool, simpleObjectField, bindingFrame, int) {
switch curr := curr.(type) {
case *valueExtendedObject:
if curr.right.inheritanceSize() > minSuperDepth {
found, field, frame, counter := findField(curr.right, minSuperDepth, f)
if found {
return true, f... | frame, counter
}
}
found, field, frame, counter := findField(curr.left, minSuperDepth-curr.right.inheritanceSize(), f)
return found, field, frame, counter + curr.right.inheritanceSize()
case *valueSimpleObject:
if minSuperDepth <= 0 {
if field, ok := curr.fields[f]; ok {
return true, field, curr.up... | csn_ccr |
func extractBtcdRPCParams(btcdConfigPath string) (string, string, error) {
// First, we'll open up the btcd configuration file found at the target
// destination.
btcdConfigFile, err := os.Open(btcdConfigPath)
if err != nil {
return "", "", err
}
defer btcdConfigFile.Close()
// With the file open extract the ... | set
// rpcpass (if any). If we can't find the pass, then we'll exit with an
// error.
rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpass\s*=\s*([^\s]+)`)
if err != nil {
return "", "", err
}
passSubmatches := rpcPassRegexp.FindSubmatch(configContents)
if passSubmatches == nil {
return "", "", fmt.Errorf(... | csn_ccr |
// Less reports whether the element with
// index i should sort before the element with index j in the Uint8Slice. | func (s Uint8Slice) Less(i, j int) bool {
return s[i] < s[j]
} | csn |
Uploads a file for immediate indexing.
**Note**: The file must be locally accessible from the server.
:param filename: The name of the file to upload. The file can be a
plain, compressed, or archived file.
:type filename: ``string``
:param kwargs: Additional arguments (opti... | def upload(self, filename, **kwargs):
"""Uploads a file for immediate indexing.
**Note**: The file must be locally accessible from the server.
:param filename: The name of the file to upload. The file can be a
plain, compressed, or archived file.
:type filename: ``string``
... | csn |
// runAll executes all the canned benchmarks and prints out the stats. | func runAll(ctx context.Context, st storage.Store, chanSize, bulkSize int) int {
// - Add non existing triples. (done)
// - Add triples that already exist. (done)
// - Remove non existing triples. (done)
// - Remove existing triples. (done)
// - BQL tree walking from root. (done)... | csn |
def get_authn_contexts(self):
"""
Gets the authentication contexts
:returns: The authentication classes for the SAML Response
:rtype: list
"""
| authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef')
return [OneLogin_Saml2_XML.element_text(node) for node in authn_context_nodes] | csn_ccr |
r"""
Convert a CSV file without header into a numpy array of floats.
>>> from openquake.baselib.general import gettemp
>>> print(read_array(gettemp('.1 .2, .3 .4, .5 .6\n')))
[[[0.1 0.2]
[0.3 0.4]
[0.5 0.6]]] | def read_array(fname, sep=','):
r"""
Convert a CSV file without header into a numpy array of floats.
>>> from openquake.baselib.general import gettemp
>>> print(read_array(gettemp('.1 .2, .3 .4, .5 .6\n')))
[[[0.1 0.2]
[0.3 0.4]
[0.5 0.6]]]
"""
with open(fname) as f:
rec... | csn |
private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFromCurrentSection = 0): string
{
$numberOfLinesToClear = $numberOfLinesToClearFromCurrentSection;
$erasedContent = [];
foreach ($this->sections as $section) {
if ($section === $this) {
... | > 0) {
// move cursor up n lines
parent::doWrite(sprintf("\x1b[%dA", $numberOfLinesToClear), false);
// erase to end of screen
parent::doWrite("\x1b[0J", false);
}
return implode('', array_reverse($erasedContent));
} | csn_ccr |
// For more details on the polymod calculation, please refer to BIP 173. | func bech32Polymod(values []int) int {
chk := 1
for _, v := range values {
b := chk >> 25
chk = (chk&0x1ffffff)<<5 ^ v
for i := 0; i < 5; i++ {
if (b>>uint(i))&1 == 1 {
chk ^= gen[i]
}
}
}
return chk
} | csn |
Run the job that execute a fixed import of a Maven project.
@param addSarlSpecificSourceFolders indicates if the source folders that are specific to SARL should be added.
@param projectInfos the list of descriptions for each project to import.
@param importConfiguration the import configuration.
@param projectCreation... | static List<IMavenProjectImportResult> runFixedImportJob(boolean addSarlSpecificSourceFolders,
Collection<MavenProjectInfo> projectInfos,
ProjectImportConfiguration importConfiguration, IProjectCreationListener projectCreationListener,
IProgressMonitor monitor) throws CoreException {
final List<IMavenProject... | csn |
func (s3) CreateMetadata(metadata map[string]string, keyID string, kmsKey []byte, sealedKey SealedKey) map[string]string {
if sealedKey.Algorithm != SealAlgorithm {
logger.CriticalIf(context.Background(), fmt.Errorf("The seal algorithm '%s' is invalid for SSE-S3", sealedKey.Algorithm))
}
if metadata == nil {
me... | metadata[S3KMSKeyID] = keyID
metadata[SSESealAlgorithm] = sealedKey.Algorithm
metadata[SSEIV] = base64.StdEncoding.EncodeToString(sealedKey.IV[:])
metadata[S3SealedKey] = base64.StdEncoding.EncodeToString(sealedKey.Key[:])
metadata[S3KMSSealedKey] = base64.StdEncoding.EncodeToString(kmsKey)
return metadata
} | csn_ccr |
Write the lines of an element to the PDf
@param string $elementName The name of the element.
@param array $element The element.
@return $this The current instance for a fluent interface. | protected function writePaymentSlipLines($elementName, array $element)
{
if (!is_string($elementName)) {
throw new \InvalidArgumentException('$elementName is not a string!');
}
if (!isset($element['lines'])) {
throw new \InvalidArgumentException('$element contains not... | csn |
def send_header(self, keyword, value):
"""Send a MIME header."""
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s: %s\r\n" % (keyword, value))
if keyword.lower() == 'connection':
if value.lower() == 'close':
| self.close_connection = 1
elif value.lower() == 'keep-alive':
self.close_connection = 0 | csn_ccr |
func (r *Route) getExecution(method string, pathParts []string, ex *routeExecution) {
curRoute := r
verb := getVerbFlagForMethod(method)
for {
// save all the middleware for matching verbs
for i := range curRoute.middleware {
if curRoute.middleware[i].verb.Matches(verb) {
ex.middleware = append(ex.midd... | if we have a handler to offer
curRoute.getHandler(method, ex)
if curRoute.fullPath == "" {
ex.pattern = "/"
} else {
ex.pattern = curRoute.fullPath
}
return
}
// iterate over our children looking for deeper to go
// binary search over regular children
if child := curRoute.children.Se... | csn_ccr |
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Crud->addListener('Users.Users', ['mailer' => 'Users.User']);
$this->Crud->mapAction('signup', [
'className' => 'CrudUsers.Register',
'view' => 'Users.signup',
'saveOptions' ... | 'text' => __('Your username or password is incorrect.')
]
],
]);
$this->Crud->mapAction('signout', [
'className' => 'CrudUsers.Logout',
'messages' => [
'success' => [
'text' => __('You are now signed out.')
... | csn_ccr |
Adds zeros to all alpha vecs that are not of the same length as the
vec list | private void addMissingZeros()
{
//go back and add 0s for the onces we missed
for (int i = 0; i < points.size(); i++)
while(points.get(i).alpha.size() < this.points.get(0).vecs.size())
points.get(i).alpha.add(0.0);
} | csn |
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\... | // finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var keywords = options['keywords'].replace(/^\s+|\s+$/g, '');
if (keywords.length) {
fallthroug... | csn_ccr |
function constructHostEntry(xmlElement) {
var host = {
scheme: DEFAULT_SCHEME,
name: '',
paths: []
};
var hostProperties = xmlElement['$'];
if (hostProperties == null || hostProperties.length == 0) {
return null;
}
// read host name
host.name = hostProperties.name;
// read sch... | != null) {
host.scheme = hostProperties.scheme;
}
// construct paths list, defined for the given host
host.paths = constructPaths(xmlElement);
return host;
} | csn_ccr |
public function delete($key): bool
{
$key = $this->buildKey($key);
| return $this->_handler->delete($key);
} | csn_ccr |
Remove all event listeners
@param string $eventName
@return void | public function removeListeners(string $eventName): void
{
foreach ($this->dispatcher->getListeners($eventName) as $listener) {
$this->removeListener($eventName, $listener);
}
} | csn |
// getDirNames returns the list of names from a pod's directory | func (p *Pod) getDirNames(path string) ([]string, error) {
dir, err := p.openFile(path, syscall.O_RDONLY|syscall.O_DIRECTORY)
if err != nil {
return nil, errwrap.Wrap(errors.New("unable to open directory"), err)
}
defer dir.Close()
ld, err := dir.Readdirnames(0)
if err != nil {
return nil, errwrap.Wrap(error... | csn |
Initialize the parser with the given command rules. | def init(self, rules):
"""Initialize the parser with the given command rules."""
# Initialize the option parser
for dest in rules.keys():
rule = rules[dest]
# Assign defaults ourselves here, instead of in the option parser
# itself in order to allow for multi... | csn |
def set_attribute_string_array(target, name, string_list):
""" Sets an attribute to an array of string on a Dataset or Group.
If the attribute `name` doesn't exist yet, it is created. If it
already exists, it is overwritten with the list of string
`string_list` (they will be vlen strings).
Notes
... | to set the attribute to. Strings must be ``str``
See Also
--------
set_attributes_all
"""
s_list = [convert_to_str(s) for s in string_list]
if sys.hexversion >= 0x03000000:
target.attrs.create(name, s_list,
dtype=h5py.special_dtype(vlen=str))
else:
... | csn_ccr |
def get_parameter(self):
"""Obtain the parameter object from the current widget state.
:returns: A BooleanParameter from the current state of widget
"""
| self._parameter.value = self._input.value()
return self._parameter | csn_ccr |
function nGram(n) {
if (typeof n !== 'number' || isNaN(n) || n < 1 || n === Infinity) {
throw new Error('`' + n + '` is not a valid argument for n-gram')
}
return grams
// Create n-grams from a given value.
function grams(value) {
var nGrams = []
var index
if (value === null || value === un... | nGrams
}
value = value.slice ? value : String(value)
index = value.length - n + 1
if (index < 1) {
return nGrams
}
while (index--) {
nGrams[index] = value.slice(index, index + n)
}
return nGrams
}
} | csn_ccr |
Creates a new snapshot of the available stats.
@return The latest statistics snapshot. | public CheckpointStatsSnapshot createSnapshot() {
CheckpointStatsSnapshot snapshot = latestSnapshot;
// Only create a new snapshot if dirty and no update in progress,
// because we don't want to block the coordinator.
if (dirty && statsReadWriteLock.tryLock()) {
try {
// Create a new snapshot
snapsh... | csn |
// GetModifiedConfiguration retrieves the modified configuration of the object.
// If annotate is true, it embeds the result as an anotation in the modified
// configuration. If an object was read from the command input, it will use that
// version of the object. Otherwise, it will use the version from the server. | func GetModifiedConfiguration(info *resource.Info, annotate bool) ([]byte, error) {
// First serialize the object without the annotation to prevent recursion,
// then add that serialization to it as the annotation and serialize it again.
var modified []byte
if info.VersionedObject != nil {
// If an object was rea... | csn |
Converts specified value into PagingParams.
:param value: value to be converted
:return: a newly created PagingParams. | def from_value(value):
"""
Converts specified value into PagingParams.
:param value: value to be converted
:return: a newly created PagingParams.
"""
if isinstance(value, PagingParams):
return value
if isinstance(value, AnyValueMap):
retu... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.