query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
def change_dylib_id(new_id, options = {})
raise ArgumentError, "argument must be a String" unless new_id.is_a?(String)
return unless machos.all?(&:dylib?)
each_macho(options) do | |macho|
macho.change_dylib_id(new_id, options)
end
repopulate_raw_machos
end | csn_ccr |
shows structured information of a object, list, tuple etc | def var_dump(*obs):
"""
shows structured information of a object, list, tuple etc
"""
i = 0
for x in obs:
str = var_dump_output(x, 0, ' ', '\n', True)
print (str.strip())
#dump(x, 0, i, '', object)
i += 1 | csn |
public static String getDataStoreIdentifier(URI location, String apiKey) {
checkArgument(getLocationType(location) != LocationType.STASH, "Stash locations do not have a data source ID");
UriBuilder uriBuilder = UriBuilder.fromUri(location)
.userInfo(apiKey)
.replacePath(... | Optional<String> zkConnectionStringOverride = getZkConnectionStringOverride(location);
if (zkConnectionStringOverride.isPresent()) {
uriBuilder.queryParam(ZK_CONNECTION_STRING_PARAM, zkConnectionStringOverride.get());
}
Optional<List<String>> hosts = getHost... | csn_ccr |
add all SearchResult objects from the SearchResults which fall
within the time range of this partition into this partition.
@param results | public void filter(CaptureSearchResults results) {
Iterator<CaptureSearchResult> itr = results.iterator();
while(itr.hasNext()) {
CaptureSearchResult result = itr.next();
String captureDate = result.getCaptureTimestamp();
if((captureDate.compareTo(startDateStr) >= 0)
&& (captureDate.compareTo(endDate... | csn |
Helper to handle methods, functions, generators, strings and raw code objects | def get_code_object(x):
"""Helper to handle methods, functions, generators, strings and raw code objects"""
if hasattr(x, '__func__'): # Method
x = x.__func__
if hasattr(x, '__code__'): # Function
x = x.__code__
if hasattr(x, 'gi_code'): # Generator
x = x.gi_code
if isinstan... | csn |
func AddAllExposedPodEdges(g osgraph.MutableUniqueGraph) {
for _, node := range g.(graph.Graph).Nodes() | {
if serviceNode, ok := node.(*kubegraph.ServiceNode); ok {
AddExposedPodEdges(g, serviceNode)
}
}
} | csn_ccr |
Add a property to the parameter
@param Parameter $property Properties to set
@return self | public function addProperty(Parameter $property)
{
$this->properties[$property->getName()] = $property;
$property->setParent($this);
$this->propertiesCache = null;
return $this;
} | csn |
python convolve gaussian kernel | def convolve_gaussian_2d(image, gaussian_kernel_1d):
"""Convolve 2d gaussian."""
result = scipy.ndimage.filters.correlate1d(
image, gaussian_kernel_1d, axis=0)
result = scipy.ndimage.filters.correlate1d(
result, gaussian_kernel_1d, axis=1)
return result | cosqa |
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme | def _map_table_name(self, model_names):
"""
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme
"""
for model in model_names:
if isinstance(model, tuple):
model = model[0]
try:
model_cls = get... | csn |
initialize Config Source Object for given resource
@param Smarty_Internal_Config $_config config object
@return Smarty_Config_Source Source Object | public static function config(Smarty_Internal_Config $_config)
{
static $_incompatible_resources = array('eval' => true, 'string' => true, 'extends' => true, 'php' => true);
$config_resource = $_config->config_resource;
$smarty = $_config->smarty;
// parse resource_name
... | csn |
Searches for a comboitem that has a date range equivalent to the specified range.
@param range The date range to locate.
@return A comboitem containing the date range, or null if not found. | public Dateitem findMatchingItem(DateRange range) {
for (BaseComponent item : getChildren()) {
if (range.equals(item.getData())) {
return (Dateitem) item;
}
}
return null;
} | csn |
Return the Brizo component url.
:param config: Config
:return: Url, str | def get_brizo_url(config):
"""
Return the Brizo component url.
:param config: Config
:return: Url, str
"""
brizo_url = 'http://localhost:8030'
if config.has_option('resources', 'brizo.url'):
brizo_url = config.get('resources', 'brizo.url') or brizo_ur... | csn |
// Group defines group's child group | func (g *Group) Group(p string, o interface{}) {
gr := getGroup(o)
for _, gchild := range gr.routers {
g.Route(gchild.methods, joinRoute(p, gchild.url), gchild.c, append(gr.handlers, gchild.handlers...)...)
}
} | csn |
// FuncHasQuery returns the offset of the string parameter named "query", or
// none if no such parameter exists. | func FuncHasQuery(sqlPackages sqlPackage, s *types.Signature) (offset int, ok bool) {
params := s.Params()
for i := 0; i < params.Len(); i++ {
v := params.At(i)
for _, paramName := range sqlPackages.paramNames {
if v.Name() == paramName {
return i, true
}
}
}
return 0, false
} | csn |
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults. | def freeze(self) -> dict:
"""
Returns a dictionary of all settings set for this object, including
any values of its parents or hardcoded defaults.
"""
settings = {}
for key, v in self._h.defaults.items():
settings[key] = self._unserialize(v.value, v.type)
... | csn |
Helper function to obtain the shape of an array | def get_input_shape(sym, proto_obj):
"""Helper function to obtain the shape of an array"""
arg_params = proto_obj.arg_dict
aux_params = proto_obj.aux_dict
model_input_shape = [data[1] for data in proto_obj.model_metadata.get('input_tensor_data')]
data_names = [data[0] for data in proto_obj.model_... | csn |
Add a profile to a role | def add_profile(project_root)
roles = Bebox::Role.list(project_root)
profiles = Bebox::Profile.list(project_root)
role = choose_option(roles, _('wizard.choose_role'))
profile = choose_option(profiles, _('wizard.role.choose_add_profile'))
if Bebox::Role.profile_in_role?(project_root, role, ... | csn |
// FailAction is part of the operation.Callbacks interface. | func (opc *operationCallbacks) FailAction(actionId, message string) error {
if !names.IsValidAction(actionId) {
return errors.Errorf("invalid action id %q", actionId)
}
tag := names.NewActionTag(actionId)
err := opc.u.st.ActionFinish(tag, params.ActionFailed, nil, message)
if params.IsCodeNotFoundOrCodeUnauthori... | csn |
python fallback on not found values | def apply_to_field_if_exists(effect, field_name, fn, default):
"""
Apply function to specified field of effect if it is not None,
otherwise return default.
"""
value = getattr(effect, field_name, None)
if value is None:
return default
else:
return fn(value) | cosqa |
public function setCoreSymlinkMergeFields($value)
{
$this->setFieldName('symlink_merge_fields');
$this->loadObject(true); |
$this->setFieldValue($value);
return $this;
} | csn_ccr |
// SetReadTimeout sets the maximum time that can pass between reads.
// If no data is received in the set duration the connection will be closed
// and Read returns an error. | func (c *BaseConn) SetReadTimeout(timeout time.Duration) {
c.readTimeout = timeout
// apply new timeout immediately
_ = c.resetTimeout()
} | csn |
function(script) {
script[ STR_ONREADYSTATECHANGE ]
= script[ STR_ONLOAD ]
= script[STR_ONERROR]
| = null;
head().removeChild( script );
} | csn_ccr |
def transform_predict(self, X, y):
"""
Apply transforms to the data, and predict with the final estimator.
Unlike predict, this also returns the transformed target
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first... | yt : array-like
Transformed target
yp : array-like
Predicted transformed target
"""
Xt, yt, _ = self._transform(X, y)
yp = self._final_estimator.predict(Xt)
return yt, yp | csn_ccr |
// Send mockcore sending seek info to the deliver server | func (c *MockConnection) Send(sinfo *ab.SeekInfo) error {
if c.Closed() {
return errors.New("mock connection is closed")
}
switch seek := sinfo.Start.Type.(type) {
case *ab.SeekPosition_Specified:
// Deliver all blocks from the given block number
fromBlock := seek.Specified.Number
c.Ledger().SendFrom(fromB... | csn |
def send(self, value):
"""
Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chain... | """
if not self.block and self._stdin is not None:
self.writer.write("{}\n".format(value))
return self
else:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE) | csn_ccr |
public function isAllowedHost($fullHost)
{
$host = \MUtil_String::stripToHost($fullHost);
$request = $this->request;
if ($request instanceof \Zend_Controller_Request_Http) {
if ($host == \MUtil_String::stripToHost($request->getServer('HTTP_HOST'))) {
return true;
... | }
}
}
$loader = $this->getLoader();
foreach ($loader->getUserLoader()->getOrganizationUrls() as $url => $orgId) {
if ($host == \MUtil_String::stripToHost($url)) {
return true;
}
}
return false;
} | csn_ccr |
Add Scheduling Block to the database.
Args:
config_dict (dict): SBI configuration | def add_sched_block_instance(self, config_dict):
"""Add Scheduling Block to the database.
Args:
config_dict (dict): SBI configuration
"""
# Get schema for validation
schema = self._get_schema()
LOG.debug('Adding SBI with config: %s', config_dict)
# ... | csn |
public function view($action, $view = null)
{
if (is_array($action)) {
foreach ($action as $realAction => $realView) {
| $this->action($realAction)->view($realView);
}
return;
}
$this->action($action)->view($view);
} | csn_ccr |
Get the config dependency.
@return \Asgard\Config\ConfigInterface | public function getConfig() {
if(!$this->config) {
$this->config = $config = new \Asgard\Config\Config($this->getCache());
if(file_exists($this->params['root'].'/config'))
$config->loadDir($this->params['root'].'/config', $this->getEnv());
}
return $this->config;
} | csn |
Toggle the drone's emergency state. | def reset(self):
"""Toggle the drone's emergency state."""
self.at(ardrone.at.ref, False, True)
time.sleep(0.1)
self.at(ardrone.at.ref, False, False) | csn |
Read JSON config file and return array
@param string $file
@return array $config | public static function getConfigFile($filename)
{
$filename = addslashes($filename);
if (is_file($filename)) {
$data = str_replace("\\", "\\\\", file_get_contents($filename));
$json = json_decode($data, true);
if (empty($json)) {
throw new \Except... | csn |
The base implementation of `_.conforms` which doesn't clone `source`.
@private
@param {Object} source The object of property predicates to conform to.
@returns {Function} Returns the new spec function. | function baseConforms(source) {
var props = keys(source);
return function(object) {
return baseConformsTo(object, source, props);
};
} | csn |
Create a User. | def create_user(self, data):
"""Create a User."""
# http://teampasswordmanager.com/docs/api-users/#create_user
log.info('Create user with %s' % data)
NewID = self.post('users.json', data).get('id')
log.info('User has been created with ID %s' % NewID)
return NewID | csn |
Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:... | def rotateAboutVectorMatrix(vec, theta_deg):
"""Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should... | csn |
Helper to handle the return type. | def _handle_type(self, other):
"""Helper to handle the return type."""
if isinstance(other, Int):
return Int
elif isinstance(other, Float):
return Float
else:
raise TypeError(
f"Unsuported operation between `{type(self)}` and `{type(oth... | csn |
func (l *StubLogger) Panicf(format string, args ...interface{}) {
| panic(fmt.Sprintf(format, args...))
} | csn_ccr |
Creates a new CachedConditionGenerator instance for the given ConditionGenerator.
Note: When no cache driver was configured the original ConditionGenerator
is returned instead.
@param int|\DateInterval|null $ttl Optional. The TTL value of this item. If no value is sent and
the driver supports TTL then the library may... | public function createCachedConditionGenerator(ConditionGenerator $conditionGenerator, $ttl = 0): ConditionGenerator
{
if (null === $this->cacheDriver) {
return $conditionGenerator;
}
return new CachedConditionGenerator($conditionGenerator, $this->cacheDriver, $ttl);
} | csn |
From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_d... | def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
U... | csn |
Generate hidden fields not related to inputs
@return string | private function buildHiddenFields()
{
$this->debug->groupCollapsed(__METHOD__);
$cfg = $this->form->cfg;
$printOpts = &$cfg['output'];
$hiddenFields = '';
if ($printOpts['inputKey']) { // && $cfg['persist_method'] != 'none'
$hiddenFields .= '<input type="hidde... | csn |
def rename(self, *args, **kwargs):
"""
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
See the :ref:`user guide <basics.rename>` for more.
P... | --------
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df = pd.DataFrame({"A": [1... | csn_ccr |
Gets the value of the resourceRequestCriterion property.
<p>
This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a <CODE>set</CODE> method for the resourceRequestCriterion pr... | public List<ResourceRequestType.ResourceRequestCriterion> getResourceRequestCriterion()
{
if (resourceRequestCriterion == null)
{
resourceRequestCriterion = new ArrayList<ResourceRequestType.ResourceRequestCriterion>();
}
return this.resourceRequestCriterion;
} | csn |
Retrieves a child component by its index.
@param index the index of the child component to be retrieved.
@return the child component at the given index. | WComponent getChildAt(final int index) {
ComponentModel model = getComponentModel();
return model.getChildren().get(index);
} | csn |
def thing_type_absent(name, thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Ensure thing type with passed properties is absent.
.. versionadded:: 2016.11.0
name
The name of the state definition.
thingTypeName
Name of the thing type.
regi... | if _tz_index != -1:
_deprecation_date_str = _deprecation_date_str[:_tz_index]
_deprecation_date = datetime.datetime.strptime(
_deprecation_date_str,
"%Y-%m-%d %H:%M:%S.%f"
)
_elapsed_time_delta = datetime.datetime.utcnow() - _de... | csn_ccr |
def parse_signature(cls, signature):
"""Parse signature declartion string
Uses :py:attr:`signature_pattern` to parse out pieces of constraint
signatures. Pattern should provide the following named groups:
prefix
Object prefix, such as a namespace
member... | groups = match.groupdict()
arguments = None
if 'arguments' in groups and groups['arguments'] is not None:
arguments = re.split(r'\,\s+', groups['arguments'])
return DotNetSignature(
prefix=groups.get('prefix', None),
member=grou... | csn_ccr |
public static Optional<Element> getChildElement(final Element elem, final DitaClass cls) {
final NodeList children = elem.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node child = children.item(i);
| if (cls.matches(child)) {
return Optional.of((Element) child);
}
}
return Optional.empty();
} | csn_ccr |
Get a single or a collection of remote objects from the object store.
This method is identical to `ray.get` except it adds support for tuples,
ndarrays and dictionaries.
Args:
object_ids: Object ID of the object to get, a list, tuple, ndarray of
object IDs to get or a dict of {key: obj... | def get(object_ids):
"""Get a single or a collection of remote objects from the object store.
This method is identical to `ray.get` except it adds support for tuples,
ndarrays and dictionaries.
Args:
object_ids: Object ID of the object to get, a list, tuple, ndarray of
object IDs t... | csn |
Config for FACE_DETECTION.
Generated from protobuf field <code>.google.cloud.videointelligence.v1beta2.FaceDetectionConfig face_detection_config = 5;</code>
@param \Google\Cloud\VideoIntelligence\V1beta2\FaceDetectionConfig $var
@return $this | public function setFaceDetectionConfig($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\VideoIntelligence\V1beta2\FaceDetectionConfig::class);
$this->face_detection_config = $var;
return $this;
} | csn |
public function clear()/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->clear()) {
return $this->falseAndSetError(
| $end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | csn_ccr |
public function handle( \AltoRouter $router, \PowerOn\Network\Request $request ) {
$match = $router->match($request->path);
if ( $match ) {
$target = explode('#', $match['target']);
$this->controller = $target[0];
$this->action = key_exists(1, $target) ? $target[1] : ... | $action : 'index';
}
$handler = $this->loadController();
if ( !$handler || !method_exists($handler, $this->action) ) {
throw new NotFoundException('El sitio al que intenta ingresar no existe.');
}
return $handler;
} | csn_ccr |
parse an color
@param mixed $color | public static function create( $color )
{
// our return
$rgb = array();
if ( is_array( $color ) )
{
$color = array_values( $color );
$rgb[0] = $color[0];
$rgb[1] = $color[1];
$rgb[2] = $color[2];
}
// parse hex color
elseif ( is_string( $color ) && substr( $color, 0, 1 ) == '#' )
{
... | csn |
def checkReference(self, reference):
"""
Check the reference for security. Tries to avoid any characters
necessary for doing a script injection.
"""
| pattern = re.compile(r'[\s,;"\'&\\]')
if pattern.findall(reference.strip()):
return False
return True | csn_ccr |
def parse(datetime_str, timezone=None, isofirst=True, dayfirst=True, yearfirst=True):
"""
Parses a datetime string and returns a `Delorean` object.
:param datetime_str: The string to be interpreted into a `Delorean` object.
:param timezone: Pass this parameter and the returned Delorean object will be n... | be in the timezone supplied. Any offsets in
the datetime_str will be ignored.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0500', timezone='US/Pacific')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='US/Pacific')
If an unambiguous timezone is detected in the datetime... | csn_ccr |
Try to set us as active | function (element, scroller) {
if (!element || !_Global.document.body || !_Global.document.body.contains(element)) {
return false;
}
if (!_ElementUtilities._setActive(element, scroller)) {
return false;
... | csn |
Set active only to true or false on a copy of this query | def show_active_only(self, state):
"""
Set active only to true or false on a copy of this query
"""
query = self._copy()
query.active_only = state
return query | csn |
protected RefProperty registerErrorModel(Swagger swagger) {
String ref = Error.class.getSimpleName();
if (swagger.getDefinitions() != null && swagger.getDefinitions().containsKey(ref)) {
// model already registered
return new RefProperty(ref);
}
ModelImpl model =... | model.addProperty("requestUri", new StringProperty().readOnly().description("http request path"));
model.addProperty("message", new StringProperty().readOnly().description("application message"));
if (settings.isDev()) {
// in DEV mode the stacktrace is returned in the error message
... | csn_ccr |
Yields each object indexed by the index with
name ``name`` with ``values`` matching on indexed
field values. | def each_indexed_object(collection, index_name, **where):
"""Yields each object indexed by the index with
name ``name`` with ``values`` matching on indexed
field values."""
index = _db[collection].indexes[index_name]
for id in index.value_map.get(indexed_value(index, where), []):
yield get_o... | csn |
def symlink_create(self, symlink, target, type_p):
"""Creates a symbolic link in the guest.
in symlink of type str
Path to the symbolic link that should be created. Guest path
style.
in target of type str
The path to the symbolic link target. If not an abs... |
"""
if not isinstance(symlink, basestring):
raise TypeError("symlink can only be an instance of type basestring")
if not isinstance(target, basestring):
raise TypeError("target can only be an instance of type basestring")
if not isinstance(type_p, SymlinkType):... | csn_ccr |
function animate(Promise, TweenModule) {
var animateTo = _animateFunc.bind(null, TweenModule.to);
var util = animateTo;
util.to = animateTo;
util.from = _animateFunc.bind(null, TweenModule.from);
util.set = function animateSet(element, params) {
params = Object.assign({}, params);
return new Promise... | to);
var tween;
return new Promise(function(resolve, reject, onCancel) {
to.onComplete = resolve;
tween = TweenModule.fromTo(element, duration, from, to);
onCancel &&
onCancel(function() {
tween.kill();
});
});
};
util.killTweensOf = TweenModule.killTweensOf... | csn_ccr |
update the attributes of a vod media
@param $mediaId string, mediaId of the media
@param $title string, new title of the media
@param $description string, new description of the media
@param array $options Supported options:
{
config: the optional bce configuration, which will overwrite the
default vod client configur... | public function updateMedia($mediaId, $title, $description, $options = array())
{
list($config) = $this->parseOptions($options, 'config');
if (empty($mediaId)) {
throw new BceClientException("The parameter mediaId should NOT be null or empty string");
}
if (empty($title... | csn |
Get the bounding box of all paths in the map combined. | function (paths) {
var maxX = Number.MIN_VALUE,
minX = Number.MAX_VALUE,
maxY = Number.MIN_VALUE,
minY = Number.MAX_VALUE;
// Find the bounding box
each(paths || this.options.data, function (point) {
var path = point.path,
i = path.length,
even = false, // while loop read... | csn |
Creates a floating-point symbol.
:param name: The name of the symbol
:param sort: The sort of the floating point
:param explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:return: An FP AST. | def FPS(name, sort, explicit_name=None):
"""
Creates a floating-point symbol.
:param name: The name of the symbol
:param sort: The sort of the floating point
:param explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:return: ... | csn |
Returns the first mapping for a table name | def _get_mapping_for_table(self, table):
""" Returns the first mapping for a table name """
for mapping in self.mappings.values():
if mapping["table"] == table:
return mapping | csn |
public String transBinaryXml(String path) throws IOException {
byte[] data = getFileData(path);
if (data == null) {
return null;
}
parseResourceTable();
XmlTranslator xmlTranslator | = new XmlTranslator();
transBinaryXml(data, xmlTranslator);
return xmlTranslator.getXml();
} | csn_ccr |
Processes a regex match for a module to create a CodeElement. | def _process_module(self, name, contents, parent, match, filepath=None):
"""Processes a regex match for a module to create a CodeElement."""
#First, get hold of the name and contents of the module so that we can process the other
#parts of the module.
modifiers = []
#We need to ... | csn |
Import network data from CSVs in a folder.
The CSVs must follow the standard form, see pypsa/examples.
Parameters
----------
csv_folder_name : string
Name of folder
encoding : str, default None
Encoding to use for UTF when reading (ex. 'utf-8'). `List of Python
standard enc... | def import_from_csv_folder(network, csv_folder_name, encoding=None, skip_time=False):
"""
Import network data from CSVs in a folder.
The CSVs must follow the standard form, see pypsa/examples.
Parameters
----------
csv_folder_name : string
Name of folder
encoding : str, default Non... | csn |
Deletes references to the external google fonts in the Home
Documentation's index.html file | def make_offline():
"""Deletes references to the external google fonts in the Home
Documentation's index.html file
"""
dir_path = Path(os.getcwd()).absolute()
css_path = dir_path / "site" / "assets" / "stylesheets"
material_css = css_path / "material-style.css"
if not material_css.exists():... | csn |
Wraps a GET request with a url check | def _get(self, url, params=None, headers=None):
"""Wraps a GET request with a url check"""
url = self.clean_url(url)
response = requests.get(url, params=params, verify=self.verify,
timeout=self.timeout, headers=headers)
return response | csn |
def _unzip_file(self, src_path, dest_path, filename):
"""unzips file located at src_path into destination_path"""
self.logger.info("unzipping file...")
# construct full path (including file name) for unzipping
unzip_path = os.path.join(dest_path, | filename)
utils.ensure_directory_exists(unzip_path)
# extract data
with zipfile.ZipFile(src_path, "r") as z:
z.extractall(unzip_path)
return True | csn_ccr |
func (f FunctionNameList) Less(i, j int) bool {
if f[i].Str == "" && f[j].Str != "" {
return true
}
if f[i].Str != "" && f[j].Str == "" {
return false
}
if f[i].Str != "" && f[j].Str != "" | {
if f[i].Str > f[j].Str {
return true
} else if f[i].Str < f[j].Str {
return false
}
}
return f[i].Name < f[j].Name
} | csn_ccr |
function createControllerFunction(func) {
var Handlebars = protos.require('handlebars');
var context, newFunc, compile, source,
funcSrc = func.toString();
var code = funcSrc
.trim()
.replace(/^function\s+(.*?)(\s+)?\{(\s+)?/, '')
.replace(/(\s+)?\}$/, '');
// Get source file path
var... | = this.filters["{{{name}}}"] || [];\n\
}\n\n\
require("util").inherits({{{name}}}, protos.lib.controller);\n\n\
protos.extend({{{name}}}, protos.lib.controller);\n\n\
{{{name}}}.filter = {{{name}}}.prototype.filter;\n\
{{{name}}}.handler = {{{name}}}.prototype.handler;\n\n\
var __funKeys__ = Object.keys({{{name}}});\n... | csn_ccr |
Returns the unique text-based ID for a todo item. | def uid(self, p_todo):
"""
Returns the unique text-based ID for a todo item.
"""
try:
return self._todo_id_map[p_todo]
except KeyError as ex:
raise InvalidTodoException from ex | csn |
put cookieMap to result
@param result a Map you want to put dumping info to. | @Override
protected void putDumpInfoTo(Map<String, Object> result) {
if(this.cookieMap.size() > 0) {
result.put(DumpConstants.COOKIES, cookieMap);
}
} | csn |
def create_processors_from_settings(self):
"""
Expects the Django setting "EVENT_TRACKING_PROCESSORS" to be defined and
point to a list of backend engine configurations.
Example::
EVENT_TRACKING_PROCESSORS = [
{
'ENGINE': 'some.arbitrary.... | 'OPTIONS': {
'user': 'foo'
}
},
]
"""
config = getattr(settings, DJANGO_PROCESSOR_SETTING_NAME, [])
processors = self.instantiate_objects(config)
return processors | csn_ccr |
public function getAncestors()
{
$ancestors = new Collection();
$ancestor = $this;
while (($ancestor = $ancestor->parent) && !$ancestors->contains($ancestor)) {
| $ancestors->push($ancestor);
break;
}
return $ancestors;
} | csn_ccr |
def get_version(*args):
"""Extract the version number from a Python module."""
contents | = get_contents(*args)
metadata = dict(re.findall('__([a-z]+)__ = [\'"]([^\'"]+)', contents))
return metadata['version'] | csn_ccr |
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too. | def methods(self, *args, **kwds):
"""
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too.
"""
self.callmanager.methods(self, *args, **kwds) | csn |
Output a string
@param string $str String to output
@param false|int $row The optional row to output to
@param false|int $col The optional column to output to | public static function string( $str, $row = null, $col = null ) {
if( $col !== null || $row !== null ) {
Cursor::rowcol($row, $col);
}
fwrite(self::$stream, $str);
} | csn |
python base64 decode byte array | def decode_arr(data):
"""Extract a numpy array from a base64 buffer"""
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | cosqa |
// NewServer constructs a server from the provided config. | func NewServer(ctx context.Context, c Config) (*Server, error) {
return newServer(ctx, c, defaultRotationStrategy(
value(c.RotateKeysAfter, 6*time.Hour),
value(c.IDTokensValidFor, 24*time.Hour),
))
} | csn |
An internal method to find the parent directory record and name given a
Joliet path. If the parent is found, return a tuple containing the
basename of the path and the parent directory record object.
Parameters:
joliet_path - The absolute Joliet path to the entry on the ISO.
R... | def _joliet_name_and_parent_from_path(self, joliet_path):
# type: (bytes) -> Tuple[bytes, dr.DirectoryRecord]
'''
An internal method to find the parent directory record and name given a
Joliet path. If the parent is found, return a tuple containing the
basename of the path and t... | csn |
public function sortBy(SortBy $sortBy): self
{
if ($sortBy->isSortedByGeoDistance()) {
if (!$this->coordinate instanceof Coordinate) {
throw InvalidFormatException::querySortedByDistanceWithoutCoordinate();
}
| $sortBy->setCoordinate($this->coordinate);
}
$this->sortBy = $sortBy;
return $this;
} | csn_ccr |
Properties of a StringValue.
@memberof google.protobuf
@interface IStringValue
@property {string|null} [value] StringValue value
Constructs a new StringValue.
@memberof google.protobuf
@classdesc Represents a StringValue.
@implements IStringValue
@constructor
@param {google.protobuf.IStringValue=} [properties] Proper... | function StringValue(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
} | csn |
Return the first string term in the conjunction, or `None`. | def string(self):
"""
Return the first string term in the conjunction, or `None`.
"""
for term in self._terms:
if isinstance(term, String):
return str(term)
return None | csn |
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format. | def genkeyhex():
'''
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format.
'''
while True:
key = hash256(
hexlify(os.urandom(40) + str(datetime.datetime.now())
.encode("utf-8")))
# 40 byt... | csn |
// NewStateBackend converts a state.State into a Backend. | func NewStateBackend(st *state.State) (Backend, error) {
m, err := st.Model()
if err != nil {
return nil, err
}
if m.Type() != state.ModelTypeIAAS {
return nil, errors.NotSupportedf("Firewall Rules for non-IAAS models")
}
return &stateShim{
State: st,
Model: m,
}, nil
} | csn |
Logs the names of the entities the loader is attempting
to load. | private function logAutoloadedEntities()
{
$cpts = array_keys($this->getConfiguration());
$message = sprintf("Found %s custom post types : %s", count($cpts), implode(", ", $cpts));
Strata::app()->setConfig("runtime.custom_post_types", $cpts);
} | csn |
def get_as_list(self, tag_name):
"""
Return the value of a tag, making sure that it's a list. Absent
tags are returned as an empty-list; single tags are returned as a
one-element list.
The returned list is a copy, and modifications do not affect the
| original object.
"""
val = self.get(tag_name, [])
if isinstance(val, list):
return val[:]
else:
return [val] | csn_ccr |
Respond with the asset.
@param \Psr\Http\Message\ResponseInterface $response The response to augment
@param string $contents The asset contents.
@param \MiniAsset\AssetTarget $build The build target.
@return \Psr\Http\Message\ResponseInterface | protected function respond($response, $contents, $build)
{
// Deliver built asset.
$body = $response->getBody();
$body->write($contents);
$body->rewind();
return $response->withHeader('Content-Type', $this->mapType($build));
} | csn |
function _supportColorProps(props) {
var p;
for (p = 0; p < props.length; p += 1) { |
$.fx.step[props[p]] = _animateColor;
}
} | csn_ccr |
call multiple python files in a script | def load_files(files):
"""Load and execute a python file."""
for py_file in files:
LOG.debug("exec %s", py_file)
execfile(py_file, globals(), locals()) | cosqa |
assigning the actual script settings depending on the iterator type
this might be overwritten by classes that inherit form ScriptIterator
Args:
sub_scripts: dictionary with the subscripts
script_order: execution order of subscripts
script_execution_freq: execution f... | def get_default_settings(sub_scripts, script_order, script_execution_freq, iterator_type):
"""
assigning the actual script settings depending on the iterator type
this might be overwritten by classes that inherit form ScriptIterator
Args:
sub_scripts: dictionary with the su... | csn |
public static List<String> getAIALocations(X509Certificate userCertificate)
throws CertificateVerificationException {
List<String> locations;
//List the AIA locations from the certificate. Those are the URL's of CA s.
try {
locations = OCSPVerifier.getAIALocations(userCer... | } catch (CertificateVerificationException e) {
throw new CertificateVerificationException("Failed to find AIA locations in the cetificate", e);
}
return locations;
} | csn_ccr |
Returns a formatted link with all of the attributes
@param array $link This should be an array containing all of the set link values
@param string $activeClass If the link is active should have the active class string set else should be empty
@param boolean If the element has any child elements set to true else set to ... | public static function formatLink($link, $activeClass, $hasChild = false, $breadcrumbLink = false) {
return "<a".self::href($link).self::title($link).self::htmlClass(($breadcrumbLink ? '' : self::$linkDefaults['a_default'].' ').(isset($link['class']) ? $link['class'] : ''), $activeClass).self::target($link).sel... | csn |
def update_ebounds(hdu_in, hdu=None):
""" 'Update' the EBOUNDS HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this raises an exception if it doesn not match hdu_in
"""
if hdu is None:
hdu = fits.BinTableHDU(
data=hdu_in.data, header=hdu_... | for col in ['CHANNEL', 'E_MIN', 'E_MAX']:
if (hdu.data[col] != hdu_in.data[col]).any():
raise ValueError("Energy bounds do not match : %s %s" %
(hdu.data[col], hdu_in.data[col]))
return hdu | csn_ccr |
Given a field key or name, return it's field key. | def get_field_key(self, key, using_name=True):
"""Given a field key or name, return it's field key.
"""
try:
if using_name:
return self.f_name[key].key
else:
return self.f[key].key
except KeyError:
raise ValueError("'%s'... | csn |
private function grabAttribsBeforeToken(Tokens $tokens, $index, array $tokenAttribsMap, array $attribs)
{
while (true) {
$token = $tokens[--$index];
if (!$token->isArray()) {
if ($token->equalsAny(['{', '}', '(', ')'])) {
break;
}
... |
}
// clear the token and whitespaces after it
$tokens[$index]->clear();
$tokens[$index + 1]->clear();
continue;
}
if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) {
continue;
... | csn_ccr |
perform elliptic curve addition | def add(self, p, q):
"""
perform elliptic curve addition
"""
if p.iszero():
return q
if q.iszero():
return p
lft = 0
# calculate the slope of the intersection line
if p == q:
if p.y == 0:
return self.zer... | csn |
def default(event, data):
"""The default handler prints basic event info."""
messages = defaultdict(lambda: 'Avast:')
messages['start'] = 'Thar she blows!'
messages['tag'] = 'Thar she blows!'
messages['stop'] = 'Away into the depths:'
messages['destroy'] = 'Away into the ... | = 'Away into the depths:'
status = get_status(event)
message = messages[status] + ' %s/%s'
log.info(message, status, get_id(event))
log.debug('"data": %s', form_json(data)) | csn_ccr |
generate a dotfile in python d tree | def to_dotfile(self):
""" Writes a DOT graphviz file of the domain structure, and returns the filename"""
domain = self.get_domain()
filename = "%s.dot" % (self.__class__.__name__)
nx.write_dot(domain, filename)
return filename | cosqa |
def runtime_error(self, msg, method):
"""
Show the error in the bar
"""
if self.testing:
self._py3_wrapper.report_exception(msg)
raise KeyboardInterrupt
if self.error_hide:
self.hide_errors()
return
# only show first line ... | errors = [self.module_nice_name, u"{}: {}".format(self.module_nice_name, msg)]
# if we have shown this error then keep in the same state
if self.error_messages != errors:
self.error_messages = errors
self.error_index = 0
self.error_output(self.error_messages[self.error_... | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.