comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_
:arg policy: The name of the index lifecycle policy
|
def delete_lifecycle(self, policy=None, params=None):
return self.transport.perform_request(
"DELETE", _make_path("_ilm", "policy", policy), params=params
)
|
// SetSourceUrl sets the SourceUrl field's value.
|
func (s *ThreatIntelIndicator) SetSourceUrl(v string) *ThreatIntelIndicator {
s.SourceUrl = &v
return s
}
|
upload file or files
@param array $options
@return array|boolean
|
protected function uploadFile($options)
{
if ( $options['type'] === 'file' ) {
$this->repo = new FileRepository($options);
$this->hasFile = true;
} else {
$this->repo = new ImageRepository($options);
$this->hasPhoto = true;
}
if ( ! $this->repo->upload($this->model, $this->request) ) {
return false;
}
return $this->repo->getDatas($this->request);
}
|
Initializes the type given the string value of the type.<p>
@param type a string representation of the type
@return the actual type object
|
private static I_Loader initLoader(String type) {
if (TYPE_PROPERTIES.equals(type)) {
return new CmsVfsBundleLoaderProperties();
} else if (TYPE_XML.equals(type)) {
return new CmsVfsBundleLoaderXml();
} else {
return new CmsVfsBundleLoaderXml();
}
}
|
Little hack to make <input> can perform waves effect
|
function (elements) {
for (var a = 0; a < elements.length; a++) {
var el = elements[a];
if (el.tagName.toLowerCase() === 'input') {
var parent = el.parentNode;
// If input already have parent just pass through
if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) {
continue;
}
// Put element class and style to the specified parent
var wrapper = document.createElement('i');
wrapper.className = el.className + ' waves-input-wrapper';
var elementStyle = el.getAttribute('style');
if (!elementStyle) {
elementStyle = '';
}
wrapper.setAttribute('style', elementStyle);
el.className = 'waves-button-input';
el.removeAttribute('style');
// Put element as child
parent.replaceChild(wrapper, el);
wrapper.appendChild(el);
}
}
}
|
Create a new file parameter
:param help_string:
:param default:
:param suffixes:
:return:
|
def create_new_file(help_string=NO_HELP, default=NO_DEFAULT, suffixes=None):
# type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str
# noinspection PyTypeChecker
return ParamFilename(
help_string=help_string,
default=default,
type_name="new_file",
suffixes=suffixes,
)
|
Get existing validation records.
|
def _get_existing(driver, zone_name, server_name, validation):
if zone_name is None:
zones = sorted(
(z for z
in driver.list_zones()
if server_name.rstrip(u'.')
.endswith(u'.' + z.domain.rstrip(u'.'))),
key=lambda z: len(z.domain),
reverse=True)
if len(zones) == 0:
raise NotInZone(server_name=server_name, zone_name=None)
else:
zones = [
z for z
in driver.list_zones()
if z.domain == zone_name]
if len(zones) == 0:
raise ZoneNotFound(zone_name=zone_name)
zone = zones[0]
subdomain = _split_zone(server_name, zone.domain)
existing = [
record for record
in zone.list_records()
if record.name == subdomain and
record.type == 'TXT' and
record.data == validation]
return zone, existing, subdomain
|
Invokes the given merge operation.
@param serviceName the service name
@param operation the merge operation
@param partitionId the partition ID of the operation
|
protected void invoke(String serviceName, Operation operation, int partitionId) {
try {
operationCount++;
operationService
.invokeOnPartition(serviceName, operation, partitionId)
.andThen(mergeCallback);
} catch (Throwable t) {
throw rethrow(t);
}
}
|
// RemovePermissionWithContext mocks base method
|
func (m *MockLambdaAPI) RemovePermissionWithContext(arg0 aws.Context, arg1 *lambda.RemovePermissionInput, arg2 ...request.Option) (*lambda.RemovePermissionOutput, error) {
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "RemovePermissionWithContext", varargs...)
ret0, _ := ret[0].(*lambda.RemovePermissionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
|
// Get a single role by name
|
func (rs *RoleService) Get(ctx context.Context, roleName string) (r *Role, resp *APIResponse, err error) {
r = &Role{}
_, resp, err = rs.client.getAction(ctx, &APIClientRequest{
APIVersion: apiV1,
Path: fmt.Sprintf("admin/security/roles/%s", roleName),
ResponseBody: r,
})
return
}
|
// NewIndexWriter returns a new IndexWriter.
|
func NewIndexWriter() IndexWriter {
buf := bytes.NewBuffer(make([]byte, 0, 1024*1024))
return &directIndex{buf: buf, w: bufio.NewWriter(buf)}
}
|
Render output from given statistics.
@param ProjectStatistics $statistics
@return void
|
public function render(ProjectStatistics $statistics)
{
$table = new Table($this->output);
$table
->setHeaders(['Name', 'Classes', 'Methods', 'Methods/Class', 'Lines', 'LoC', 'LoC/Method'])
->setRows($statistics->components())
->addRow($statistics->other())
->addRow(new TableSeparator)
->addRow($statistics->total());
for ($i = 1; $i <= 6; $i++) {
$table->setColumnStyle($i, (new TableStyle)->setPadType(STR_PAD_LEFT));
}
$table->render();
$metaData = array_merge(
(new CodeTestRatio($statistics))->summary(),
['Number of Routes: '.app(NumberOfRoutes::class)->get()]
);
$this->output->text(
implode(' ', $metaData)
);
}
|
Is this table a m:n pivot table?
@param bool $newStatus The new status.
@return bool The old status.
|
public function isPivotTable($newStatus = false)
{
$oldStatus = $this->isPivotTable;
if (func_num_args()) {
$this->isPivotTable = $newStatus;
} // if
return $oldStatus;
}
|
/*
(non-Javadoc)
@see org.protempa.proposition.TemporalProposition#isEqual(java.lang.Object)
|
@Override
public boolean isEqual(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TemporalParameter)) {
return false;
}
TemporalParameter p = (TemporalParameter) o;
return super.isEqual(p)
&& (this.value == p.value
|| (this.value != null && this.value.equals(p.value)));
}
|
Removes all active facets from the request.
@return SearchRequest
|
public function removeAllFacets()
{
$path = $this->prefixWithNamespace('filter');
$this->argumentsAccessor->reset($path);
$this->stateChanged = true;
return $this;
}
|
Parses the authorization header for a basic authentication.
@param string $header
@return false|array
|
private static function parseAuthorizationHeader($header)
{
if (strpos($header, 'Digest') !== 0) {
return false;
}
$needed_parts = ['nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1];
$data = [];
preg_match_all('@('.implode('|', array_keys($needed_parts)).')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', substr($header, 7), $matches, PREG_SET_ORDER);
if ($matches) {
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
}
return empty($needed_parts) ? $data : false;
}
|
All CloudFormation states listed here: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html
|
def exit_unless_updateable!
stack_name = Jets::Naming.parent_stack_name
exists = stack_exists?(stack_name)
return unless exists # continue because stack could be updating
stack = cfn.describe_stacks(stack_name: stack_name).stacks.first
status = stack["stack_status"]
if status =~ /^ROLLBACK_/ ||
status =~ /_IN_PROGRESS$/
region = `aws configure get region`.strip rescue "us-east-1"
url = "https://console.aws.amazon.com/cloudformation/home?region=#{region}#/stacks"
puts "The parent stack of the #{Jets.config.project_name.color(:green)} project is not in an updateable state."
puts "Stack name #{stack_name.color(:yellow)} status #{stack["stack_status"].color(:yellow)}"
puts "Here's the CloudFormation url to check for more details #{url}"
exit 1
end
end
|
Returns the order in which the given node's children should be evaluated.
<p>In most cases, this is EvaluationDirection.FORWARD because the AST order matches the actual
evaluation order. A few nodes require reversed evaluation instead.
|
private static EvaluationDirection getEvaluationDirection(Node node) {
switch (node.getToken()) {
case DESTRUCTURING_LHS:
case ASSIGN:
case DEFAULT_VALUE:
if (node.getFirstChild().isDestructuringPattern()) {
// The lhs of a destructuring assignment is evaluated AFTER the rhs. This is only true for
// destructuring, though, not assignments like "first().x = second()" where "first()" is
// evaluated first.
return EvaluationDirection.REVERSE;
}
// fall through
default:
return EvaluationDirection.FORWARD;
}
}
|
----- helper methods ----------------------------------------------------
|
@VisibleForTesting
public static List<IStruct> getAllTraits(IReferenceableInstance entityDefinition,
TypeSystem typeSystem) throws AtlasException {
List<IStruct> traitInfo = new LinkedList<>();
for (String traitName : entityDefinition.getTraits()) {
IStruct trait = entityDefinition.getTrait(traitName);
String typeName = trait.getTypeName();
Map<String, Object> valuesMap = trait.getValuesMap();
traitInfo.add(new Struct(typeName, valuesMap));
traitInfo.addAll(getSuperTraits(typeName, valuesMap, typeSystem));
}
return traitInfo;
}
|
Calculate and update which pages are visible,
possibly updating CSS classes on the pages
@param {boolean} updateClasses Wheter to update page CSS classes as well
@returns {void}
|
function (updateClasses) {
var i, len, $page,
state = this.state,
visibleRange = this.calculateVisibleRange(),
fullyVisibleRange = this.calculateFullyVisibleRange();
state.visiblePages.length = 0;
state.fullyVisiblePages.length = 0;
for (i = 0, len = this.$pages.length; i < len; ++i) {
$page = this.$pages.eq(i);
if (i < visibleRange.min || i > visibleRange.max) {
if (updateClasses && $page.hasClass(CSS_CLASS_PAGE_VISIBLE)) {
$page.removeClass(CSS_CLASS_PAGE_VISIBLE);
}
} else {
if (updateClasses && !$page.hasClass(CSS_CLASS_PAGE_VISIBLE)) {
$page.addClass(CSS_CLASS_PAGE_VISIBLE);
}
state.visiblePages.push(i + 1);
}
if (i >= fullyVisibleRange.min && i <= fullyVisibleRange.max) {
state.fullyVisiblePages.push(i + 1);
}
}
}
|
Builds a Request. All parameters must be effectively immutable, via safe copies.
@param httpMethod for the request.
@param url for the request.
@param headers to include.
@param body of the request, can be {@literal null}
@return a Request
|
public static Request create(HttpMethod httpMethod,
String url,
Map<String, Collection<String>> headers,
Body body) {
return new Request(httpMethod, url, headers, body);
}
|
// SetEventSubscription sets the EventSubscription field's value.
|
func (s *RemoveSourceIdentifierFromSubscriptionOutput) SetEventSubscription(v *EventSubscription) *RemoveSourceIdentifierFromSubscriptionOutput {
s.EventSubscription = v
return s
}
|
Returns SQL to define the table.
|
def ddl(self, dialect=None, creates=True, drops=True):
dialect = self._dialect(dialect)
creator = CreateTable(self.table).compile(mock_engines[dialect])
creator = "\n".join(l for l in str(creator).splitlines() if l.strip()) # remove empty lines
comments = "\n\n".join(self._comment_wrapper.fill("in %s: %s" %
(col, self.comments[col]))
for col in self.comments)
result = []
if drops:
result.append(self._dropper(dialect) + ';')
if creates:
result.append("%s;\n%s" % (creator, comments))
for child in self.children.values():
result.append(child.ddl(dialect=dialect, creates=creates,
drops=drops))
return '\n\n'.join(result)
|
// ChatAttachmentUploadStart implements the chat1.NotifyChatInterface
// for ChatRPC.
|
func (c *ChatRPC) ChatAttachmentUploadStart(
_ context.Context, _ chat1.ChatAttachmentUploadStartArg) error {
return nil
}
|
// Complete is an event fired when a transaction successfully completed.
//
// https://developer.mozilla.org/docs/Web/Reference/Events/complete_indexedDB
|
func Complete(listener func(*vecty.Event)) *vecty.EventListener {
return &vecty.EventListener{Name: "complete", Listener: listener}
}
|
注册前置分发器.
@param IURLPreDispatcher $dispatcher
@param int $index
|
public function registerPreDispatcher(IURLPreDispatcher $dispatcher, $index = 10) {
$this->preDispatchers [ $index ] [] = $dispatcher;
ksort($this->preDispatchers, SORT_NUMERIC);
}
|
Get the report summary.
@return string[]
|
public function getSummary()
{
$summary = [];
$name = $this->getName();
$message = $this->getMessage();
if ($name !== $message) {
$summary['name'] = $name;
}
$summary['message'] = $message;
$summary['severity'] = $this->getSeverity();
return array_filter($summary);
}
|
// WarnConstraintAliases shows a warning to the user that they have used an
// alias for a constraint that might go away sometime.
|
func WarnConstraintAliases(ctx *cmd.Context, aliases map[string]string) {
for alias, canonical := range aliases {
ctx.Infof("Warning: constraint %q is deprecated in favor of %q.\n", alias, canonical)
}
}
|
Return the Pauli sigma_Z operator acting on the given qubit
|
def sZ(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
""""""
return Pauli.sigma(qubit, 'Z', coefficient)
|
Check resource.
@return Result
|
public function check()
{
foreach ($this->target->paths as $path) {
if (! $this->getFilesystem()->isWritable($path)) {
return $this->makeResult(
false,
sprintf($this->target->getErrorMessage(), $path)
);
}
}
return $this->makeHealthyResult();
}
|
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated
|
@SuppressWarnings("unchecked")
@Override
public EList<IfcAppliedValue> getBaseCosts() {
return (EList<IfcAppliedValue>) eGet(Ifc4Package.Literals.IFC_CONSTRUCTION_RESOURCE__BASE_COSTS, true);
}
|
Retrieve Bad Player Stats
@access public
@return object JSON
|
public function retrieveBadPlayerStats ()
{
$data = file_get_contents("http://battlefield.play4free.com/en/profile/stats/" .$this->_profileID. "/" .$this->_soldierID. "?g=[%22BadPlayerStats%22]");
$badPlayerStats = json_decode($data);
return $badPlayerStats;
}
|
// AddToUserAgent adds an extension to the current user agent
|
func (c *Client) AddToUserAgent(extension string) error {
if extension != "" {
c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension)
return nil
}
return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent)
}
|
@param $name
@return mixed
|
final public function &__get($name)
{
$value = $this->data[$name];
//Apply accessor
$this->applyModifier($name, $value, 'get');
return $value;
}
|
Returns the array of channel ids for the policy.
@return The array of channel ids
|
public long[] getChannelIdArray()
{
long[] ret = new long[channelIds.size()];
for(int i = 0; i < channelIds.size(); i++)
ret[i] = channelIds.get(i);
return ret;
}
|
Returns whether the keypath resolution should propagate to children. Some keypaths resolve
to content other than leaf contents (such as a layer or content group transform) so sometimes
this will return false.
|
@SuppressWarnings("SimplifiableIfStatement")
@RestrictTo(RestrictTo.Scope.LIBRARY)
public boolean propagateToChildren(String key, int depth) {
if ("__container".equals(key)) {
return true;
}
return depth < keys.size() - 1 || keys.get(depth).equals("**");
}
|
// NewRef returns a new membership reference
|
func NewRef(refresh time.Duration, context Context, chConfigRef *lazyref.Reference) *Ref {
ref := &Ref{
chConfigRef: chConfigRef,
context: context,
}
ref.Reference = lazyref.New(
ref.initializer(),
lazyref.WithRefreshInterval(lazyref.InitImmediately, refresh),
)
return ref
}
|
// Fatalf returns an error that will cause mage to print out the
// given message and exit with the given exit code.
|
func Fatalf(code int, format string, args ...interface{}) error {
return fatalErr{
code: code,
error: fmt.Errorf(format, args...),
}
}
|
Get the select columns for the relation query.
@param array $columns
@return \Mellivora\Database\Eloquent\Relations\BelongsToMany
|
protected function shouldSelect(array $columns = ['*'])
{
if ($columns === ['*']) {
$columns = [$this->related->getTable() . '.*'];
}
return array_merge($columns, $this->aliasedPivotColumns());
}
|
Computes the volume of this SpatialComparable.
@param box Box
@param scale Scaling factor
@return the volume of this SpatialComparable
|
public static double volumeScaled(SpatialComparable box, double scale) {
final int dim = box.getDimensionality();
double vol = 1.;
for(int i = 0; i < dim; i++) {
double delta = box.getMax(i) - box.getMin(i);
if(delta == 0.) {
return 0.;
}
vol *= delta * scale;
}
return vol;
}
|
Build a result set keyed by PK.
@param array $results
@param string. $primaryKey
@return array
|
protected function buildKeyedResultSet(array $results, string $primaryKey) : array
{
$builder = new EntityBuilder($this->mapper, array_keys($this->eagerLoads), $this->useCache);
$keys = array_map(function ($item) use ($primaryKey) {
return $item[$primaryKey];
}, $results);
return array_combine($keys, array_map(function ($item) use ($builder) {
return $builder->build($item);
}, $results));
}
|
This method is the same as the other processAuthChallenge() without the user/password option.
|
public Request processAuthChallenge(Response response, Request req_msg) {
return processAuthChallenge(response, req_msg, null, null);
}
|
{@inheritdoc}
@param int $bufferSize
@throws \RuntimeException
|
public function emit(ResponseInterface $response, int $bufferSize = 4096){
while(0 < ob_get_level()){
ob_end_flush();
}
if(!headers_sent($file, $line)){
$this->emitHttpStatus($response);
$this->emitHeaders($response);
}
if(0 < $response->getBody()->getSize()){
$this->emitBody($response, $bufferSize);
}
}
|
Fixes for various DOM errors that MAL commits.
Yes, I know this is a cardinal sin, but there's really no elegant way to fix this.
|
def fix_bad_html(html):
# on anime list pages, sometimes tds won't be properly opened.
html = re.sub(r'[\s]td class=', "<td class=", html)
# on anime list pages, if the user doesn't specify progress, MAL will try to close a span it didn't open.
def anime_list_closing_span(match):
return match.group(u'count') + '/' + match.group(u'total') + '</td>'
html = re.sub(r'(?P<count>[0-9\-]+)</span>/(?P<total>[0-9\-]+)</a></span></td>', anime_list_closing_span, html)
# on anime info pages, under rating, there's an extra </div> by the "licensing company" note.
html = html.replace('<small>L</small></sup><small> represents licensing company</small></div>', '<small>L</small></sup><small> represents licensing company</small>')
# on manga character pages, sometimes the character info column will have an extra </div>.
def manga_character_double_closed_div_picture(match):
return "<td " + match.group(u'td_tag') + ">\n\t\t\t<div " + match.group(u'div_tag') + "><a " + match.group(u'a_tag') + "><img " + match.group(u'img_tag') + "></a></div>\n\t\t\t</td>"
html = re.sub(r"""<td (?P<td_tag>[^>]+)>\n\t\t\t<div (?P<div_tag>[^>]+)><a (?P<a_tag>[^>]+)><img (?P<img_tag>[^>]+)></a></div>\n\t\t\t</div>\n\t\t\t</td>""", manga_character_double_closed_div_picture, html)
def manga_character_double_closed_div_character(match):
return """<a href="/character/""" + match.group(u'char_link') + """">""" + match.group(u'char_name') + """</a>\n\t\t\t<div class="spaceit_pad"><small>""" + match.group(u'role') + """</small></div>"""
html = re.sub(r"""<a href="/character/(?P<char_link>[^"]+)">(?P<char_name>[^<]+)</a>\n\t\t\t<div class="spaceit_pad"><small>(?P<role>[A-Za-z ]+)</small></div>\n\t\t\t</div>""", manga_character_double_closed_div_character, html)
return html
|
deletes the entry for the key & parameter from the store.
|
def delete(key, parameters = {})
@stores.map {|s| s.delete(key, parameters)}.any?
end
|
Print the result, ascii encode if necessary
|
def print_result(result):
""""""
try:
print result
except UnicodeEncodeError:
if sys.stdout.encoding:
print result.encode(sys.stdout.encoding, 'replace')
else:
print result.encode('utf8')
except:
print "Unexpected error attempting to print result"
|
Bind an extra variable to the view with the given variable id. The same instance will be
provided to all views the binding is bound to.
|
@NonNull
public final ItemBinding<T> bindExtra(int variableId, Object value) {
if (extraBindings == null) {
extraBindings = new SparseArray<>(1);
}
extraBindings.put(variableId, value);
return this;
}
|
// SetText sets the text content of the entry.
|
func (e *Entry) SetText(text string) {
e.text.Set([]rune(text))
// TODO: Enable when RuneBuf supports cursor movement for CJK.
// e.ensureCursorIsVisible()
e.offset = 0
}
|
// ListenAndServe listens on the TCP network address addr and then calls Serve
// with handler to handle sessions on incoming connections. Handler is typically
// nil, in which case the DefaultHandler is used.
|
func ListenAndServe(addr string, handler Handler, options ...Option) error {
srv := &Server{Addr: addr, Handler: handler}
for _, option := range options {
if err := srv.SetOption(option); err != nil {
return err
}
}
return srv.ListenAndServe()
}
|
Find actual default data source name.
<p>If use master-slave rule, return master data source name.</p>
@return actual default data source name
|
public Optional<String> findActualDefaultDataSourceName() {
String defaultDataSourceName = shardingDataSourceNames.getDefaultDataSourceName();
if (Strings.isNullOrEmpty(defaultDataSourceName)) {
return Optional.absent();
}
Optional<String> masterDefaultDataSourceName = findMasterDataSourceName(defaultDataSourceName);
return masterDefaultDataSourceName.isPresent() ? masterDefaultDataSourceName : Optional.of(defaultDataSourceName);
}
|
Process the text
@param source the sourcetext
@return the result of text processing
@see TextProcessor#process(CharSequence)
|
public CharSequence process(CharSequence source) {
if (source != null && source.length() > 0) {
String stringSource = source instanceof String ? (String) source : source.toString();
// Array to cache founded indexes of sequences
int[] indexes = new int[escape.length];
Arrays.fill(indexes, -1);
int length = source.length();
int offset = 0;
StringBuilder result = new StringBuilder(length);
while (offset < length) {
// Find next escape sequence
int escPosition = -1;
int escIndex = -1;
for (int i = 0; i < escape.length; i++) {
int index;
if (indexes[i] < offset) {
index = stringSource.indexOf(escape[i][0], offset);
indexes[i] = index;
} else {
index = indexes[i];
}
if (index >= 0 && (index < escPosition || escPosition < 0)) {
escPosition = index;
escIndex = i;
}
}
// If escape sequence is found
if (escPosition >= 0) {
// replace chars before escape sequence
result.append(stringSource, offset, escPosition);
// Replace sequence
result.append(escape[escIndex][1]);
offset = escPosition + escape[escIndex][0].length();
} else {
// Put other string to result sequence
result.append(stringSource, offset, length);
offset = length;
}
}
return result;
} else {
return new StringBuilder(0);
}
}
|
Determine if the browser is Maxthon or not, add by BugBuster
@return boolean True if the browser is Maxthon otherwise false
|
protected function checkBrowserMaxthon() {
if( stripos($this->_agent,'Maxthon') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Maxthon'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_COOL_MAXTHON);
return true;
}
return false;
}
|
update the chart function
|
function UpdateChartData()
{
while(Points > 10)
{
Points -= 1;
myLineChart.removeData();
}
myLineChart.addData([Data["Temperature"]], Math.floor((Date.now() - StartTime) / 1000.0));
myLineChart.update();
Points+=1;
}
|
// Draw implements the Drawable interface.
|
func (self *Block) Draw(buf *Buffer) {
if self.Border {
self.drawBorder(buf)
}
buf.SetString(
self.Title,
self.TitleStyle,
image.Pt(self.Min.X+2, self.Min.Y),
)
}
|
Build the menu structure.
@return mixed
|
public function getItemProviders()
{
foreach ($this->modules->enabled() as $module) {
$name = studly_case($module->getName());
$class = 'Modules\\'.$name.'\\MenuExtenders\\MenuExtender';
if (class_exists($class)) {
$extender = $this->container->make($class);
$this->extenders->put($module->getName(), [
'content' => $extender->getContentItems(),
'static' => $extender->getStaticItems(),
]);
}
}
return $this->extenders;
}
|
Auto Generated Code
|
def show_vcs_output_vcs_nodes_vcs_node_info_node_public_ip_addresses_node_public_ip_address(self, **kwargs):
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_nodes = ET.SubElement(output, "vcs-nodes")
vcs_node_info = ET.SubElement(vcs_nodes, "vcs-node-info")
node_public_ip_addresses = ET.SubElement(vcs_node_info, "node-public-ip-addresses")
node_public_ip_address = ET.SubElement(node_public_ip_addresses, "node-public-ip-address")
node_public_ip_address.text = kwargs.pop('node_public_ip_address')
callback = kwargs.pop('callback', self._callback)
return callback(config)
|
Put CHAP-MD5 specific attributes
For authenticating using CHAP-MD5 via RADIUS you have to put the challenge
and the response. The chapid is inserted in the first byte of the response.
@return void
|
function putAuthAttributes()
{
if (isset($this->username)) {
$this->putAttribute(RADIUS_USER_NAME, $this->username);
}
if (isset($this->response)) {
$response = pack('C', $this->chapid) . $this->response;
$this->putAttribute(RADIUS_CHAP_PASSWORD, $response);
}
if (isset($this->challenge)) {
$this->putAttribute(RADIUS_CHAP_CHALLENGE, $this->challenge);
}
}
|
Update the Group memberships for the given users state
:param user: User to update for
:param state: State to update user for
:return:
|
def update_groups_for_user(self, user: User, state: State = None):
if state is None:
state = user.profile.state
for config in self.filter(states=state):
# grant user new groups for their state
config.update_group_membership_for_user(user)
for config in self.exclude(states=state):
# ensure user does not have groups from previous state
config.remove_user_from_alliance_groups(user)
config.remove_user_from_corp_groups(user)
|
Initialize this manager.
|
void startInternal() throws LifecycleException {
_log.info( getClass().getSimpleName() + " starts initialization... (configured" +
" nodes definition " + _memcachedNodes + ", failover nodes " + _failoverNodes + ")" );
_statistics = Statistics.create( _enableStatistics );
_memcachedNodesManager = createMemcachedNodesManager( _memcachedNodes, _failoverNodes);
if(_storage == null) {
_storage = createStorageClient( _memcachedNodesManager, _statistics );
}
final String sessionCookieName = _manager.getSessionCookieName();
_currentRequest = new CurrentRequest();
_trackingHostValve = createRequestTrackingHostValve(sessionCookieName, _currentRequest);
final Context context = _manager.getContext();
context.getParent().getPipeline().addValve(_trackingHostValve);
_trackingContextValve = createRequestTrackingContextValve(sessionCookieName);
context.getPipeline().addValve( _trackingContextValve );
initNonStickyLockingMode( _memcachedNodesManager );
_transcoderService = createTranscoderService( _statistics );
_backupSessionService = new BackupSessionService( _transcoderService, _sessionBackupAsync, _sessionBackupTimeout,
_backupThreadCount, _storage, _memcachedNodesManager, _statistics );
_log.info( "--------\n- " + getClass().getSimpleName() + " finished initialization:" +
"\n- sticky: "+ _sticky +
"\n- operation timeout: " + _operationTimeout +
"\n- node ids: " + _memcachedNodesManager.getPrimaryNodeIds() +
"\n- failover node ids: " + _memcachedNodesManager.getFailoverNodeIds() +
"\n- storage key prefix: " + _memcachedNodesManager.getStorageKeyFormat().prefix +
"\n- locking mode: " + _lockingMode + " (expiration: " + _lockExpiration + "s)" +
"\n--------");
}
|
Decorator for views that require a team be supplied wither via a slug in the
url pattern or already set on the request object from the TeamMiddleware
|
def team_required(func=None):
def decorator(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
slug = kwargs.pop("slug", None)
if not getattr(request, "team", None):
request.team = get_object_or_404(Team, slug=slug)
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator
|
// SetName sets the Name field's value.
|
func (s *CreateDataSourceInput) SetName(v string) *CreateDataSourceInput {
s.Name = &v
return s
}
|
------------------------------------------------------------------ Interface ------------------------------------------------------------------
|
function TieBreaker(oldRes, posAry, limit, opts) {
if (!(this instanceof TieBreaker)) {
return new TieBreaker(oldRes, posAry, limit, opts);
}
this._opts = TieBreaker.defaults(opts);
var invReason = TieBreaker.invalid(oldRes, posAry, this._opts, limit);
if (invReason !== null) {
this._opts.log.error('Invalid %d player TieBreaker with oldRes=%j rejected, opts=%j',
limit, oldRes, this._opts
);
throw new Error('Cannot construct TieBreaker: ' + invReason);
}
var xs = createMatches(posAry, limit, this._opts);
var ms = [];
if (this._opts.grouped) {
for (var i = 0; i < xs.length; i += 1) {
for (var j = 0; j < xs[i].matches.length; j += 1) {
var m = xs[i].matches[j];
// NB: modifying the matches here so that outside world sees the section
// corr. to the section they came from - whereas gs inst needs s === 1
ms.push({
id: new Id(xs[i].tbSection, m.id.r, m.id.m),
p: m.p.slice()
});
}
}
this.groupStages = xs;
}
else {
ms = xs;
}
Base.call(this, oldRes.length, ms);
this.name = 'TieBreaker';
this.grouped = this._opts.grouped;
this.strict = this._opts.strict;
this.posAry = posAry;
this.limit = limit;
this.oldRes = oldRes;
this.numSections = posAry.length;
this.sectionSize = $.flatten(posAry[0]).length;
this.betweenPosition = Math.ceil(this.limit / this.numSections);
// Demote player positions until we are done
// Demotion must unfortunately happen here, and not in previous tourneys results.
// This is because demotion will change depending on what limits we choose.
// While this means if we bypass TB we may end up forwarding unfairly (perhaps
// more players from one group than another), TB is here to fix it, so use it.
var pls = this.players(); // the players that are actually in matches here
this.numPlayers = pls.length; // override this.numPlayers set via Base.call(this)
var playersGuaranteed = oldRes.filter(function (r) {
return pls.indexOf(r.seed) < 0 && r.pos <= limit;
}).length;
oldRes.forEach(function (r) {
if (pls.indexOf(r.seed) >= 0) {
r.pos = pls.length + playersGuaranteed;
}
});
}
|
/* (non-Javadoc)
@see org.joml.Matrix4dc#getTransposed(int, java.nio.ByteBuffer)
|
public ByteBuffer getTransposed(int index, ByteBuffer dest) {
MemUtil.INSTANCE.putTransposed(this, index, dest);
return dest;
}
|
A helper function used by the {@link #getSubProperties} methods.
|
protected static void extractSubProperties (Properties source, Properties dest, String prefix)
{
// extend the prefix to contain a dot
prefix = prefix + ".";
int preflen = prefix.length();
// scan the source properties
Enumeration<?> names = source.propertyNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
// skip unrelated properties
if (!name.startsWith(prefix)) {
continue;
}
// insert the value into the new properties minus the prefix
dest.put(name.substring(preflen), source.getProperty(name));
}
}
|
Define the ball style.
@param eventType the type of event for this ball
|
public void setStyle(final JRebirthEventType eventType) {
switch (eventType) {
case CREATE_APPLICATION:
this.circle.setFill(BallColors.APPLICATION.get());
this.label.setText("App");
break;
case CREATE_NOTIFIER:
this.circle.setFill(BallColors.NOTIFIER.get());
this.label.setText("N");
break;
case CREATE_GLOBAL_FACADE:
this.circle.setFill(BallColors.GLOBAL_FACADE.get());
this.label.setText("GF");
break;
case CREATE_UI_FACADE:
this.circle.setFill(BallColors.UI_FACADE.get());
this.label.setText("UF");
break;
case CREATE_SERVICE_FACADE:
this.circle.setFill(BallColors.SERVICE_FACADE.get());
this.label.setText("SF");
break;
case CREATE_COMMAND_FACADE:
this.circle.setFill(BallColors.COMMAND_FACADE.get());
this.label.setText("CF");
break;
case CREATE_SERVICE:
this.circle.setFill(BallColors.SERVICE.get());
this.label.setText("S");
break;
case CREATE_MODEL:
this.circle.setFill(BallColors.MODEL.get());
this.label.setText("M");
break;
case CREATE_COMMAND:
this.circle.setFill(BallColors.COMMAND.get());
this.label.setText("C");
break;
case CREATE_VIEW:
this.circle.setFill(BallColors.VIEW.get());
this.label.setText("V");
break;
default:
// Nothing to colorize
}
}
|
设置Long类型参数.
@param value
|
public void setLong(Long value) {
this.checkNull(value);
list.add(value);
type.add(Long.class);
}
|
Outputs a BeautifulSoup object as a string that should hopefully be minimally modified
|
def _get_bs4_string(soup):
if len(soup.find_all("script")) == 0:
soup_str = soup.prettify(formatter=None).strip()
else:
soup_str = str(soup.html)
soup_str = re.sub("&", "&", soup_str)
soup_str = re.sub("<", "<", soup_str)
soup_str = re.sub(">", ">", soup_str)
return soup_str
|
// Save stores given cloud image metadata.
// It supports bulk calls.
|
func (api *API) Save(metadata params.MetadataSaveParams) (params.ErrorResults, error) {
all, err := imagecommon.Save(api.metadata, metadata)
if err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
return params.ErrorResults{Results: all}, nil
}
|
Connect to JCR Repostory and JMS queue
@throws JMSException if JMS Exception occurred
|
@PostConstruct
public void acquireConnections() throws JMSException {
LOGGER.debug("Initializing: {}", this.getClass().getCanonicalName());
connection = connectionFactory.createConnection();
connection.start();
jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = jmsSession.createProducer(createDestination());
eventBus.register(this);
}
|
Only allow class attributes that are instances of
rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy
|
def checkattr(metacls, attr, value):
if not isinstance(value, (
types.MethodType,
types.FunctionType,
classmethod,
staticmethod,
property)):
if attr in dir(type('dummy', (object,), {})) + \
['__metaclass__', '__qualname__']:
return
if attr.startswith('_'):
raise SyntaxError(
"TreeModel attribute `{0}` "
"must not start with `_`".format(attr))
if not inspect.isclass(value):
if not isinstance(value, Column):
raise TypeError(
"TreeModel attribute `{0}` "
"must be an instance of "
"`rootpy.tree.treetypes.Column`".format(attr))
return
if not issubclass(value, (ROOT.TObject, ROOT.ObjectProxy)):
raise TypeError(
"TreeModel attribute `{0}` must inherit "
"from `ROOT.TObject` or `ROOT.ObjectProxy`".format(
attr))
|
Use this API to fetch vpnsessionpolicy_aaagroup_binding resources of given name .
|
public static vpnsessionpolicy_aaagroup_binding[] get(nitro_service service, String name) throws Exception{
vpnsessionpolicy_aaagroup_binding obj = new vpnsessionpolicy_aaagroup_binding();
obj.set_name(name);
vpnsessionpolicy_aaagroup_binding response[] = (vpnsessionpolicy_aaagroup_binding[]) obj.get_resources(service);
return response;
}
|
Examines the value yielded from the generator and prepares the next step in interation.
@param mixed $yielded
|
private function next($yielded)
{
if (!$this->generator->valid()) {
$result = $this->generator->getReturn();
if ($result instanceof Awaitable) {
$this->reject(new AwaitableReturnedError($result));
return;
}
if ($result instanceof Generator) {
$this->reject(new GeneratorReturnedError($result));
return;
}
$this->resolve($result);
return;
}
$this->busy = true;
if ($yielded instanceof Generator) {
$yielded = new self($yielded);
}
$this->current = $yielded;
if ($yielded instanceof Awaitable) {
$yielded->done($this->send, $this->capture);
} else {
Loop\queue($this->send, $yielded);
}
$this->busy = false;
}
|
Called by PresentsSession to let us know that we can clear it entirely out of the system.
|
protected void clearSession (PresentsSession session)
{
// remove the session from the username map
PresentsSession rc;
synchronized (_usermap) {
rc = _usermap.remove(session.getAuthName());
}
// sanity check just because we can
if (rc == null) {
log.info("Cleared session: unregistered!", "session", session);
} else if (rc != session) {
log.info("Cleared session: multiple!", "s1", rc, "s2", session);
} else {
log.info("Cleared session", "session", session);
}
}
|
// newUnconfirmedBlocks returns new data structure to track currently unconfirmed blocks.
|
func newUnconfirmedBlocks(chain chainRetriever, depth uint) *unconfirmedBlocks {
return &unconfirmedBlocks{
chain: chain,
depth: depth,
}
}
|
shutdown all configured cluster monitors.
|
@Override
public void shutdownClusterMonitors() {
for (String clusterName : clustersProvider.getClusterNames()) {
ClusterMonitor<AggDataFromCluster> clusterMonitor = (ClusterMonitor<AggDataFromCluster>) AggregateClusterMonitor
.findOrRegisterAggregateMonitor(clusterName);
clusterMonitor.stopMonitor();
clusterMonitor.getDispatcher().stopDispatcher();
}
}
|
// tx is either "key=value" or just arbitrary bytes
|
func (app *KVStoreApplication) DeliverTx(tx []byte) types.ResponseDeliverTx {
var key, value []byte
parts := bytes.Split(tx, []byte("="))
if len(parts) == 2 {
key, value = parts[0], parts[1]
} else {
key, value = tx, tx
}
app.state.db.Set(prefixKey(key), value)
app.state.Size += 1
tags := []cmn.KVPair{
{Key: []byte("app.creator"), Value: []byte("Cosmoshi Netowoko")},
{Key: []byte("app.key"), Value: key},
}
return types.ResponseDeliverTx{Code: code.CodeTypeOK, Tags: tags}
}
|
Get a cached socket to the given address
@param remote Remote address the socket is connected to.
@return A socket with unknown state, possibly closed underneath. Or null.
|
public Socket get(SocketAddress remote) {
synchronized(multimap) {
List<Socket> sockList = multimap.get(remote);
if (sockList == null) {
return null;
}
Iterator<Socket> iter = sockList.iterator();
while (iter.hasNext()) {
Socket candidate = iter.next();
iter.remove();
if (!candidate.isClosed()) {
return candidate;
}
}
}
return null;
}
|
@param \Spryker\Zed\Kernel\Container $container
@return \Spryker\Zed\Kernel\Container
|
public function providePersistenceLayerDependencies(Container $container): Container
{
$container = parent::providePersistenceLayerDependencies($container);
$container = $this->addProductListPropelQuery($container);
return $container;
}
|
%prog digest fastafile NspI,BfuCI
Digest fasta sequences to map restriction site positions.
|
def digest(args):
p = OptionParser(digest.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, enzymes = args
enzymes = enzymes.split(",")
enzymes = [x for x in AllEnzymes if str(x) in enzymes]
f = Fasta(fastafile, lazy=True)
fw = must_open(opts.outfile, "w")
header = ["Contig", "Length"] + [str(x) for x in enzymes]
print("\t".join(header), file=fw)
for name, rec in f.iteritems_ordered():
row = [name, len(rec)]
for e in enzymes:
pos = e.search(rec.seq)
pos = "na" if not pos else "|".join(str(x) for x in pos)
row.append(pos)
print("\t".join(str(x) for x in row), file=fw)
|
Marshal collection.
@param cassandraTypeClazz
the cassandra type clazz
@param result
the result
@param clazz
the clazz
@return the collection
|
public static Collection marshalCollection(Class cassandraTypeClazz, Collection result, Class clazz, Class resultTypeClass)
{
Collection mappedCollection = result;
if (cassandraTypeClazz.isAssignableFrom(BytesType.class))
{
mappedCollection = (Collection) PropertyAccessorHelper.getObject(resultTypeClass);
for (Object value : result)
{
byte[] valueAsBytes = new byte[((ByteBuffer) value).remaining()];
((ByteBuffer) value).get(valueAsBytes);
mappedCollection.add(PropertyAccessorHelper.getObject(clazz, valueAsBytes));
}
}
return mappedCollection;
}
|
// Add creates a RemindersAddCall object in preparation for accessing the reminders.add endpoint
|
func (s *RemindersService) Add(text string, time int) *RemindersAddCall {
var call RemindersAddCall
call.service = s
call.text = text
call.time = time
return &call
}
|
Returns the projects in all workspaces containing archived ones or not.
@param boolean $archived Return archived projects or not
@param string $opt_fields Return results with optional parameters
@return string JSON or null
|
public function getProjects($archived = false, $opt_fields = "")
{
$archived = $archived ? "true" : "false";
$opt_fields = ($opt_fields != "") ? "&opt_fields={$opt_fields}" : "";
return $this->curl->get("projects?archived={$archived}{$opt_fields}");
}
|
@param integer $layoutId
@return bool
|
public function setDefaultLayout($layoutId): bool
{
$layout = new LayoutRecord();
$layout->id = $layoutId;
$layout->name = 'Default';
$layout->isDefault = true;
return $layout->save();
}
|
// AssertType makes sure the sentence's type matches the provided one.
|
func (p *parser) AssertType(typ string) {
if p.Type != typ {
p.SetErr("type", p.Type)
}
}
|
Read the band in native blocks.
|
def read_band_blocks(self, blocksize=CHUNK_SIZE):
""""""
# For sentinel 1 data, the block are 1 line, and dask seems to choke on that.
band = self.filehandle
shape = band.shape
token = tokenize(blocksize, band)
name = 'read_band-' + token
dskx = dict()
if len(band.block_shapes) != 1:
raise NotImplementedError('Bands with multiple shapes not supported.')
else:
chunks = band.block_shapes[0]
def do_read(the_band, the_window, the_lock):
with the_lock:
return the_band.read(1, None, window=the_window)
for ji, window in band.block_windows(1):
dskx[(name, ) + ji] = (do_read, band, window, self.read_lock)
res = da.Array(dskx, name, shape=list(shape),
chunks=chunks,
dtype=band.dtypes[0])
return DataArray(res, dims=('y', 'x'))
|
// HasAskForMore returns true if a value for AskForMore has been set in this context
|
func HasAskForMore(ctx context.Context) bool {
_, ok := ctx.Value(ctxKeyAskForMore).(bool)
return ok
}
|
Overide virtual methods for this extension. `this` : is this Fancytree object `this._super`: the virtual function that was overridden (member of prev. extension or Fancytree)
|
function(ctx){
var tree = ctx.tree;
// Bind init-handler to apply cookie state
tree.$div.bind("fancytreeinit", function(event){
tree.debug("COOKIE " + document.cookie);
});
// Init the tree
this._super(ctx);
}
|
Creates the x-axis and y-axis with proper orientations
@return {void}
@private
|
function buildAxis() {
xAxis = d3Axis.axisBottom(xScale)
.ticks(xTicks)
.tickPadding(tickPadding)
.tickFormat(d3Format.format(xAxisFormat));
yAxis = d3Axis.axisLeft(yScale)
.ticks(yTicks)
.tickPadding(tickPadding)
.tickFormat(d3Format.format(yAxisFormat));
}
|
Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
BDEFileEntry: file entry or None.
|
def GetFileEntryByPathSpec(self, path_spec):
return bde_file_entry.BDEFileEntry(
self._resolver_context, self, path_spec, is_root=True, is_virtual=True)
|
Creates EETData object from array received from API
@param $array
@return EETData
|
static function fromArray($array) {
$data = new EETData();
foreach (self::$keyNames as $key) {
if (array_key_exists($key, $array)) {
$data->$key = $array[$key];
}
}
$data->rawData = $array;
return $data;
}
|
// safeArrayAllocDescriptorEx allocates SafeArray.
//
// AKA: SafeArrayAllocDescriptorEx in Windows API.
|
func safeArrayAllocDescriptorEx(variantType VT, dimensions uint32) (*SafeArray, error) {
return nil, NewError(E_NOTIMPL)
}
|
Pass through to provider BookAdminSession.get_book_form_for_update
|
def get_book_form(self, *args, **kwargs):
""""""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.get_bin_form_for_update_template
# This method might be a bit sketchy. Time will tell.
if isinstance(args[-1], list) or 'book_record_types' in kwargs:
return self.get_book_form_for_create(*args, **kwargs)
else:
return self.get_book_form_for_update(*args, **kwargs)
|
// NewFileSystemAPIServer ...
|
func NewFileSystemAPIServer(store store.GroupStore) *FileSystemAPIServer {
s := new(FileSystemAPIServer)
s.gstore = store
return s
}
|
Perform an HTTP request
|
def request(method, path, options, format)
begin
response = connection(format).send(method) do |request|
case method.to_sym
when :get, :delete
request.url(formatted_path(path, format), options)
when :post, :put
request.path = formatted_path(path, format)
request.body = options unless options.empty?
end
end
'raw' == format.to_s.downcase ? response : response.body
rescue MultiJson::DecodeError
Hashie::Mash.new
end
end
|
Return the route url to call with bindings from configuration files.
@param $route
@return string
|
protected function getRouteUrlWithBindings($route)
{
$urlRouteBindings = [];
$urlInjectedBindings = [];
$routeAction = $route->getAction();
if (isset($routeAction['as'])) {
if (isset($this->profile['api_calls_bindings'])) {
foreach ($this->profile['api_calls_bindings'] as $apiCallsBinding) {
$routesAliases = $apiCallsBinding['routes_aliases'];
foreach ($routesAliases as $routeAlias) {
if ($routeAlias == $routeAction['as']) {
foreach ($apiCallsBinding['bindings'] as $binding) {
if ($binding['in'] == 'query-route') {
$urlRouteBindings[$binding['name']] = $binding['value'];
} else if ($binding['in'] == 'query-injected') {
$urlInjectedBindings[$binding['name']] = $binding['value'];
}
}
}
}
}
}
}
$url = $this->getRouteUri($route);
foreach ($urlRouteBindings as $name => $value) {
$url = str_replace('{'.$name.'}', $value, $url);
}
if (count($urlInjectedBindings) > 0) {
$firstName = array_keys($urlInjectedBindings)[0];
$firstValue = array_shift($urlInjectedBindings);
$url .= '?' . $firstName . '=' . $firstValue;
foreach ($urlInjectedBindings as $name => $value) {
$url .= '&' . $name . '=' . $value;
}
}
return $url;
}
|
// ValidatePostCtx will confirm Post content length is valid.
|
func (iapi *InsightApi) ValidatePostCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contentLengthString := r.Header.Get("Content-Length")
contentLength, err := strconv.Atoi(contentLengthString)
if err != nil {
writeInsightError(w, "Content-Length Header must be set")
return
}
// Broadcast Tx has the largest possible body. Cap max content length
// to iapi.params.MaxTxSize * 2 plus some arbitrary extra for JSON
// encapsulation.
maxPayload := (iapi.params.MaxTxSize * 2) + 50
if contentLength > maxPayload {
writeInsightError(w, fmt.Sprintf("Maximum Content-Length is %d", maxPayload))
return
}
next.ServeHTTP(w, r)
})
}
|
Returns the calendar week number (1-53).
|
def cweek
start = Date.civil(year, 1, 1)
((jd - start.jd + start.cwday - 5) / 7.0).ceil
end
|
Process a JSONP request by evaluating the mocked response text
|
function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || requestSettings,
newMock = null;
// If the response handler on the moock is a function, call it
if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
mockHandler.response(origSettings);
} else {
// Evaluate the responseText javascript in a global context
if( typeof mockHandler.responseText === 'object' ) {
$.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
} else {
$.globalEval( '(' + mockHandler.responseText + ')');
}
}
// Successful response
setTimeout(function() {
jsonpSuccess( requestSettings, callbackContext, mockHandler );
jsonpComplete( requestSettings, callbackContext, mockHandler );
}, parseResponseTimeOpt(mockHandler.responseTime) || 0);
// If we are running under jQuery 1.5+, return a deferred object
if($.Deferred){
newMock = new $.Deferred();
if(typeof mockHandler.responseText == "object"){
newMock.resolveWith( callbackContext, [mockHandler.responseText] );
}
else{
newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
}
}
return newMock;
}
|
Creates a new keystore for the izou aes key
@param fileName the path to the keystore
@param password the password to use with the keystore
@return the newly created keystore
|
private KeyStore createKeyStore(String fileName, String password) {
File file = new File(fileName);
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance("JCEKS");
if (file.exists()) {
keyStore.load(new FileInputStream(file), password.toCharArray());
} else {
keyStore.load(null, null);
keyStore.store(new FileOutputStream(fileName), password.toCharArray());
}
} catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException e) {
logger.error("Unable to create key store", e);
}
return keyStore;
}
|
Gets specified object
@param {string} name Object name
@returns {*} Specified object
@throws {Error} if specified object does not exist
@this {Injector}
|
function(name) {
this._checkObject(name);
if (!this._hasObject([name])) {
this._setObject([name], this._getObjectCreator([name]).call())._removeObjectCreator([name]);
}
return this._getObject([name]);
}
|
Subsets and Splits
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.