query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
get contour and fill image python | def filter_contour(imageFile, opFile):
""" convert an image by applying a contour """
im = Image.open(imageFile)
im1 = im.filter(ImageFilter.CONTOUR)
im1.save(opFile) | cosqa |
Register a javascript file in the asset's js folder
@param string $name the js file name to register
@param int $position the position of the JavaScript code.
@see CClientScript::registerScriptFile | public function registerAssetJs($name, $position = CClientScript::POS_END) {
$this->cs->registerScriptFile($this->getAssetsUrl() . "/js/{$name}", $position);
} | csn |
def correct_dactyl_chain(self, scansion: str) -> str:
"""
Three or more unstressed accents in a row is a broken dactyl chain, best detected and
processed backwards.
Since this method takes a Procrustean approach to modifying the scansion pattern,
it is not used by default in the... | if one == self.constants.STRESSED and \
two == self.constants.STRESSED:
feet += [one]
feet += [two]
idx -= 2
continue
# handle "U U U" foot as "- U U"
if one == self.constants.UNSTRESSED and \
... | csn_ccr |
Adds a new ReadGroupSet into this repo. | def addReadGroupSet(self):
"""
Adds a new ReadGroupSet into this repo.
"""
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
dataUrl = self._args.dataFile
indexFile = self._args.indexFile
parsed = urlparse.urlparse(dataUrl)
... | csn |
Sets the layout template.
@param string $template The template name
@return self | public function setTemplate($template)
{
$layout = $this->getViewModel();
$layout->setTemplate((string) $template);
return $this;
} | csn |
func (client *Client) SetLanguage(langs ...string) error {
if len(langs) == 0 {
return fmt.Errorf("languages cannot be empty")
| }
client.Languages = langs
client.flagForInit()
return nil
} | csn_ccr |
Naturally, the magical girl is very good at performing magic. She recently met her master wizard Devu, who gifted her R potions of red liquid,
B potions of blue liquid, and G potions of green liquid.
-
The red liquid potions have liquid amounts given by r[1], ..., r[R] liters.
-
The green liquid potions have liqu... | import sys
import math
import heapq
def half(n):
return n//2
def main(arr,m):
a,b,c=arr
while m!=0:
s=max(a,b,c)
if s==a:
a=half(a)
elif s==b:
b=half(b)
else:
c=half(c)
m-=1
return max(a,b,c)
for i in range(int(input())):
r,g,b,m=list(map(int,input().split()))
arr=[]
... | apps |
Generates an OpenID Connect ID token for a service account.
<p>Sample code:
<pre><code>
try (IamCredentialsClient iamCredentialsClient = IamCredentialsClient.create()) {
ServiceAccountName name = ServiceAccountName.of("[PROJECT]", "[SERVICE_ACCOUNT]");
List<String> delegates = new ArrayList<>();
String au... | public final GenerateIdTokenResponse generateIdToken(
ServiceAccountName name, List<String> delegates, String audience, boolean includeEmail) {
GenerateIdTokenRequest request =
GenerateIdTokenRequest.newBuilder()
.setName(name == null ? null : name.toString())
.addAllDelegates... | csn |
Print out server session data. | def get_session_data( username, password_verifier, salt, client_public, private, preset):
"""Print out server session data."""
session = SRPServerSession(
SRPContext(username, prime=preset[0], generator=preset[1]),
hex_from_b64(password_verifier), private=private)
session.process(client_pub... | csn |
Create `Application` instance for this . | def _create_app(self):
"""
Create `Application` instance for this .
"""
pymux = self.pymux
def on_focus_changed():
""" When the focus changes to a read/write buffer, make sure to go
to insert mode. This happens when the ViState was set to NAVIGATION
... | csn |
public static ProjectFilterSettings fromEncodedString(String s) {
ProjectFilterSettings result = new ProjectFilterSettings();
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String minPriority;
if (bar >= 0) {
minPriority = s.substring(0, ... |
s = "";
}
result.setDisplayFalseWarnings(Boolean.valueOf(displayFalseWarnings).booleanValue());
}
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String minRankStr;
if (bar >= 0) {
minRankStr = s.su... | csn_ccr |
Write a command to the socket
:param Command command: the Command data structure | def _write(self, command, future):
"""Write a command to the socket
:param Command command: the Command data structure
"""
def on_written():
self._on_written(command, future)
try:
self._stream.write(command.command, callback=on_written)
except ... | csn |
function tileToBBOX(tile) {
var e = tile2lon(tile[0] + 1, tile[2]);
var w = tile2lon(tile[0], tile[2]);
var s = tile2lat(tile[1] | + 1, tile[2]);
var n = tile2lat(tile[1], tile[2]);
return [w, s, e, n];
} | csn_ccr |
// SetUser - sets a user info. | func (adm *AdminClient) SetUser(accessKey, secretKey string, status AccountStatus) error {
if !auth.IsAccessKeyValid(accessKey) {
return auth.ErrInvalidAccessKeyLength
}
if !auth.IsSecretKeyValid(secretKey) {
return auth.ErrInvalidSecretKeyLength
}
data, err := json.Marshal(UserInfo{
SecretKey: secretKey,... | csn |
Assert that subject has access at given level or higher for object. | def required_permission(f, level):
"""Assert that subject has access at given level or higher for object."""
@functools.wraps(f)
def wrapper(request, pid, *args, **kwargs):
d1_gmn.app.auth.assert_allowed(request, level, pid)
return f(request, pid, *args, **kwargs)
return wrapper | csn |
def _add_command(self, name, **parameters):
"""
Add a new command to the blueprint.
:param name: The command name
:type name: str
:param parameters: The command parameters
:type parameters: dict
:rtype: Fluent |
"""
command = self._create_command(name, **parameters)
self._commands.append(command)
return command | csn_ccr |
func (d *State332c) Sum32() uint32 {
d.pc, d.pb = | Jenkins364(d.tail, len(d.tail), d.pc, d.pb)
d.hash = d.pc
return d.hash
} | csn_ccr |
def add_weatherdata(self, data):
"""Appends weather data.
Args:
data (WeatherData): weather data object
| """
if not isinstance(data, WeatherData):
raise ValueError('Weather data need to be of type WeatherData')
self._data["WEATHER DATA"].append(data) | csn_ccr |
func LookupPath(bin string, paths string) (string, error) {
pathsArr := filepath.SplitList(paths)
for _, path := range pathsArr {
binPath := filepath.Join(path, bin)
binAbsPath, err := filepath.Abs(binPath)
if err != nil {
return "", fmt.Errorf("unable to find | absolute path for %s", binPath)
}
if fileutil.IsExecutable(binAbsPath) {
return binAbsPath, nil
}
}
return "", fmt.Errorf("unable to find %q in %q", bin, paths)
} | csn_ccr |
def hpo2(n): return n & (-n)
def lhpo2(n):
q = 0
m = hpo2(n)
while m%2 == 0:
m = m >> 1
q += 1
return q
def nimsum(x,y): return x ^ y
def nimprod(x,y):
if x < 2 or y < 2:
return x * y
h = hpo2(x)
if x > h:
return nimprod(h, y) ^ nimprod(x^h, y)
if hp... | #include <cstdint>
#include <functional>
#include <iomanip>
#include <iostream>
uint32_t hpo2(uint32_t n) {
return n & -n;
}
uint32_t lhpo2(uint32_t n) {
uint32_t q = 0, m = hpo2(n);
for (; m % 2 == 0; m >>= 1, ++q) {}
return q;
}
uint32_t nimsum(uint32_t x, uint32_t y) {
return x ^ y;
}
uin... | codetrans_contest |
Update the user attribute key with the data received from POST.
@param \Concrete\Core\Entity\Attribute\Key\UserKey $key The user attribute key to be updated
@param \Symfony\Component\HttpFoundation\Request $request The request containing the posted data
@return \Concrete\Core\Entity\Attribute\Key\UserKey | protected function saveFromRequest(Key $key, Request $request)
{
$key->setAttributeKeyDisplayedOnProfile((string) $request->request->get('uakProfileDisplay') == 1);
$key->setAttributeKeyEditableOnProfile((string) $request->request->get('uakProfileEdit') == 1);
$key->setAttributeKeyRequiredOn... | csn |
Get the severity at which the message shall be sent.
@param severity
the severity to set
@throws IllegalArgumentException
if the severity is not a valid severity. | public void setSeverity(byte severity) throws IllegalArgumentException {
if (severity < SyslogMessage.SEVERITY_EMERGENCY
|| severity > SyslogMessage.SEVERITY_DEBUG) {
throw new IllegalArgumentException("Not a valid severity.");
}
this.severity = severity;
} | csn |
func (s *SearchService) Indices(indices ...string) *SearchService {
if s.indices == nil {
s.indices = make([]string, 0) |
}
s.indices = append(s.indices, indices...)
return s
} | csn_ccr |
protected boolean prePrepare() {
if (tc.isEntryEnabled())
Tr.entry(tc, "prePrepare");
//
// Cancel timeout prior to completion phase
//
cancelAlarms();
//
| // Inform the Synchronisations we are about to complete
//
if (!_rollbackOnly) {
if (_syncs != null) {
_syncs.distributeBefore();
}
}
if (tc.isEntryEnabled())
Tr.exit(tc, "prePrepare", !_rollbackOnly);
return !_rollbackOnly;
... | csn_ccr |
public function menu(Environment $env, $identifier = '', $template = '_sub_menu.twig', $params = [])
{
$menu = $this->menu->menu($identifier);
$context = [
'name' => $menu->getName(),
| 'menu' => $menu->getItems(),
];
$context += (array) $params;
return $env->render($template, $context);
} | csn_ccr |
// BuildDirectoryTree used by swarmfs_unix | func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) {
uri, err := Parse("bzz:/" + mhash)
if err != nil {
return nil, nil, err
}
addr, err = a.Resolve(ctx, uri.Addr)
if err != nil {
return nil, ... | csn |
protected void indent(Appendable app, int indentLevel) throws IOException {
| for (int i=0; i<indentLevel; i++) {
app.append(' ');
}
} | csn_ccr |
python3 how to correct print out bit data | def pack_bits( longbits ):
"""Crunch a 64-bit int (8 bool bytes) into a bitfield."""
byte = longbits & (0x0101010101010101)
byte = (byte | (byte>>7)) & (0x0003000300030003)
byte = (byte | (byte>>14)) & (0x0000000f0000000f)
byte = (byte | (byte>>28)) & (0x00000000000000ff)
return byte | cosqa |
public function index_onDelete()
{
if (method_exists($this->controller, 'onDelete')) {
return call_user_func_array([$this->controller, 'onDelete'], func_get_args());
}
/*
* Validate checked identifiers
*/
$checkedIds = post('checked');
if (!$ch... | $query->whereIn($model->getKeyName(), $checkedIds);
$this->controller->listExtendQuery($query, $definition);
/*
* Delete records
*/
$records = $query->get();
if ($records->count()) {
foreach ($records as $record) {
$record->delete()... | csn_ccr |
public function parseRestrictedAreas($areas)
{
if (is_string($areas) && !empty($areas))
{
$areas = trim($areas);
$areas = explode(PHP_EOL, $areas);
}
return $this->filterOutArrayValues(
$areas,
function($val) {
| $valid = preg_match('/^[\/\{\}a-z\_\-\?\=]{1,255}$/i', $val);
if (!$valid)
{
return false;
}
return true;
}
);
} | csn_ccr |
// getMessageTimestamp will inspect the `chatResponseFull` to ruturn a timestamp value
// in `chat.postMessage` its under `ts`
// in `chat.postEphemeral` its under `message_ts` | func (c chatResponseFull) getMessageTimestamp() string {
if len(c.Timestamp) > 0 {
return c.Timestamp
}
return c.MessageTimeStamp
} | csn |
function () {
return new Promise(function (resolve, reject) {
var rotations = [];
for (var i = 0; i < spotlightRotations.length; i++) {
var now = new Date();
var daysToAdd = 3 * i;
now.setDate(now.getDate() + daysToAdd);
va... | start.setDate(start.getDate() + (daysUntilNext - 3));
var obj = {
rotation: spotlightRotations[currentSpotlight],
daysUntilNext: daysUntilNext,
startDate: start
};
rotations.push(obj);
}
... | csn_ccr |
set key with value, returns value | def set(key , value)
index = key_index(key)
if( index )
i_values.set(index , value)
else
i_keys.push(key)
i_values.push(value)
end
value
end | csn |
static Object getLCState(StateManagerInternal sm)
{
// unfortunately the LifeCycleState classes are package private.
// so we have to do some dirty reflection hack to access them
try
{
Field myLC = sm.getClass().getDeclaredField("myLC");
myLC.setAccessible(true);
|
return myLC.get(sm);
}
catch (NoSuchFieldException e)
{
return e;
}
catch (IllegalAccessException e)
{
return e;
}
} | csn_ccr |
public function editCategoryGroup($category_group_id = null)
{
$this->setCategoryGroup($category_group_id);
$this->setTitleEditCategoryGroup();
$this->setBreadcrumbEditCategoryGroup();
$this->setData('category_group', $this->data_category_group);
$this->setData('can_delete',... | $this->setData('languages', $this->language->getList(array('enabled' => true)));
$this->setData('category_group_types', $this->category_group->getTypes());
$this->submitEditCategoryGroup();
$this->outputEditCategoryGroup();
} | csn_ccr |
Returns list of plugins of given type in given directory.
@param string $plugintype
@param string $fulldir
@return array | protected static function fetch_plugins($plugintype, $fulldir) {
global $CFG;
$fulldirs = (array)$fulldir;
if ($plugintype === 'theme') {
if (realpath($fulldir) !== realpath($CFG->dirroot.'/theme')) {
// Include themes in standard location too.
array_... | csn |
def observed_vis(self, context):
""" Observed visibility data source """
lrow, urow = MS.row_extents(context)
data = self._manager.ordered_main_table.getcol(
| self._vis_column, startrow=lrow, nrow=urow-lrow)
return data.reshape(context.shape).astype(context.dtype) | csn_ccr |
Creates the Elastic search client service definition.
Will also load support services.
@param string $clientName
@param ContainerBuilder $container
@return Definition | private function createElasticClient($clientName, ContainerBuilder $container)
{
// Storage metadata
$smfName = sprintf('%s.metadata', $clientName);
$definition = new Definition(
Utility::getLibraryClass('Search\Elastic\StorageMetadataFactory')
);
$definition->set... | csn |
public function getToken($tokenId)
{
$tracker = $this->loader->getTracker();
$token | = $tracker->getToken($tokenId);
return $token;
} | csn_ccr |
public static function sendGetRequest($url, array $parameters=array(), $arrayForm=false)
{
if (count($parameters) > 0)
{
$query_string = http_build_query($parameters, '', '&');
$url .= $query_string;
}
# Get cURL resource
$curl = curl_init();
... | CURLOPT_URL => $url,
);
curl_setopt_array($curl, $curlOptions);
# Send the request
$rawResponse = curl_exec($curl);
# Close request to clear up some resources
curl_close($curl);
# Convert to json object.
$resp... | csn_ccr |
Get widget by it's alias defined in module's config.
@param string $alias
@param array $params the constructor parameters
@return Object widget
@throws Exception if the alias not found. | public function getWidget($alias, array $params = [])
{
if (empty($this->_widgets[$alias])) {
throw new Exception("Shared widget '{$alias}' not found in configuration of module " . static::className());
}
$widget = Yii::createObject($this->_widgets[$alias], $params);
retu... | csn |
func (r *runtimeVerbose) Init(from string) {
if r.hasInit {
return
}
r.hasInit = true
r.IsWindows = strings.Index(from, "\\") > -1
r.Gopath = r.determineGoPath(from) |
r.MainFile = from
r.VerboseEnv = os.Getenv("VERBOSE")
r.initVerboseRegexp()
} | csn_ccr |
public function getTable($model)
{
if (false !== $pos = array_search($model, | $this->map)) {
return $pos;
}
return null;
} | csn_ccr |
log an informational message
@param $message | public function logInfo($message, $object = null)
{
$this->doLog(LogHelper::LOG_LEVEL_INFO, $message, $object);
} | csn |
public <T extends IEntity> void findAllAsync(T entity, CallbackHandler callbackHandler) throws FMSException {
//findall is to be called as query
| String query = "SELECT * FROM " + entity.getClass().getSimpleName();
executeQueryAsync(query, callbackHandler);
} | csn_ccr |
def setup_variables(options = {})
@color = (preferred_color || options.delete(:color))
@outline = (preferred_outline || options.delete(:outline))
@width, @height = options.delete(:size)
| @min_value, @max_value = options[:min_value], options[:max_value]
@opacity = options[:opacity] || 1.0
@complexity = options[:complexity]
end | csn_ccr |
Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices. | def cli(env, context_id):
"""Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices.
"""
manager = SoftLayer.IP... | csn |
func (p Protos) SetResourceStatus(resourceID string, rstatus string) error {
statusJSON, err := json.Marshal(&struct {
Status string `json:"status"`
}{
Status: rstatus,
})
if err != nil {
return err
}
url := p.createURL("resource/" + resourceID)
req, err := http.NewRequest("POST", url, | bytes.NewBuffer(statusJSON))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
_, err = p.makeRequest(req)
if err != nil {
return err
}
return nil
} | csn_ccr |
function(elementA, elementB) {
var isSuccessor = false;
this.search(elementA, function(element) {
if (element === elementB && element !== elementA) {
isSuccessor = true;
| return false;
}
}, { outbound: true });
return isSuccessor;
} | csn_ccr |
public function registerEventListeners($model)
{
$activities = $this->config('activities', $model);
foreach ($activities as $activity) {
call_user_func("$model::$activity", function ($instance) | use ($activity) {
$this->{$activity}($instance);
});
}
} | csn_ccr |
def qteMakeAppletActive(self, applet: (QtmacsApplet, str)):
"""
Make ``applet`` visible and give it the focus.
If ``applet`` is not yet visible it will replace the
currently active applet, otherwise only the focus will shift.
The ``applet`` parameter can either be an instance o... | that it
# is actually installed and visible. If it is a conventional
# applet then insert it into the layout.
if self.qteIsMiniApplet(appletObj):
if appletObj is not self._qteMiniApplet:
self.qteLogger.warning('Wrong mini applet. Not activated.')
prin... | csn_ccr |
function sortGroups(selector) {
selector.each((subSelector) => {
subSelector.nodes.sort((a, b) => {
// different types cannot be sorted
if (a.type !== b.type) {
return 0;
}
// | sort alphabetically
return a.value < b.value ? -1 : 1;
});
});
selector.sort((a, b) => (a.nodes.join('') < b.nodes.join('') ? -1 : 1));
} | csn_ccr |
Returns the computed set.
@return the computed set | protected Set<E> set() {
return elements.entrySet()
.stream()
.filter(entry -> !entry.getValue().isTombstone())
.map(entry -> decode(entry.getKey()))
.collect(Collectors.toSet());
} | csn |
cat assigned?
Change the site of this object.
Any of the NON_SITES values will
unset the site
@param new_site[Integer, String] The new site
@return [void] | def site=(new_site)
return nil unless updatable? || creatable?
# unset the site? Use nil or an empty string
if NON_SITES.include? new_site
unset_site
return
end
new_id = JSS::Site.valid_id new_site, api: @api
new_name = JSS::Site.map_all_ids_to(:name, api: @api)[new... | csn |
def clean_dict(dct):
'''Returns a dict where items with a None value are removed'''
return dict((key, | val) for key, val in dct.items() if val is not None) | csn_ccr |
Sends a wheel event for the provided number of clicks. May be negative to reverse
direction. | def wheel(delta=1):
""" Sends a wheel event for the provided number of clicks. May be negative to reverse
direction. """
location = get_position()
e = Quartz.CGEventCreateMouseEvent(
None,
Quartz.kCGEventScrollWheel,
location,
Quartz.kCGMouseButtonLeft)
e2 = Quartz.CG... | csn |
def toimage(self, width=None, height=None):
'''Return the current scene as a PIL Image.
**Example**
You can build your molecular viewer as usual and dump an image
at any resolution supported by the video card (up to the
memory limits)::
v = QtViewer()
... | self.resizeGL(width, height)
else:
width = self.width()
height = self.height()
self.paintGL()
self.post_processing.remove(effect)
coltex = effect.texture
coltex.bind()
glActiveTexture(GL_TEXTURE0)
data = glGetTexImage(GL_TEXTURE_2D, 0, ... | csn_ccr |
// Copy returns a copy of the operator. | func (b *storageDBWrapper) Copy() *storageDBWrapper {
session := b.session.Copy()
coll := b.metaColl.With(session)
db := coll.Database
txnRunner := jujutxn.NewRunner(jujutxn.RunnerParams{
Database: db,
ServerSideTransactions: false,
})
dbWrap := storageDBWrapper{
session: session,
db: ... | csn |
Method for averaging the tensor projection over the unit
with option for custom quadrature.
Args:
quad (dict): quadrature for integration, should be
dictionary with "points" and "weights" keys defaults
to quadpy.sphere.Lebedev(19) as read from file
R... | def average_over_unit_sphere(self, quad=None):
"""
Method for averaging the tensor projection over the unit
with option for custom quadrature.
Args:
quad (dict): quadrature for integration, should be
dictionary with "points" and "weights" keys defaults
... | csn |
def _expand_disk(disk):
'''
Convert the libcloud Volume object into something more serializable.
'''
ret = {}
ret.update(disk.__dict__)
zone = | ret['extra']['zone']
ret['extra']['zone'] = {}
ret['extra']['zone'].update(zone.__dict__)
return ret | csn_ccr |
Generate a list of values to be used like parameters to one method
@param $instance
@param $method
@param $parameters
@param bool $labels
@return array
@throws SimplesRunTimeError | public function resolveMethodParameters($instance, $method, $parameters, $labels = false)
{
// method reflection
$reflectionMethod = new ReflectionMethod($instance, $method);
// resolved array of parameters
return $this->resolveParameters($reflectionMethod->getParameters(), $paramet... | csn |
public function add(navigation_node $node, $beforekey=null) {
global $CFG;
$key = $node->key;
$type = $node->type;
// First check we have a 2nd dimension for this type
if (!array_key_exists($type, $this->orderedcollection)) {
$this->orderedcollection[$type] = array()... | break;
}
}
if ($newindex === $this->count) {
debugging('Navigation node add_before: Reference node not found ' . $beforekey .
', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
}
}
// Ad... | csn_ccr |
Checks whether the command is enabled or not in the current environment.
Override this to check for x or y and return false if the command can not
run properly under the current conditions.
@return bool | public function isEnabled()
{
if (null === $this->enablePdfPreview) {
$this->enablePdfPreview = $this->getContainer()->getParameter('kunstmaan_media.enable_pdf_preview');
}
return $this->enablePdfPreview;
} | csn |
def _chk_hdrgoids(hdrgos):
"""Check that hdrgo set is a set of GO IDs."""
goid = next(iter(hdrgos))
if isinstance(goid, str) and goid[:3] == "GO:":
| return
assert False, "HDRGOS DO NOT CONTAIN GO IDs: {E}".format(E=goid) | csn_ccr |
public function toJson() {
$result = array();
$result['name'] = $this->getName();
$result['hasDefault'] = $this->isDefaultValueAvailable();
try {
if ($result['hasDefault']) {
// In some cases, the call to getDefaultValue can log NOTICES
// in particular if an undefined con... |
}
$result['isArray'] = $this->isArray();
// Let's export only the type if we are in a constructor... in order to save time.
if ($this->getDeclaringFunction()->isConstructor()) {
// TODO: is there a need to instanciate a MoufPropertyDescriptor?
$moufPropertyDescriptor... | csn_ccr |
def _request(self, data):
"""Moved out to make testing easier."""
| return requests.post(self.endpoint, data=data.encode("ascii")).content | csn_ccr |
invalid syntax python slice | def is_full_slice(obj, l):
"""
We have a full length slice.
"""
return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and
obj.step is None) | cosqa |
Create a new Blog or Page.
Route is defined in inherited controllers.
@param Request $request
@return array|Response | protected function newPostAction(Request $request)
{
$entityManager = $this->get('doctrine.orm.entity_manager');
$page = $this->getNewPage();
$form = $this->get('form.factory')->create($this->getNewPageType(), $page);
$form->handleRequest($request);
if ($form->isValid()) {
... | csn |
function clean(test) {
var err = test.err || {};
if (err instanceof Error) {
err = errorJSON(err);
}
return {
title: test.title,
fullTitle: test.fullTitle(),
| duration: test.duration,
currentRetry: test.currentRetry(),
err: cleanCycles(err)
};
} | csn_ccr |
public static double convertToCelsius (TemperatureScale from, double temperature) {
switch(from) {
case FARENHEIT:
return convertFarenheitToCelsius(temperature);
case CELSIUS:
return temperature;
case KELVIN:
return convertKel... | return convertRankineToCelsius(temperature);
default:
throw(new RuntimeException("Invalid termpature conversion"));
}
} | csn_ccr |
def get_init(self):
"""Return initial name.
"""
suffix = self._separator + "%s" % | str(self._counter_init)
return self._base_name + suffix | csn_ccr |
Create a results row for this application. | def _get_generic_two_antidep_episodes_result(
rowdata: Tuple[Any, ...] = None) -> DataFrame:
"""
Create a results row for this application.
"""
# Valid data types... see:
# - pandas.core.dtypes.common.pandas_dtype
# - https://pandas.pydata.org/pandas-docs/stable/timeseries.html
# - h... | csn |
def _pidgin_status(status, message):
""" Updates status and message for Pidgin IM application.
`status`
Status type.
`message`
Status message.
"""
try:
iface = _dbus_get_interface('im.pidgin.purple.PurpleService',
'/im... | code = PIDGIN_CODE_MAP[status]
saved_status = iface.PurpleSavedstatusNew('', code)
# set the message, if provided
iface.PurpleSavedstatusSetMessage(saved_status, message)
# activate status
iface.PurpleSavedstatusActivate(saved_status)
except dbus.e... | csn_ccr |
func (t *Table) GetSelection() (row, column int) {
| return t.selectedRow, t.selectedColumn
} | csn_ccr |
public function getInstance($alias = null)
{
if (!$alias && !$this->mainAlias) {
$namespace = explode('\\', $this->_entityName);
$alias = strtolower(end($namespace));
$this->mainAlias = $alias;
} elseif ($alias) {
| $this->mainAlias = $alias;
}
return $this->qb ? $this->qb : $this->qb = $this->createQueryBuilder($this->mainAlias);
} | csn_ccr |
public function pushCriteria($criteria)
{
if (is_string($criteria)) {
$criteria = new $criteria;
}
if (!$criteria instanceof CriteriaInterface) {
throw new RepositoryException("Class " . | get_class($criteria) . " must be an instance of Prettus\\Repository\\Contracts\\CriteriaInterface");
}
$this->criteria->push($criteria);
return $this;
} | csn_ccr |
Register collection of WordPress conditions.
@return void | public function registerWordPressConditions()
{
$this->app->singleton('wpconditions', function ($app) {
return new WordpressConditions;
});
$this->app->alias('wpconditions', WordpressConditions::class);
} | csn |
finding unique lists in python | def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for i, e in enumerate(L) if L.index(e) == i] | cosqa |
can you chain if tags in python | def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = el.name
return name in self.break_tags or name in self.user_break_tags | cosqa |
def run_census(flags_obj, ctx):
"""Construct all necessary functions and call run_loop.
Args:
flags_obj: Object containing user specified flags.
"""
train_file = os.path.join(flags_obj.data_dir, census_dataset.TRAINING_FILE)
test_file = os.path.join(flags_obj.data_dir, census_dataset.EVAL_FILE)
# Trai... |
for k, v in tensors_to_log.items()}
train_hooks = hooks_helper.get_train_hooks(
flags_obj.hooks, model_dir=flags_obj.model_dir,
batch_size=flags_obj.batch_size, tensors_to_log=tensors_to_log)
# Note: this will only be invoked once, so `--epochs_between_evals` is now effectively `--... | csn_ccr |
Return a collection of files
@param mixed $resources Absolute file or directory path or an array of both
@param string $extension File extension to load/filter with the prefixed dot (.php, .yml)
@throws InvalidArgumentException If resources aren't absolute dir or file path
@return array | public function load($resources, $extension = '')
{
$finder = new Finder();
$collection = array();
if (is_array($resources)) {
foreach ($resources as $resource) {
$subcollection = array();
$subcollection = $this->load($resource);
$... | csn |
// IsMaster reports whether the connected machine
// agent lives at the same network address as the primary
// mongo server for the replica set.
// This call will return an error if the connected
// agent is not a machine agent with model-manager
// privileges. | func (st *State) IsMaster() (bool, error) {
var results params.IsMasterResult
err := st.facade.FacadeCall("IsMaster", nil, &results)
return results.Master, err
} | csn |
def master2model(model_params:Sequence[Tensor], master_params:Sequence[Tensor], flat_master:bool=False)->None:
"Copy `master_params` to `model_params`."
if flat_master:
for model_group,master_group in zip(model_params,master_params):
if len(model_group) != 0:
for model, maste... | _unflatten_dense_tensors(master_group[0].data, model_group)):
model.data.copy_(master)
else:
for model_group,master_group in zip(model_params,master_params):
for model, master in zip(model_group, master_group): model.data.copy_(master.data) | csn_ccr |
Deletes obsolete deployment directories | public function cleanup()
{
$this->log('cleanup', LOG_DEBUG);
$past_deployments = array();
if (is_array($this->remote_host))
{
foreach ($this->remote_host as $remote_host)
{
if ($past_dirs = $this->collectPastDeployments($remote_host, $this->remote_dir))
{
$past_deployments[] = array(
... | csn |
Add an LED that's part of this keypad. | def add_led(self, led):
"""Add an LED that's part of this keypad."""
self._leds.append(led)
self._components[led.component_number] = led | csn |
Move all FlexForm data of current record to conf array | public function moveFlexFormDataToConf()
{
// don't move this to init
$this->pi_initPIflexForm();
$piFlexForm = $this->cObj->data['pi_flexform'];
if (is_array($piFlexForm['data'])) {
foreach ($piFlexForm['data'] as $sheetKey => $sheet) {
foreach ($sheet a... | csn |
Get defaultDomain.
@return string | public function getDefaultDomain()
{
if ($this->defaultDomain) {
return $this->defaultDomain;
} elseif ($first = $this->getDomains()->first()) {
return $first->getDomain();
} else {
return null;
}
} | csn |
def dataflow_to_dataset(df, types):
"""
Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
... | """
# TODO theoretically it can support dict
assert isinstance(df, DataFlow), df
assert isinstance(types, (list, tuple)), types
df = MapData(df, lambda dp: tuple(dp))
df.reset_state()
ds = tf.data.Dataset.from_generator(
df.get_data, tuple(types))
ret... | csn_ccr |
func assignValueStringSlice(params map[string]interface{}, name string, out *[]string) error {
if raw, ok := params[name]; ok {
var tmp []string
switch raw.(type) {
case string:
tmp = make([]string, 1, 1)
tmp[0] = raw.(string)
case []string:
l := len(raw.([]string))
tmp = make([]string, l, l)
co... | if s, ok := v.(string); ok {
tmp[i] = s
} else {
return fmt.Errorf("Index %d of %s expected to be string", i, name)
}
}
default:
return fmt.Errorf("Expecting %s to be a string or []string", name)
}
*out = tmp
delete(params, name)
}
return nil
} | csn_ccr |
value associated with the given key in subtree rooted at x; null if no such key | private Node<T> get(Node<T> x, long key) {
while (x != null) {
if (x.value == key) return x;
if (key < x.value) x = x.left;
else x = x.right;
}
return null;
} | csn |
Get the values of all attributes in a hash
The returned hash has the form
<code>array('attributename' => 'single value',
'attributename' => array('value1', value2', value3'))</code>
Only attributes present at the entry will be returned.
@access public
@return array Hash of all attributes with their values | public function getValues()
{
$attrs = array();
foreach ($this->_attributes as $attr => $value) {
$attrs[$attr] = $this->getValue($attr);
}
return $attrs;
} | csn |
Takes the screen capture of the designated area. If no dimensions are specified, it will take
a screenshot of the full screen by default. | public void take() throws AWTException {
Rectangle area = new Rectangle(dimensions);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(area);
data = getByteArray(image);
} | csn |
def strids2ids(tokens: Iterable[str]) -> List[int]:
"""
Returns sequence of integer ids given a | sequence of string ids.
:param tokens: List of integer tokens.
:return: List of word ids.
"""
return list(map(int, tokens)) | csn_ccr |
Sets the width of the bottom sheet, the items, which are displayed by the adapter, belong
to.
@param width
The width, which should be set, as an {@link Integer} value | public final void setWidth(final int width) {
if (style == Style.LIST_COLUMNS && (getDeviceType(context) == DeviceType.TABLET ||
getOrientation(context) == Orientation.LANDSCAPE)) {
columnCount = 2;
} else if (style == Style.GRID) {
int padding = context.getResour... | csn |
Adds extra information that is suffixed to the original exception message.
@param string $hint | public function addHint($hint)
{
if (!$this->containsHints) {
$this->message .= "\nHint: ".$hint;
$this->containsHints = true;
} else {
$this->message .= ', '.$hint;
}
} | csn |
// Limit generate LIMIT start, limit statement | func (statement *Statement) Limit(limit int, start ...int) *Statement {
statement.LimitN = limit
if len(start) > 0 {
statement.Start = start[0]
}
return statement
} | csn |
// Formatting function used to implement the %minute% code. | func ioOutputFormatMinute(ld *LineData, b *bytes.Buffer) error {
_, err := b.WriteString(fmt.Sprintf("%02d", ld.TimeStamp.Minute()))
return err
} | csn |
public function get(array $queryParams = [])
{
$response = $this->client->get("{$this->uri()}", [
'query' => $queryParams,
| ]);
return $this->handleResponse($response);
} | csn_ccr |
func (self *Operation) Cancel(id int64) (bool, error) {
var res bool
// params := Params{Params: []interface{}{self.Key, id}}
params := []interface{}{self.Key, id}
if err | := self.Call("operation.cancel", params, &res); err != nil {
return false, err
}
return res, nil
} | csn_ccr |
Processes the country's address format definition.
@param string $countryCode The country code.
@param array $definition The definition.
@return array The processed definition. | protected function processDefinition($countryCode, array $definition)
{
$definition['country_code'] = $countryCode;
// Merge-in defaults.
$definition += $this->getGenericDefinition();
// Always require the given name and family name.
$definition['required_fields'][] = Address... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.