comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Set the correct cache headers
@param string $lastModified The time the source file was last modified
@param string $file The filename
@param boolean $hit Whether this was a cache hit or not | protected function setCacheHeaders($lastModified, $file, $hit)
{
// Set some flags
$this->cacheHeadersSet = true;
$this->cacheHeadersMaxAge = 31536000; // 1 year
$this->cacheHeadersLastModified = $lastModified;
$this->cacheHeadersExpires = time() + $this->cacheHeadersMaxAge;
$this->cacheHeadersFile = $file;
$this->cacheHeadersHit = $hit ? 'HIT' : 'MISS';
// --------------------------------------------------------------------------
header('Cache-Control: max-age=' . $this->cacheHeadersMaxAge . ', must-revalidate', true);
header('Last-Modified: ' . date('r', $this->cacheHeadersLastModified), true);
header('Expires: ' . date('r', $this->cacheHeadersExpires), true);
header('ETag: "' . md5($this->cacheHeadersFile) . '"', true);
header('X-CDN-CACHE: ' . $this->cacheHeadersHit, true);
} |
If the interval contains just a single point (i.e. this.lo == this.hi), then the overlap is 0.
Consider using {@link #overlapRelative(DoubleRange)}.
@param other interval to compare to
@return 0 if one of the intervals is a single point | public double overlapAbsolute(DoubleRange other) {
if (!intersects(other)) {
return 0;
}
int loCmp = lo.compareTo(other.lo);
int hiCmp = hi.compareTo(other.hi);
if (loCmp >= 0 && hiCmp <= 0) {
return this.length();
} else if (loCmp <= 0 && hiCmp >= 0) {
return other.length();
} else {
double newLo = (loCmp >= 0) ? this.lo : other.lo;
double newHi = (hiCmp <= 0) ? this.hi : other.hi;
return newHi - newLo;
}
} |
Replace an xsl:value-of element with a literal value
@param DOMElement $valueOf
@param string $value
@return void | protected function replaceValueOf(DOMElement $valueOf, $value)
{
$valueOf->parentNode->replaceChild($this->createText($value), $valueOf);
} |
// SetEventTypeCategories sets the EventTypeCategories field's value. | func (s *EventFilter) SetEventTypeCategories(v []*string) *EventFilter {
s.EventTypeCategories = v
return s
} |
Run nightwatch to start executing the tests | function (cb) {
Nightwatch.runner(argv, function (status) {
var err = null;
if (status) {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: tests passed');
} else {
console.log([moment().format('HH:mm:ss:SSS')] + ' kne: tests failed');
err = new Error('kne: nightwatch runner returned an error status code');
}
cb(err);
});
} |
Swipe vertical displacement must be less than this. | function( event ) {
// SAP MODIFICATION: if jQuery event is created programatically there's no originalEvent property. Therefore the existence of event.originalEvent needs to be checked.
var data = event.originalEvent && event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $( event.target )
};
} |
Invoke an HTTP POST request on a remote host.
@param path The request path
@param metaData The parameters (collection of Parameter objects)
@param payload
@return The Response object | @Override
public com.flickr4java.flickr.Response postMultiPart(String path, UploadMetaData metaData, Payload payload, String apiKey, String sharedSecret) throws FlickrException {
OAuthRequest request = new OAuthRequest(Verb.POST, buildUrl(path));
Map<String, String> uploadParameters = new HashMap<>(metaData.getUploadParameters());
buildMultipartRequest(uploadParameters, request);
OAuth10aService service = createAndSignRequest(apiKey, sharedSecret, request);
// Ensure all parameters (including oauth) are added to payload so signature matches
uploadParameters.putAll(request.getOauthParameters());
request.addMultipartPayload(String.format("form-data; name=\"photo\"; filename=\"%s\"", metaData.getFilename()), metaData.getFilemimetype(), payload.getPayload());
uploadParameters.entrySet().forEach(e ->
request.addMultipartPayload(String.format("form-data; name=\"%s\"", e.getKey()), null, e.getValue().getBytes()));
try {
return handleResponse(request, service);
} catch (IllegalAccessException | InterruptedException | ExecutionException | InstantiationException | IOException | SAXException | ParserConfigurationException e) {
throw new FlickrRuntimeException(e);
}
} |
Edit the keyword associated to a search engine
@param {string} name
Name of the engine to remove
@param {function} handler
Callback function for Engine Manager | function engineManager_editKeyword(name, handler)
{
// Select the search engine
this.selectedEngine = name;
// Setup the modal dialog handler
md = new modalDialog.modalDialog(this._controller.window);
md.start(handler);
var button = this.getElement({type: "engine_button", subtype: "edit"});
this._controller.click(button);
md.waitForDialog();
} |
Put corners into a proper grid. Make sure its a rectangular grid or else return false. Rows and columns
are selected to ensure right hand rule. | boolean orderNodes( FastQueue<Node> corners , GridInfo info ) {
// Find a node with just two edges. This is a corner and will be the arbitrary origin in our graph
Node seed = null;
for (int i = 0; i < corners.size; i++) {
Node n = corners.get(i);
if( n.countEdges() == 2 ) {
seed = n;
break;
}
}
if( seed == null ) {
if( verbose != null ) verbose.println("Can't find a corner with just two edges. Aborting");
return false;
}
// find one edge and mark that as the row direction
int rowEdge = 0;
while( seed.edges[rowEdge] == null )
rowEdge = (rowEdge+1)%4;
int colEdge = (rowEdge+1)%4;
while( seed.edges[colEdge] == null )
colEdge = (colEdge+2)%4;
// if it's left handed swap the row and column direction
if( !isRightHanded(seed,rowEdge,colEdge)) {
int tmp = rowEdge;
rowEdge = colEdge;
colEdge = tmp;
}
// add the corns to list in a row major order
while( seed != null ) {
int before = info.nodes.size();
Node n = seed;
do {
info.nodes.add(n);
n = n.edges[colEdge];
} while( n != null );
seed = seed.edges[rowEdge];
if( info.cols == -1 ) {
info.cols = info.nodes.size();
} else {
int columnsInRow = info.nodes.size()-before;
if( columnsInRow != info.cols ) {
if( verbose != null ) verbose.println("Number of columns in each row is variable");
return false;
}
}
}
info.rows = info.nodes.size()/info.cols;
return true;
} |
// SetSSES3 sets the SSES3 field's value. | func (s *InventoryEncryption) SetSSES3(v *SSES3) *InventoryEncryption {
s.SSES3 = v
return s
} |
Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1 | def get_content_version(cls, abspath: str) -> str:
data = cls.get_content(abspath)
hasher = hashlib.md5()
if isinstance(data, bytes):
hasher.update(data)
else:
for chunk in data:
hasher.update(chunk)
return hasher.hexdigest() |
Convert an ed25519 public key to a base64-encoded string.
Args:
key (Ed25519PublicKey): the key to write to the file.
Returns:
str: the key representation as a str | def ed25519_public_key_to_string(key):
return base64.b64encode(key.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw,
), None).decode('utf-8') |
// Open a connection | func (s *SNMP) Open() (err error) {
if s.conn != nil {
return
}
err = retry(int(s.args.Retries), func() error {
conn, e := net.DialTimeout(s.args.Network, s.args.Address, s.args.Timeout)
if e == nil {
s.conn = conn
}
return e
})
if err != nil {
return
}
s.engine = newSNMPEngine(s.args)
if err = s.engine.Discover(s); err != nil {
s.Close()
}
return
} |
Tells wether provided value is valid according to current type node.
@param mixed $value Value to validate.
@return bool | public function isValid($value)
{
if (!is_array($value)) {
return false;
}
foreach ($value as $subValue) {
if (!$this->valueTypeNode->isValid($subValue)) {
return false;
}
}
return true;
} |
Gets a new instance of the Validation class.
@param string The name or instance of the Fieldset to link to
@return Validation | public static function forge($fieldset = 'default')
{
if (is_string($fieldset))
{
($set = \Fieldset::instance($fieldset)) and $fieldset = $set;
}
if ($fieldset instanceof Fieldset)
{
if ($fieldset->validation(false) != null)
{
throw new \DomainException('Form instance already exists, cannot be recreated. Use instance() instead of forge() to retrieve the existing instance.');
}
}
return new static($fieldset);
} |
xml: inititiated when a start tag is encountered | function xmlStartElement($parser,$name,$attribs)
{
$this->xmlAttrib[$this->xmlCount] = $attribs;
$this->xmlName[$this->xmlCount] = $name;
$this->xmlSData[$this->xmlCount] = '$this->makeTableHeader("xml", "xml element", 2);';
$this->xmlSData[$this->xmlCount] .= '$this->makeTDHeader("xml", "xmlName");';
$this->xmlSData[$this->xmlCount] .= 'echo "<strong>' . $this->xmlName[$this->xmlCount] . '</strong>".$this->closeTDRow();';
$this->xmlSData[$this->xmlCount] .= '$this->makeTDHeader("xml", "xmlAttributes");';
if(count($attribs) > 0) $this->xmlSData[$this->xmlCount] .= '$this->varIsArray($this->xmlAttrib[' . $this->xmlCount . ']);';
else $this->xmlSData[$this->xmlCount] .= 'echo " ";';
$this->xmlSData[$this->xmlCount] .= 'echo $this->closeTDRow();';
$this->xmlCount++;
} |
// StartTime uses a given start time for the span being created. | func StartTime(start time.Time) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.Timestamp = start
}
} |
Generate next blob in file | def next_blob(self):
""""""
try:
length = struct.unpack('<i', self.blob_file.read(4))[0]
except struct.error:
raise StopIteration
header = CLBHeader(file_obj=self.blob_file)
blob = {'CLBHeader': header}
remaining_length = length - header.size
pmt_data = []
pmt_raw_data = self.blob_file.read(remaining_length)
pmt_raw_data_io = BytesIO(pmt_raw_data)
for _ in range(int(remaining_length / 6)):
channel_id, time, tot = struct.unpack(
'>cic', pmt_raw_data_io.read(6)
)
pmt_data.append(PMTData(ord(channel_id), time, ord(tot)))
blob['PMTData'] = pmt_data
blob['PMTRawData'] = pmt_raw_data
return blob |
Orders ips by hostnames
The purpose of this method is to sort ips of hostnames so it tries all IPs of hostname 1,
then all IPs of hostname 2, etc
== Return
@return [Array] array of ips ordered by hostnames | def hostnames_ips
@hostnames.map do |hostname|
ips.select { |ip, host| host == hostname }.keys
end.flatten
end |
// Start starts a new Watch for you. | func Start() Watch {
watch := &watch{time.Time{}, time.Time{}}
return watch.Start()
} |
Write usage information to the output stream. | def usage
parameters = @link_schema.parameters.map { |parameter| "<#{parameter}>" }
parameters = parameters.empty? ? '' : " #{parameters.join(' ')}"
example_body = @link_schema.example_body
body_parameter = example_body.nil? ? '' : ' <body>'
@output.write <<-USAGE
Usage: #{@cli_name} #{name}#{parameters}#{body_parameter}
Description:
#{description}
USAGE
if example_body
example_body = MultiJson.dump(example_body, pretty: true)
example_body = example_body.lines.map do |line|
" #{line}"
end.join
@output.write <<-USAGE
Body example:
#{example_body}
USAGE
end
end |
Load fixture to database.
@param string $fixturePath The fixture path relative to fixturesRootPath.
@throws DatabaseEx
@throws FixtureLoaderEx | public function loadDbFixture(string $fixturePath)
{
list($fixtureFormat, $fixtureData) = $this->loadFixtureData($fixturePath);
// Postpone database connection till we really need it.
$this->db->dbConnect();
$this->db->dbLoadFixture($fixtureFormat, $fixtureData);
} |
// Map a function on each element of a slice of strings | func MapS(f func(string) string, sl []string) (result []string) {
result = make([]string, len(sl))
for i := range sl {
result[i] = f(sl[i])
}
return result
} |
// Close closes the index. | func (i *Index) Close() error {
// Lock index and close partitions.
i.mu.Lock()
defer i.mu.Unlock()
for _, p := range i.partitions {
if err := p.Close(); err != nil {
return err
}
}
// Mark index as closed.
i.opened = false
return nil
} |
>>> _isbool(True)
True
>>> _isbool("False")
True
>>> _isbool(1)
False | def _isbool(string):
return isinstance(string, _bool_type) or\
(isinstance(string, (_binary_type, _text_type))
and
string in ("True", "False")) |
Função para conversão de texto e caracteres especiais em HTML
@param <string> $texto
@return <string> $retorno | public static function formataTexto($texto) {
$texto = htmlentities($texto, ENT_QUOTES);
$acentos = array('á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç', 'Á', 'À', 'Ã', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Õ', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç', 'ñ', 'Ñ');
$acentos_html = array('á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç', 'Á', 'À', 'Ã', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Õ', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç', 'ñ', 'Ñ');
$retorno = str_replace($acentos, $acentos_html, $texto);
return $retorno;
} |
Represents a `getblocks` packet.
@constructor
@param {Hash[]} locator
@param {Hash?} stop
@property {Hash[]} locator
@property {Hash|null} stop | function GetBlocksPacket(locator, stop) {
if (!(this instanceof GetBlocksPacket))
return new GetBlocksPacket(locator, stop);
Packet.call(this);
this.version = common.PROTOCOL_VERSION;
this.locator = locator || [];
this.stop = stop || null;
} |
Creates a new call set. (callsets.create)
@param Google_CallSet $postBody
@param array $optParams Optional parameters.
@return Genomics_CallSet | public function create(Genomics_CallSet $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Genomics_CallSet");
} |
Marshall the given parameter object. | public void marshall(TransformInput transformInput, ProtocolMarshaller protocolMarshaller) {
if (transformInput == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(transformInput.getDataSource(), DATASOURCE_BINDING);
protocolMarshaller.marshall(transformInput.getContentType(), CONTENTTYPE_BINDING);
protocolMarshaller.marshall(transformInput.getCompressionType(), COMPRESSIONTYPE_BINDING);
protocolMarshaller.marshall(transformInput.getSplitType(), SPLITTYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
Define the common setting that any backup type will have | protected function define_settings() {
global $CFG;
require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');
// Define filename setting
$filename = new backup_filename_setting('filename', base_setting::IS_FILENAME, 'backup.mbz');
$filename->set_ui_filename(get_string('filename', 'backup'), 'backup.mbz', array('size'=>50));
$this->add_setting($filename);
// Present converter settings only in type course and mode general backup operations.
$converters = array();
if ($this->plan->get_type() == backup::TYPE_1COURSE and $this->plan->get_mode() == backup::MODE_GENERAL) {
$converters = convert_helper::available_converters(false);
foreach ($converters as $cnv) {
$formatcnv = new backup_users_setting($cnv, base_setting::IS_BOOLEAN, false);
$formatcnv->set_ui(new backup_setting_ui_checkbox($formatcnv, get_string('backupformat'.$cnv, 'backup')));
$this->add_setting($formatcnv);
}
}
// Define users setting (keeping it on hand to define dependencies)
$users = new backup_users_setting('users', base_setting::IS_BOOLEAN, true);
$users->set_ui(new backup_setting_ui_checkbox($users, get_string('rootsettingusers', 'backup')));
$this->add_setting($users);
$this->converter_deps($users, $converters);
// Define anonymize (dependent of users)
$anonymize = new backup_anonymize_setting('anonymize', base_setting::IS_BOOLEAN, false);
$anonymize->set_ui(new backup_setting_ui_checkbox($anonymize, get_string('rootsettinganonymize', 'backup')));
$this->add_setting($anonymize);
$users->add_dependency($anonymize);
// Define role_assignments (dependent of users)
$roleassignments = new backup_role_assignments_setting('role_assignments', base_setting::IS_BOOLEAN, true);
$roleassignments->set_ui(new backup_setting_ui_checkbox($roleassignments, get_string('rootsettingroleassignments', 'backup')));
$this->add_setting($roleassignments);
$users->add_dependency($roleassignments);
// Define activities
$activities = new backup_activities_setting('activities', base_setting::IS_BOOLEAN, true);
$activities->set_ui(new backup_setting_ui_checkbox($activities, get_string('rootsettingactivities', 'backup')));
$this->add_setting($activities);
// Define blocks
$blocks = new backup_generic_setting('blocks', base_setting::IS_BOOLEAN, true);
$blocks->set_ui(new backup_setting_ui_checkbox($blocks, get_string('rootsettingblocks', 'backup')));
$this->add_setting($blocks);
$this->converter_deps($blocks, $converters);
// Define filters
$filters = new backup_generic_setting('filters', base_setting::IS_BOOLEAN, true);
$filters->set_ui(new backup_setting_ui_checkbox($filters, get_string('rootsettingfilters', 'backup')));
$this->add_setting($filters);
$this->converter_deps($filters, $converters);
// Define comments (dependent of users)
$comments = new backup_comments_setting('comments', base_setting::IS_BOOLEAN, true);
$comments->set_ui(new backup_setting_ui_checkbox($comments, get_string('rootsettingcomments', 'backup')));
$this->add_setting($comments);
$users->add_dependency($comments);
// Define badges (dependent of activities).
$badges = new backup_badges_setting('badges', base_setting::IS_BOOLEAN, true);
$badges->set_ui(new backup_setting_ui_checkbox($badges, get_string('rootsettingbadges', 'backup')));
$this->add_setting($badges);
$activities->add_dependency($badges);
$users->add_dependency($badges);
// Define calendar events.
$events = new backup_calendarevents_setting('calendarevents', base_setting::IS_BOOLEAN, true);
$events->set_ui(new backup_setting_ui_checkbox($events, get_string('rootsettingcalendarevents', 'backup')));
$this->add_setting($events);
// Define completion (dependent of users)
$completion = new backup_userscompletion_setting('userscompletion', base_setting::IS_BOOLEAN, true);
$completion->set_ui(new backup_setting_ui_checkbox($completion, get_string('rootsettinguserscompletion', 'backup')));
$this->add_setting($completion);
$users->add_dependency($completion);
// Define logs (dependent of users)
$logs = new backup_logs_setting('logs', base_setting::IS_BOOLEAN, true);
$logs->set_ui(new backup_setting_ui_checkbox($logs, get_string('rootsettinglogs', 'backup')));
$this->add_setting($logs);
$users->add_dependency($logs);
// Define grade_histories (dependent of users)
$gradehistories = new backup_generic_setting('grade_histories', base_setting::IS_BOOLEAN, true);
$gradehistories->set_ui(new backup_setting_ui_checkbox($gradehistories, get_string('rootsettinggradehistories', 'backup')));
$this->add_setting($gradehistories);
$users->add_dependency($gradehistories);
// The restore does not process the grade histories when some activities are ignored.
// So let's define a dependency to prevent false expectations from our users.
$activities->add_dependency($gradehistories);
// Define question bank inclusion setting.
$questionbank = new backup_generic_setting('questionbank', base_setting::IS_BOOLEAN, true);
$questionbank->set_ui(new backup_setting_ui_checkbox($questionbank, get_string('rootsettingquestionbank', 'backup')));
$this->add_setting($questionbank);
$groups = new backup_groups_setting('groups', base_setting::IS_BOOLEAN, true);
$groups->set_ui(new backup_setting_ui_checkbox($groups, get_string('rootsettinggroups', 'backup')));
$this->add_setting($groups);
// Define competencies inclusion setting if competencies are enabled.
$competencies = new backup_competencies_setting();
$competencies->set_ui(new backup_setting_ui_checkbox($competencies, get_string('rootsettingcompetencies', 'backup')));
$this->add_setting($competencies);
// Define custom fields inclusion setting if custom fields are used.
$customfields = new backup_customfield_setting('customfield', base_setting::IS_BOOLEAN, true);
$customfields->set_ui(new backup_setting_ui_checkbox($customfields, get_string('rootsettingcustomfield', 'backup')));
$this->add_setting($customfields);
} |
Compute default reference WCS from list of Catalog objects. | def build_referenceWCS(catalog_list):
wcslist = []
for catalog in catalog_list:
for scichip in catalog.catalogs:
wcslist.append(catalog.catalogs[scichip]['wcs'])
return utils.output_wcs(wcslist) |
Compile a DDL schema from an abstract reader
@param reader abstract DDL reader
@param db database
@param whichProcs which type(s) of procedures to load
@throws VoltCompiler.VoltCompilerException | void loadSchema(Reader reader, Database db, DdlProceduresToLoad whichProcs)
throws VoltCompiler.VoltCompilerException {
int currLineNo = 1;
DDLStatement stmt = getNextStatement(reader, m_compiler, currLineNo);
while (stmt != null) {
// Some statements are processed by VoltDB and the rest are handled by HSQL.
processVoltDBStatements(db, whichProcs, stmt);
stmt = getNextStatement(reader, m_compiler, stmt.endLineNo);
}
try {
reader.close();
} catch (IOException e) {
throw m_compiler.new VoltCompilerException("Error closing schema file");
}
// process extra classes
m_tracker.addExtraClasses(m_classMatcher.getMatchedClassList());
// possibly save some memory
m_classMatcher.clear();
} |
Creates string for get—request with given list of resources.<p>
@param resources to be transmitted
@return valid string for get-request | protected String getRequestString(List<CmsResource> resources) {
String res = "?";
for (CmsResource resource : resources) {
res += "resources=" + resource.getStructureId().getStringValue() + "&";
}
return res.substring(0, res.length() - 1); //Remove last "&"
} |
Prepares a service to manage collections on the database. This service will be set up by the Amity server. | function(database, callback){
var dbName = database.databaseName || database.name;
var options = {
name:dbName + '/_collections',
service:feathersMongoColls(amityMongo.db.db(dbName))
};
amityMongo.amity_collManager.push(options);
callback();
} |
// newLogger returns a log15.Logger which writes to stdout and a log file | func newLogger(tty bool, file string, verbose bool) log15.Logger {
stdoutFormat := log15.LogfmtFormat()
if tty {
stdoutFormat = log15.TerminalFormat()
}
stdoutHandler := log15.StreamHandler(os.Stdout, stdoutFormat)
if !verbose {
stdoutHandler = log15.LvlFilterHandler(log15.LvlInfo, stdoutHandler)
}
log := log15.New()
log.SetHandler(log15.MultiHandler(
log15.Must.FileHandler(file, log15.LogfmtFormat()),
stdoutHandler,
))
return log
} |
// getNegativeNumber will return a negative number from a
// byte slice. This will iterate through all characters until
// a non-digit has been found. | func getNegativeNumber(b []rune) int {
if b[0] != '-' {
return 0
}
i := 1
for ; i < len(b); i++ {
if !isDigit(b[i]) {
return i
}
}
return i
} |
Checks to see if a token is given. If so, it tries to validate the token
and log the user in. | def validate_token
token = params[:token]
return false if token.nil?
user = User.validate_token(token)
return false if user.nil?
login_user(user)
return true
end |
Clears all of the SOAP headers from the given SOAP client.
@param soapClient the client to remove the headers from | @Override
public void clearHeaders(Stub soapClient) {
soapClient._setProperty(HTTPConstants.REQUEST_HEADERS, new Hashtable<String, String>());
soapClient.clearHeaders();
} |
parseOctetSting.
@param string $data
@param array $result
@param bool $contextEspecific
@return void | protected static function parseOctetSting(&$data, &$result, $contextEspecific)
{
// Octetstring type
$data = self::parseCommon($data, $octectstringData);
if ($contextEspecific) {
$result[] = [
'octet string(' . self::$len . ')',
$octectstringData, ];
} else {
$result[] = [
'octet string (' . self::$len . ')',
self::parseASN((string) $octectstringData), ];
}
} |
Output result
@param mixed $data
@param string $format Output format as MIME or extension | public function output($data, $format = null)
{
$contentType = $this->outputContentType($format);
try {
$content = $this->serializeData($data, $contentType);
} catch (\UnexpectedValueException $e) {
if (!isset($format) && isset($this->defaultFormat) && $this->defaultFormat !== $contentType) {
$this->output($data, $this->defaultFormat); // Try default format instead
return;
}
throw $e;
}
$this->getResponse()->getBody()->write($content);
} |
// nolint: gocyclo | func (o *Config) String() string {
o.defaults()
c := "input: "
if o.Input != "" {
c += "<arg>"
} else if o.InputDir != "" {
c += o.InputDir
} else {
c += strings.Join(o.InputFiles, ", ")
}
if len(o.ExcludeGlob) > 0 {
c += "\nexclude: " + strings.Join(o.ExcludeGlob, ", ")
}
c += "\noutput: "
if o.InputDir != "" && o.OutputDir != "." {
c += o.OutputDir
} else if o.OutputMap != "" {
c += o.OutputMap
} else {
c += strings.Join(o.OutputFiles, ", ")
}
if o.OutMode != "" {
c += "\nchmod: " + o.OutMode
}
if len(o.DataSources) > 0 {
c += "\ndatasources: " + strings.Join(o.DataSources, ", ")
}
if len(o.DataSourceHeaders) > 0 {
c += "\ndatasourceheaders: " + strings.Join(o.DataSourceHeaders, ", ")
}
if len(o.Contexts) > 0 {
c += "\ncontexts: " + strings.Join(o.Contexts, ", ")
}
if o.LDelim != "{{" {
c += "\nleft_delim: " + o.LDelim
}
if o.RDelim != "}}" {
c += "\nright_delim: " + o.RDelim
}
if len(o.Templates) > 0 {
c += "\ntemplates: " + strings.Join(o.Templates, ", ")
}
return c
} |
Handles saving of debug information and halts the execution of the script on fatal error or if the
{@link halt_on_errors} property is set to TRUE
@access private | private function _log($category, $data, $fatal = true) {
// if debugging is on
if ($this->debug !== false) {
// if category is different than "warnings"
// (warnings are generated internally)
if ($category != 'warnings' && $this->debug_show_backtrace) {
// get backtrace information
$backtrace_data = debug_backtrace();
// unset first entry as it refers to the call to this particular method
unset($backtrace_data[0]);
$data['backtrace'] = array();
// iterate through the backtrace information
foreach ($backtrace_data as $backtrace)
// extract needed information
$data['backtrace'][] = array(
$this->language['file'] => (isset($backtrace['file']) ? $backtrace['file'] : ''),
$this->language['function'] => $backtrace['function'] . '()',
$this->language['line'] => (isset($backtrace['line']) ? $backtrace['line'] : ''),
);
}
// saves debug information
$this->debug_info[$category][] = $data;
// if the saved debug info is about a fatal error
// and execution is to be stopped on fatal errors
if ($fatal && $this->halt_on_errors) die();
return false;
// if there are any unsuccessful queries or other errors and no debugging
} elseif (($category == 'unsuccessful-queries' || $category == 'errors') && $this->debug === false) {
// get backtrace information
$backtraceInfo = debug_backtrace();
// log error to the system logger
error_log('Zebra_Database (MySQL): ' . (isset($data['error']) ? $data['error'] : $data['message']) . print_r(' in ' . $backtraceInfo[1]['file'] . ' on line ' . $backtraceInfo[1]['line'], true));
}
} |
Add a set of evidences to the Bayesian network to reason with it.
@param bn
@param evidences
map in format [nodeName, status] to set evidences in the
bayesian network
@throws ShanksException | public static void addEvidences(ProbabilisticNetwork bn,
Map<String, String> evidences) throws ShanksException {
for (Entry<String, String> evidence : evidences.entrySet()) {
ShanksAgentBayesianReasoningCapability.addEvidence(bn,
evidence.getKey(), evidence.getValue());
}
} |
Given a bunch of TimePeriods, return a TimePeriod that most closely
contains them. | def get_containing_period(cls, *periods):
""""""
if any(not isinstance(period, TimePeriod) for period in periods):
raise TypeError("periods must all be TimePeriods: {}".format(periods))
latest = datetime.datetime.min
earliest = datetime.datetime.max
for period in periods:
# the best we can do to conain None is None!
if period._latest is None:
latest = None
elif latest is not None and period._latest > latest:
latest = period._latest
if period._earliest is None:
earliest = None
elif earliest is not None and period._earliest < earliest:
earliest = period._earliest
return TimePeriod(earliest, latest) |
// AddToGroupVersion registers common meta types into schemas. | func AddToGroupVersion(scheme *runtime.Scheme, groupVersion schema.GroupVersion) {
scheme.AddKnownTypeWithName(groupVersion.WithKind(WatchEventKind), &WatchEvent{})
scheme.AddKnownTypeWithName(
schema.GroupVersion{Group: groupVersion.Group, Version: runtime.APIVersionInternal}.WithKind(WatchEventKind),
&InternalEvent{},
)
// Supports legacy code paths, most callers should use metav1.ParameterCodec for now
scheme.AddKnownTypes(groupVersion,
&ListOptions{},
&ExportOptions{},
&GetOptions{},
&DeleteOptions{},
&CreateOptions{},
&UpdateOptions{},
&PatchOptions{},
)
utilruntime.Must(scheme.AddConversionFuncs(
Convert_v1_WatchEvent_To_watch_Event,
Convert_v1_InternalEvent_To_v1_WatchEvent,
Convert_watch_Event_To_v1_WatchEvent,
Convert_v1_WatchEvent_To_v1_InternalEvent,
))
// Register Unversioned types under their own special group
scheme.AddUnversionedTypes(Unversioned,
&Status{},
&APIVersions{},
&APIGroupList{},
&APIGroup{},
&APIResourceList{},
)
// register manually. This usually goes through the SchemeBuilder, which we cannot use here.
utilruntime.Must(AddConversionFuncs(scheme))
utilruntime.Must(RegisterDefaults(scheme))
} |
// Tail return tail thing | func Tail(path string) string {
parts := strings.Split(path, "/")
return parts[len(parts)-1]
} |
/*
Automatically convert basic type to store | public static function simpleTypeToStore($inputData)
{
switch (gettype($inputData)) {
case 'string':
$store = new PBString();
$store->setValue($inputData);
return $store;
case 'boolean':
$store = new Boolean();
$store->setValue($inputData);
return $store;
}
return $inputData;
} |
Sets the properties and dependencies for HTML elements
@param ElementInterface $elm
@param array $data | protected static function populateElement(ElementInterface $elm, array $data)
{
self::setValue($elm, $data);
$hasAttributes = isset($data['attributes'])
&& is_array($data['attributes']);
if (! $hasAttributes) {
return;
}
foreach ($data['attributes'] as $attribute => $value) {
$elm->setAttribute($attribute, $value);
}
} |
______________________________________ MISC | function(path) {
var output = {},
obj = path ? utils.getProp(this.data, path) : this.data;
if (!obj)
return null;
for (var i in obj)
if (!outputFiler.test(i))
output[i] = obj[i];
return output;
} |
------------------- | protected OptionalThing<RunnerResult> synchronizedNeighborPreparing(Iterator<NeighborConcurrentGroup> groupIte,
Supplier<OptionalThing<RunnerResult>> runner) { // in preparing lock
if (groupIte.hasNext()) {
final NeighborConcurrentGroup group = groupIte.next();
synchronized (group.getGroupPreparingLock()) {
return synchronizedNeighborPreparing(groupIte, runner);
}
} else {
return runner.get();
}
} |
获取省市区地址码.
@param string $addressCode 地址码
@param string $birthdayCode 出生日期码
@return string | private function _getAddress($addressCode, $birthdayCode)
{
$address = '';
if (isset($this->_addressCodeTimeline[$addressCode])) {
$timeline = $this->_addressCodeTimeline[$addressCode];
$year = substr($birthdayCode, 0, 4);
foreach ($timeline as $key => $val) {
if (($key == 0 && $year < $val['start_year']) || $year >= $val['start_year']) {
$address = $val['address'];
}
}
}
return $address;
} |
Strip trailing </aiml> tag and concatenate all valid AIML files found in the ZIP. | def concatenate_aiml(path='aiml-en-us-foundation-alice.v1-9.zip', outfile='aiml-en-us-foundation-alice.v1-9.aiml'):
""""""
path = find_data_path(path) or path
zf = zipfile.ZipFile(path)
for name in zf.namelist():
if not name.lower().endswith('.aiml'):
continue
with zf.open(name) as fin:
happyending = '#!*@!!BAD'
for i, line in enumerate(fin):
try:
line = line.decode('utf-8').strip()
except UnicodeDecodeError:
line = line.decode('ISO-8859-1').strip()
if line.lower().startswith('</aiml>') or line.lower().endswith('</aiml>'):
happyending = (i, line)
break
else:
pass
if happyending != (i, line):
print('Invalid AIML format: {}\nLast line (line number {}) was: {}\nexpected "</aiml>"'.format(
name, i, line)) |
Sets list type
Implementation of this method also clears enumeration strategy property
@param string List type | public function setType($type)
{
$const = sprintf('%s::TYPE_%s', __CLASS__, strtoupper($type));
if(defined($const))
{
$type = constant($const);
}
$this->setAttributeDirectly('type', $type);
$this->enumerationStrategy = null;
} |
// NewSetFirewallRuleCommand returns a command to set firewall rules. | func NewSetFirewallRuleCommand() cmd.Command {
cmd := &setFirewallRuleCommand{}
cmd.newAPIFunc = func() (SetFirewallRuleAPI, error) {
root, err := cmd.NewAPIRoot()
if err != nil {
return nil, errors.Trace(err)
}
return firewallrules.NewClient(root), nil
}
return modelcmd.Wrap(cmd)
} |
@param stdClass $json
@param string|object $class
@param Callable $callback
@return mixed | private static function transformObject(\stdClass $json, $class, $callback)
{
if (is_string($class)) {
$object = new $class();
} else {
$object = $class;
}
foreach (static::getPropertyMapping($object) as $destination => $source) {
static::map($json, $source, $object, $destination);
}
if ($callback) {
call_user_func_array($callback, array($object));
}
return $object;
} |
Given a firebase ref, will return a function that will return all objects stored.
@param {Object} firebaseRef A reference to the firebase Object
@returns {Function} The all function | function all(firebaseRef) {
return function(cb) {
firebaseRef.once('value').then(function success(records) {
var results = records.val();
if (!results) {
return cb(null, []);
}
var list = Object.keys(results).map(function(key) {
return results[key];
});
cb(null, list);
}, cb);
};
} |
parse values from lines of the SVD section
Parameters
----------
lines : list | def parse_values_from_lines(self,lines):
assert len(lines) == 3,"SvdData.parse_values_from_lines: expected " + \
"3 lines, not {0}".format(len(lines))
try:
self.svdmode = int(lines[0].strip().split()[0])
except Exception as e:
raise Exception("SvdData.parse_values_from_lines: error parsing" + \
" svdmode from line {0}: {1} \n".format(lines[0],str(e)))
try:
raw = lines[1].strip().split()
self.maxsing = int(raw[0])
self.eigthresh = float(raw[1])
except Exception as e:
raise Exception("SvdData.parse_values_from_lines: error parsing" + \
" maxsing and eigthresh from line {0}: {1} \n"\
.format(lines[1],str(e)))
# try:
# self.eigwrite = int(lines[2].strip())
# except Exception as e:
# raise Exception("SvdData.parse_values_from_lines: error parsing" + \
# " eigwrite from line {0}: {1} \n".format(lines[2],str(e)))
self.eigwrite = lines[2].strip() |
Closes underlying byte stream.
@throws IOException if an I/O error occurs. | public void close() throws IOException {
if (fInputStream != null) {
fInputStream.close();
fInputStream = null;
fData = null;
}
} |
Retrieves logical definitions for a class id
Arguments
---------
nid : str
Node identifier for entity to be queried
Returns
-------
LogicalDefinition | def logical_definitions(self, nid):
ldefs = self.all_logical_definitions
if ldefs is not None:
#print("TESTING: {} AGAINST LD: {}".format(nid, str(ldefs)))
return [x for x in ldefs if x.class_id == nid]
else:
return [] |
/ <reference path="footer.js" /> / <reference path="../services/SortService.js" /> / <reference path="../../lib/jquery-1.8.2.min" /> | function ($scope, options, sortService, domUtilityService, $filter, $templateCache, $utils, $timeout, $parse, $http, $q) {
var defaults = {
//Define an aggregate template to customize the rows when grouped. See github wiki for more details.
aggregateTemplate: undefined,
//Callback for when you want to validate something after selection.
afterSelectionChange: function() {
},
/* Callback if you want to inspect something before selection,
return false if you want to cancel the selection. return true otherwise.
If you need to wait for an async call to proceed with selection you can
use rowItem.changeSelection(event) method after returning false initially.
Note: when shift+ Selecting multiple items in the grid this will only get called
once and the rowItem will be an array of items that are queued to be selected. */
beforeSelectionChange: function() {
return true;
},
//checkbox templates.
checkboxCellTemplate: undefined,
checkboxHeaderTemplate: undefined,
//definitions of columns as an array [], if not defines columns are auto-generated. See github wiki for more details.
columnDefs: undefined,
//*Data being displayed in the grid. Each item in the array is mapped to a row being displayed.
data: [],
//Data updated callback, fires every time the data is modified from outside the grid.
dataUpdated: function() {
},
//Enables cell editing.
enableCellEdit: false,
//Enables cell editing on focus
enableCellEditOnFocus: false,
//Enables cell selection.
enableCellSelection: false,
//Enable or disable resizing of columns
enableColumnResize: false,
//Enable or disable reordering of columns
enableColumnReordering: false,
//Enable or disable HEAVY column virtualization. This turns off selection checkboxes and column pinning and is designed for spreadsheet-like data.
enableColumnHeavyVirt: false,
//Enables the server-side paging feature
enablePaging: false,
//Enable column pinning
enablePinning: false,
//To be able to have selectable rows in grid.
enableRowSelection: true,
//Enables or disables sorting in grid.
enableSorting: true,
//Enables or disables text highlighting in grid by adding the "unselectable" class (See CSS file)
enableHighlighting: false,
// string list of properties to exclude when auto-generating columns.
excludeProperties: [],
/* filterOptions -
filterText: The text bound to the built-in search box.
useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box.
*/
filterOptions: {
filterText: "",
useExternalFilter: false
},
//Defining the height of the footer in pixels.
footerRowHeight: 55,
// the template for the column menu and filter, including the button.
footerTemplate: undefined,
// Enables a trade off between refreshing the contents of the grid continuously while scrolling (behaviour when true)
// and keeping the scroll bar button responsive at the expense of refreshing grid contents (behaviour when false)
forceSyncScrolling: true,
//Initial fields to group data by. Array of field names, not displayName.
groups: [],
// set the initial state of aggreagate grouping. "true" means they will be collapsed when grouping changes, "false" means they will be expanded by default.
groupsCollapsedByDefault: true,
//The height of the header row in pixels.
headerRowHeight: 30,
//Define a header row template for further customization. See github wiki for more details.
headerRowTemplate: undefined,
/*Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled.
Useful if you want drag + drop but your users insist on crappy browsers. */
jqueryUIDraggable: false,
//Enable the use jqueryUIThemes
jqueryUITheme: false,
//Prevent unselections when in single selection mode.
keepLastSelected: true,
/*Maintains the column widths while resizing.
Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false.*/
maintainColumnRatios: undefined,
// the template for the column menu and filter, including the button.
menuTemplate: undefined,
//Set this to false if you only want one item selected at a time
multiSelect: true,
// pagingOptions -
pagingOptions: {
// pageSizes: list of available page sizes.
pageSizes: [250, 500, 1000],
//pageSize: currently selected page size.
pageSize: 250,
//currentPage: the uhm... current page.
currentPage: 1
},
//the selection checkbox is pinned to the left side of the viewport or not.
pinSelectionCheckbox: false,
//Array of plugin functions to register in ng-grid
plugins: [],
//User defined unique ID field that allows for better handling of selections and for server-side paging
primaryKey: undefined,
//Row height of rows in grid.
rowHeight: 30,
//Define a row template to customize output. See github wiki for more details.
rowTemplate: undefined,
//all of the items selected in the grid. In single select mode there will only be one item in the array.
selectedItems: [],
//Disable row selections by clicking on the row and only when the checkbox is clicked.
selectWithCheckboxOnly: false,
/*Enables menu to choose which columns to display and group by.
If both showColumnMenu and showFilter are false the menu button will not display.*/
showColumnMenu: false,
/*Enables display of the filterbox in the column menu.
If both showColumnMenu and showFilter are false the menu button will not display.*/
showFilter: false,
//Show or hide the footer alltogether the footer is enabled by default
showFooter: false,
//Show the dropzone for drag and drop grouping
showGroupPanel: false,
//Row selection check boxes appear as the first column.
showSelectionCheckbox: false,
/*Define a sortInfo object to specify a default sorting state.
You can also observe this variable to utilize server-side sorting (see useExternalSorting).
Syntax is sortinfo: { fields: ['fieldName1',' fieldName2'], direction: 'ASC'/'asc' || 'desc'/'DESC'}*/
sortInfo: {fields: [], columns: [], directions: [] },
//Set the tab index of the Vieport.
tabIndex: -1,
//totalServerItems: Total items are on the server.
totalServerItems: 0,
/*Prevents the internal sorting from executing.
The sortInfo object will be updated with the sorting information so you can handle sorting (see sortInfo)*/
useExternalSorting: false,
/*i18n language support. choose from the installed or included languages, en, fr, sp, etc...*/
i18n: 'en',
//the threshold in rows to force virtualization on
virtualizationThreshold: 50,
// Don't handle tabs, so they can be used to navigate between controls.
noTabInterference: false
},
self = this;
self.maxCanvasHt = 0;
//self vars
self.config = $.extend(defaults, window.ngGrid.config, options);
// override conflicting settings
self.config.showSelectionCheckbox = (self.config.showSelectionCheckbox && self.config.enableColumnHeavyVirt === false);
self.config.enablePinning = (self.config.enablePinning && self.config.enableColumnHeavyVirt === false);
self.config.selectWithCheckboxOnly = (self.config.selectWithCheckboxOnly && self.config.showSelectionCheckbox !== false);
self.config.pinSelectionCheckbox = self.config.enablePinning;
if (typeof options.columnDefs === "string") {
self.config.columnDefs = $scope.$eval(options.columnDefs);
}
self.rowCache = [];
self.rowMap = [];
self.gridId = "ng" + $utils.newId();
self.$root = null; //this is the root element that is passed in with the binding handler
self.$groupPanel = null;
self.$topPanel = null;
self.$headerContainer = null;
self.$headerScroller = null;
self.$headers = null;
self.$viewport = null;
self.$canvas = null;
self.rootDim = self.config.gridDim;
self.data = [];
self.lateBindColumns = false;
self.filteredRows = [];
self.initTemplates = function() {
var templates = ['rowTemplate', 'aggregateTemplate', 'headerRowTemplate', 'checkboxCellTemplate', 'checkboxHeaderTemplate', 'menuTemplate', 'footerTemplate'];
var promises = [];
angular.forEach(templates, function(template) {
promises.push( self.getTemplate(template) );
});
return $q.all(promises);
};
//Templates
// test templates for urls and get the tempaltes via synchronous ajax calls
self.getTemplate = function (key) {
var t = self.config[key];
var uKey = self.gridId + key + ".html";
var p = $q.defer();
if (t && !TEMPLATE_REGEXP.test(t)) {
$http.get(t, {
cache: $templateCache
})
.success(function(data){
$templateCache.put(uKey, data);
p.resolve();
})
.error(function(err){
p.reject("Could not load template: " + t);
});
} else if (t) {
$templateCache.put(uKey, t);
p.resolve();
} else {
var dKey = key + ".html";
$templateCache.put(uKey, $templateCache.get(dKey));
p.resolve();
}
return p.promise;
};
if (typeof self.config.data === "object") {
self.data = self.config.data; // we cannot watch for updates if you don't pass the string name
}
self.calcMaxCanvasHeight = function() {
var calculatedHeight;
if(self.config.groups.length > 0){
calculatedHeight = self.rowFactory.parsedData.filter(function(e) {
return !e[NG_HIDDEN];
}).length * self.config.rowHeight;
} else {
calculatedHeight = self.filteredRows.length * self.config.rowHeight;
}
return calculatedHeight;
};
self.elementDims = {
scrollW: 0,
scrollH: 0,
rowIndexCellW: 25,
rowSelectedCellW: 25,
rootMaxW: 0,
rootMaxH: 0
};
//self funcs
self.setRenderedRows = function (newRows) {
$scope.renderedRows.length = newRows.length;
for (var i = 0; i < newRows.length; i++) {
if (!$scope.renderedRows[i] || (newRows[i].isAggRow || $scope.renderedRows[i].isAggRow)) {
$scope.renderedRows[i] = newRows[i].copy();
$scope.renderedRows[i].collapsed = newRows[i].collapsed;
if (!newRows[i].isAggRow) {
$scope.renderedRows[i].setVars(newRows[i]);
}
} else {
$scope.renderedRows[i].setVars(newRows[i]);
}
$scope.renderedRows[i].rowIndex = newRows[i].rowIndex;
$scope.renderedRows[i].offsetTop = newRows[i].offsetTop;
$scope.renderedRows[i].selected = newRows[i].selected;
newRows[i].renderedRowIndex = i;
}
self.refreshDomSizes();
$scope.$emit('ngGridEventRows', newRows);
};
self.minRowsToRender = function() {
var viewportH = $scope.viewportDimHeight() || 1;
return Math.floor(viewportH / self.config.rowHeight);
};
self.refreshDomSizes = function() {
var dim = new ngDimension();
dim.outerWidth = self.elementDims.rootMaxW;
dim.outerHeight = self.elementDims.rootMaxH;
self.rootDim = dim;
self.maxCanvasHt = self.calcMaxCanvasHeight();
};
self.buildColumnDefsFromData = function () {
self.config.columnDefs = [];
var item = self.data[0];
if (!item) {
self.lateBoundColumns = true;
return;
}
$utils.forIn(item, function (prop, propName) {
if (self.config.excludeProperties.indexOf(propName) === -1) {
self.config.columnDefs.push({
field: propName
});
}
});
};
self.buildColumns = function() {
var columnDefs = self.config.columnDefs,
cols = [];
if (!columnDefs) {
self.buildColumnDefsFromData();
columnDefs = self.config.columnDefs;
}
if (self.config.showSelectionCheckbox) {
cols.push(new ngColumn({
colDef: {
field: '\u2714',
width: self.elementDims.rowSelectedCellW,
sortable: false,
resizable: false,
groupable: false,
headerCellTemplate: $templateCache.get($scope.gridId + 'checkboxHeaderTemplate.html'),
cellTemplate: $templateCache.get($scope.gridId + 'checkboxCellTemplate.html'),
pinned: self.config.pinSelectionCheckbox
},
index: 0,
headerRowHeight: self.config.headerRowHeight,
sortCallback: self.sortData,
resizeOnDataCallback: self.resizeOnData,
enableResize: self.config.enableColumnResize,
enableSort: self.config.enableSorting,
enablePinning: self.config.enablePinning
}, $scope, self, domUtilityService, $templateCache, $utils));
}
if (columnDefs.length > 0) {
var checkboxOffset = self.config.showSelectionCheckbox ? 1 : 0;
var groupOffset = $scope.configGroups.length;
$scope.configGroups.length = 0;
angular.forEach(columnDefs, function(colDef, i) {
i += checkboxOffset;
var column = new ngColumn({
colDef: colDef,
index: i + groupOffset,
originalIndex: i,
headerRowHeight: self.config.headerRowHeight,
sortCallback: self.sortData,
resizeOnDataCallback: self.resizeOnData,
enableResize: self.config.enableColumnResize,
enableSort: self.config.enableSorting,
enablePinning: self.config.enablePinning,
enableCellEdit: self.config.enableCellEdit || self.config.enableCellEditOnFocus,
cellEditableCondition: self.config.cellEditableCondition
}, $scope, self, domUtilityService, $templateCache, $utils);
var indx = self.config.groups.indexOf(colDef.field);
if (indx !== -1) {
column.isGroupedBy = true;
$scope.configGroups.splice(indx, 0, column);
column.groupIndex = $scope.configGroups.length;
}
cols.push(column);
});
$scope.columns = cols;
if (self.config.groups.length > 0) {
self.rowFactory.getGrouping(self.config.groups);
}
}
};
self.configureColumnWidths = function() {
var asterisksArray = [],
percentArray = [],
asteriskNum = 0,
totalWidth = 0;
// When rearranging columns, their index in $scope.columns will no longer match the original column order from columnDefs causing
// their width config to be out of sync. We can use "originalIndex" on the ngColumns to get hold of the correct setup from columnDefs, but to
// avoid O(n) lookups in $scope.columns per column we setup a map.
var indexMap = {};
// Build a map of columnDefs column indices -> ngColumn indices (via the "originalIndex" property on ngColumns).
angular.forEach($scope.columns, function(ngCol, i) {
// Disregard columns created by grouping (the grouping columns don't match a column from columnDefs)
if (!$utils.isNullOrUndefined(ngCol.originalIndex)) {
var origIndex = ngCol.originalIndex;
if (self.config.showSelectionCheckbox) {
//if visible, takes up 25 pixels
if(ngCol.originalIndex === 0 && ngCol.visible){
totalWidth += 25;
}
// The originalIndex will be offset 1 when including the selection column
origIndex--;
}
indexMap[origIndex] = i;
}
});
angular.forEach(self.config.columnDefs, function(colDef, i) {
// Get the ngColumn that matches the current column from columnDefs
var ngColumn = $scope.columns[indexMap[i]];
colDef.index = i;
var isPercent = false, t;
//if width is not defined, set it to a single star
if ($utils.isNullOrUndefined(colDef.width)) {
colDef.width = "*";
} else { // get column width
isPercent = isNaN(colDef.width) ? $utils.endsWith(colDef.width, "%") : false;
t = isPercent ? colDef.width : parseInt(colDef.width, 10);
}
// check if it is a number
if (isNaN(t) && !$scope.hasUserChangedGridColumnWidths) {
t = colDef.width;
// figure out if the width is defined or if we need to calculate it
if (t === 'auto') { // set it for now until we have data and subscribe when it changes so we can set the width.
ngColumn.width = ngColumn.minWidth;
totalWidth += ngColumn.width;
var temp = ngColumn;
$scope.$on('$destroy', $scope.$on("ngGridEventData", function () {
self.resizeOnData(temp);
}));
return;
} else if (t.indexOf("*") !== -1) { // we need to save it until the end to do the calulations on the remaining width.
if (ngColumn.visible !== false) {
asteriskNum += t.length;
}
asterisksArray.push(colDef);
return;
} else if (isPercent) { // If the width is a percentage, save it until the very last.
percentArray.push(colDef);
return;
} else { // we can't parse the width so lets throw an error.
throw "unable to parse column width, use percentage (\"10%\",\"20%\", etc...) or \"*\" to use remaining width of grid";
}
} else if (ngColumn.visible !== false) {
totalWidth += ngColumn.width = parseInt(ngColumn.width, 10);
}
});
// Now we check if we saved any percentage columns for calculating last
if (percentArray.length > 0) {
//If they specificy for maintain column ratios to be false in grid config, then it will remain false. If not specifiied or true, will be true.
self.config.maintainColumnRatios = self.config.maintainColumnRatios !== false;
// If any columns with % widths have been hidden, then let other % based columns use their width
var percentWidth = 0; // The total % value for all columns setting their width using % (will e.g. be 40 for 2 columns with 20% each)
var hiddenPercent = 0; // The total % value for all columns setting their width using %, but which have been hidden
angular.forEach(percentArray, function(colDef) {
// Get the ngColumn that matches the current column from columnDefs
var ngColumn = $scope.columns[indexMap[colDef.index]];
var percent = parseFloat(colDef.width) / 100;
percentWidth += percent;
if (!ngColumn.visible) {
hiddenPercent += percent;
}
});
var percentWidthUsed = percentWidth - hiddenPercent;
// do the math
angular.forEach(percentArray, function(colDef) {
// Get the ngColumn that matches the current column from columnDefs
var ngColumn = $scope.columns[indexMap[colDef.index]];
// Calc the % relative to the amount of % reserved for the visible columns (that use % based widths)
var percent = parseFloat(colDef.width) / 100;
if (hiddenPercent > 0) {
percent = percent / percentWidthUsed;
}
else {
percent = percent / percentWidth;
}
var pixelsForPercentBasedWidth = self.rootDim.outerWidth * percentWidth;
ngColumn.width = pixelsForPercentBasedWidth * percent;
totalWidth += ngColumn.width;
});
}
// check if we saved any asterisk columns for calculating later
if (asterisksArray.length > 0) {
//If they specificy for maintain column ratios to be false in grid config, then it will remain false. If not specifiied or true, will be true.
self.config.maintainColumnRatios = self.config.maintainColumnRatios !== false;
// get the remaining width
var remainingWidth = self.rootDim.outerWidth - totalWidth;
// are we overflowing vertically?
if (self.maxCanvasHt > $scope.viewportDimHeight()) {
//compensate for scrollbar
remainingWidth -= domUtilityService.ScrollW;
}
// calculate the weight of each asterisk rounded down
var asteriskVal = Math.floor(remainingWidth / asteriskNum);
// set the width of each column based on the number of stars
angular.forEach(asterisksArray, function(colDef, i) {
// Get the ngColumn that matches the current column from columnDefs
var ngColumn = $scope.columns[indexMap[colDef.index]];
ngColumn.width = asteriskVal * colDef.width.length;
if (ngColumn.visible !== false) {
totalWidth += ngColumn.width;
}
var isLast = (i === (asterisksArray.length - 1));
//if last asterisk and doesn't fill width of grid, add the difference
if(isLast && totalWidth < self.rootDim.outerWidth){
var gridWidthDifference = self.rootDim.outerWidth - totalWidth;
if(self.maxCanvasHt > $scope.viewportDimHeight()){
gridWidthDifference -= domUtilityService.ScrollW;
}
ngColumn.width += gridWidthDifference;
}
});
}
};
self.init = function() {
return self.initTemplates().then(function(){
//factories and services
$scope.selectionProvider = new ngSelectionProvider(self, $scope, $parse);
$scope.domAccessProvider = new ngDomAccessProvider(self);
self.rowFactory = new ngRowFactory(self, $scope, domUtilityService, $templateCache, $utils);
self.searchProvider = new ngSearchProvider($scope, self, $filter);
self.styleProvider = new ngStyleProvider($scope, self);
$scope.$on('$destroy', $scope.$watch('configGroups', function(a) {
var tempArr = [];
angular.forEach(a, function(item) {
tempArr.push(item.field || item);
});
self.config.groups = tempArr;
self.rowFactory.filteredRowsChanged();
$scope.$emit('ngGridEventGroups', a);
}, true));
$scope.$on('$destroy', $scope.$watch('columns', function (a) {
if(!$scope.isColumnResizing){
domUtilityService.RebuildGrid($scope, self);
}
$scope.$emit('ngGridEventColumns', a);
}, true));
$scope.$on('$destroy', $scope.$watch(function() {
return options.i18n;
}, function(newLang) {
$utils.seti18n($scope, newLang);
}));
self.maxCanvasHt = self.calcMaxCanvasHeight();
if (self.config.sortInfo.fields && self.config.sortInfo.fields.length > 0) {
$scope.$on('$destroy', $scope.$watch(function() {
return self.config.sortInfo;
}, function(sortInfo){
if (!sortService.isSorting) {
self.sortColumnsInit();
$scope.$emit('ngGridEventSorted', self.config.sortInfo);
}
}, true));
}
});
// var p = $q.defer();
// p.resolve();
// return p.promise;
};
self.resizeOnData = function(col) {
// we calculate the longest data.
var longest = col.minWidth;
var arr = $utils.getElementsByClassName('col' + col.index);
angular.forEach(arr, function(elem, index) {
var i;
if (index === 0) {
var kgHeaderText = $(elem).find('.ngHeaderText');
i = $utils.visualLength(kgHeaderText) + 10; // +10 some margin
} else {
var ngCellText = $(elem).find('.ngCellText');
i = $utils.visualLength(ngCellText) + 10; // +10 some margin
}
if (i > longest) {
longest = i;
}
});
col.width = col.longest = Math.min(col.maxWidth, longest + 7); // + 7 px to make it look decent.
domUtilityService.BuildStyles($scope, self, true);
};
self.lastSortedColumns = [];
self.sortData = function(col, evt) {
if (evt && evt.shiftKey && self.config.sortInfo) {
var indx = self.config.sortInfo.columns.indexOf(col);
if (indx === -1) {
if (self.config.sortInfo.columns.length === 1) {
self.config.sortInfo.columns[0].sortPriority = 1;
}
self.config.sortInfo.columns.push(col);
col.sortPriority = self.config.sortInfo.columns.length;
self.config.sortInfo.fields.push(col.field);
self.config.sortInfo.directions.push(col.sortDirection);
self.lastSortedColumns.push(col);
} else {
self.config.sortInfo.directions[indx] = col.sortDirection;
}
} else if (!self.config.useExternalSorting || (self.config.useExternalSorting && self.config.sortInfo )) {
var isArr = $.isArray(col);
self.config.sortInfo.columns.length = 0;
self.config.sortInfo.fields.length = 0;
self.config.sortInfo.directions.length = 0;
var push = function (c) {
self.config.sortInfo.columns.push(c);
self.config.sortInfo.fields.push(c.field);
self.config.sortInfo.directions.push(c.sortDirection);
self.lastSortedColumns.push(c);
};
if (isArr) {
angular.forEach(col, function (c, i) {
c.sortPriority = i + 1;
push(c);
});
} else {
self.clearSortingData(col);
col.sortPriority = undefined;
push(col);
}
self.sortActual();
self.searchProvider.evalFilter();
$scope.$emit('ngGridEventSorted', self.config.sortInfo);
}
};
self.sortColumnsInit = function() {
if (self.config.sortInfo.columns) {
self.config.sortInfo.columns.length = 0;
} else {
self.config.sortInfo.columns = [];
}
var cols = [];
angular.forEach($scope.columns, function(c) {
var i = self.config.sortInfo.fields.indexOf(c.field);
if (i !== -1) {
c.sortDirection = self.config.sortInfo.directions[i] || 'asc';
cols[i] = c;
}
});
if(cols.length === 1){
self.sortData(cols[0]);
}else{
self.sortData(cols);
}
};
self.sortActual = function() {
if (!self.config.useExternalSorting) {
var tempData = self.data.slice(0);
angular.forEach(tempData, function(item, i) {
var e = self.rowMap[i];
if (e !== undefined) {
var v = self.rowCache[e];
if (v !== undefined) {
item.preSortSelected = v.selected;
item.preSortIndex = i;
}
}
});
sortService.Sort(self.config.sortInfo, tempData);
angular.forEach(tempData, function(item, i) {
self.rowCache[i].entity = item;
self.rowCache[i].selected = item.preSortSelected;
self.rowMap[item.preSortIndex] = i;
delete item.preSortSelected;
delete item.preSortIndex;
});
}
};
self.clearSortingData = function (col) {
if (!col) {
angular.forEach(self.lastSortedColumns, function (c) {
c.sortDirection = "";
c.sortPriority = null;
});
self.lastSortedColumns = [];
} else {
angular.forEach(self.lastSortedColumns, function (c) {
if (col.index !== c.index) {
c.sortDirection = "";
c.sortPriority = null;
}
});
self.lastSortedColumns[0] = col;
self.lastSortedColumns.length = 1;
}
};
self.fixColumnIndexes = function() {
//fix column indexes
for (var i = 0; i < $scope.columns.length; i++) {
$scope.columns[i].index = i;
}
};
self.fixGroupIndexes = function() {
angular.forEach($scope.configGroups, function(item, i) {
item.groupIndex = i + 1;
});
};
//$scope vars
$scope.elementsNeedMeasuring = true;
$scope.columns = [];
$scope.renderedRows = [];
$scope.renderedColumns = [];
$scope.headerRow = null;
$scope.rowHeight = self.config.rowHeight;
$scope.jqueryUITheme = self.config.jqueryUITheme;
$scope.showSelectionCheckbox = self.config.showSelectionCheckbox;
$scope.enableCellSelection = self.config.enableCellSelection;
$scope.enableCellEditOnFocus = self.config.enableCellEditOnFocus;
$scope.footer = null;
$scope.selectedItems = self.config.selectedItems;
$scope.multiSelect = self.config.multiSelect;
$scope.showFooter = self.config.showFooter;
$scope.footerRowHeight = $scope.showFooter ? self.config.footerRowHeight : 0;
$scope.showColumnMenu = self.config.showColumnMenu;
$scope.forceSyncScrolling = self.config.forceSyncScrolling;
$scope.showMenu = false;
$scope.configGroups = [];
$scope.gridId = self.gridId;
//Paging
$scope.enablePaging = self.config.enablePaging;
$scope.pagingOptions = self.config.pagingOptions;
//i18n support
$scope.i18n = {};
$utils.seti18n($scope, self.config.i18n);
$scope.adjustScrollLeft = function (scrollLeft) {
var colwidths = 0,
totalLeft = 0,
x = $scope.columns.length,
newCols = [],
dcv = !self.config.enableColumnHeavyVirt;
var r = 0;
var addCol = function (c) {
if (dcv) {
newCols.push(c);
} else {
if (!$scope.renderedColumns[r]) {
$scope.renderedColumns[r] = c.copy();
} else {
$scope.renderedColumns[r].setVars(c);
}
}
r++;
};
for (var i = 0; i < x; i++) {
var col = $scope.columns[i];
if (col.visible !== false) {
var w = col.width + colwidths;
if (col.pinned) {
addCol(col);
var newLeft = i > 0 ? (scrollLeft + totalLeft) : scrollLeft;
domUtilityService.setColLeft(col, newLeft, self);
totalLeft += col.width;
} else {
if (w >= scrollLeft) {
if (colwidths <= scrollLeft + self.rootDim.outerWidth) {
addCol(col);
}
}
}
colwidths += col.width;
}
}
if (dcv) {
$scope.renderedColumns = newCols;
}
};
self.prevScrollTop = 0;
self.prevScrollIndex = 0;
$scope.adjustScrollTop = function(scrollTop, force) {
if (self.prevScrollTop === scrollTop && !force) {
return;
}
if (scrollTop > 0 && self.$viewport[0].scrollHeight - scrollTop <= self.$viewport.outerHeight()) {
$scope.$emit('ngGridEventScroll');
}
var rowIndex = Math.floor(scrollTop / self.config.rowHeight);
var newRange;
if (self.filteredRows.length > self.config.virtualizationThreshold) {
// Have we hit the threshold going down?
if (self.prevScrollTop < scrollTop && rowIndex < self.prevScrollIndex + SCROLL_THRESHOLD) {
return;
}
//Have we hit the threshold going up?
if (self.prevScrollTop > scrollTop && rowIndex > self.prevScrollIndex - SCROLL_THRESHOLD) {
return;
}
newRange = new ngRange(Math.max(0, rowIndex - EXCESS_ROWS), rowIndex + self.minRowsToRender() + EXCESS_ROWS);
} else {
var maxLen = $scope.configGroups.length > 0 ? self.rowFactory.parsedData.length : self.filteredRows.length;
newRange = new ngRange(0, Math.max(maxLen, self.minRowsToRender() + EXCESS_ROWS));
}
self.prevScrollTop = scrollTop;
self.rowFactory.UpdateViewableRange(newRange);
self.prevScrollIndex = rowIndex;
};
//scope funcs
$scope.toggleShowMenu = function() {
$scope.showMenu = !$scope.showMenu;
};
$scope.toggleSelectAll = function(state, selectOnlyVisible) {
$scope.selectionProvider.toggleSelectAll(state, false, selectOnlyVisible);
};
$scope.totalFilteredItemsLength = function() {
return self.filteredRows.length;
};
$scope.showGroupPanel = function() {
return self.config.showGroupPanel;
};
$scope.topPanelHeight = function() {
return self.config.showGroupPanel === true ? self.config.headerRowHeight + 32 : self.config.headerRowHeight;
};
$scope.viewportDimHeight = function() {
return Math.max(0, self.rootDim.outerHeight - $scope.topPanelHeight() - $scope.footerRowHeight - 2);
};
$scope.groupBy = function (col) {
if (self.data.length < 1 || !col.groupable || !col.field) {
return;
}
//first sort the column
if (!col.sortDirection) {
col.sort({ shiftKey: $scope.configGroups.length > 0 ? true : false });
}
var indx = $scope.configGroups.indexOf(col);
if (indx === -1) {
col.isGroupedBy = true;
$scope.configGroups.push(col);
col.groupIndex = $scope.configGroups.length;
} else {
$scope.removeGroup(indx);
}
self.$viewport.scrollTop(0);
domUtilityService.digest($scope);
};
$scope.removeGroup = function(index) {
var col = $scope.columns.filter(function(item) {
return item.groupIndex === (index + 1);
})[0];
col.isGroupedBy = false;
col.groupIndex = 0;
if ($scope.columns[index].isAggCol) {
$scope.columns.splice(index, 1);
$scope.configGroups.splice(index, 1);
self.fixGroupIndexes();
}
if ($scope.configGroups.length === 0) {
self.fixColumnIndexes();
domUtilityService.digest($scope);
}
$scope.adjustScrollLeft(0);
};
$scope.togglePin = function (col) {
var indexFrom = col.index;
var indexTo = 0;
for (var i = 0; i < $scope.columns.length; i++) {
if (!$scope.columns[i].pinned) {
break;
}
indexTo++;
}
if (col.pinned) {
indexTo = Math.max(col.originalIndex, indexTo - 1);
}
col.pinned = !col.pinned;
// Splice the columns
$scope.columns.splice(indexFrom, 1);
$scope.columns.splice(indexTo, 0, col);
self.fixColumnIndexes();
// Finally, rebuild the CSS styles.
domUtilityService.BuildStyles($scope, self, true);
self.$viewport.scrollLeft(self.$viewport.scrollLeft() - col.width);
};
$scope.totalRowWidth = function() {
var totalWidth = 0,
cols = $scope.columns;
for (var i = 0; i < cols.length; i++) {
if (cols[i].visible !== false) {
totalWidth += cols[i].width;
}
}
return totalWidth;
};
$scope.headerScrollerDim = function() {
var viewportH = $scope.viewportDimHeight(),
maxHeight = self.maxCanvasHt,
vScrollBarIsOpen = (maxHeight > viewportH),
newDim = new ngDimension();
newDim.autoFitHeight = true;
newDim.outerWidth = $scope.totalRowWidth();
if (vScrollBarIsOpen) {
newDim.outerWidth += self.elementDims.scrollW;
} else if ((maxHeight - viewportH) <= self.elementDims.scrollH) { //if the horizontal scroll is open it forces the viewport to be smaller
newDim.outerWidth += self.elementDims.scrollW;
}
return newDim;
};
} |
Method to get current user
@return Array format as Facebook | public function getUser($lead_id)
{
// Because the received data already contains user info so we don't need to make any request
$raw = Conversation::get('request_raw');
if (isset($raw['callback_query'])) {
$raw = $raw['callback_query'];
$user = $raw['from'];
}
else {
$user = $raw['message']['from'];
}
return [
'user_id' => $lead_id,
'first_name' => $user['first_name'],
'last_name' => $user['last_name'],
'source' => 'telegram:' . Conversation::get('page_id'),
'locale' => str_replace('-', '_', $user['language_code'])
];
} |
// nextValueBytes returns the next value in the stream as a set of bytes. | func (d *Decoder) nextValueBytes() (bs []byte) {
d.d.uncacheRead()
d.r.track()
d.swallow()
bs = d.r.stopTrack()
return
} |
Performs external loads for the fields in $content.
@param Content $content | public function loadExternalFieldData(Content $content)
{
foreach ($content->fields as $field) {
$this->storageHandler->getFieldData($content->versionInfo, $field);
}
} |
// GetAttribute returns attribute value if it's present, otherwise
// it returns an empty string | func GetAttribute(e xml.StartElement, name xml.Name) string {
for _, a := range e.Attr {
if NameEquals(a.Name, name) {
return a.Value
}
}
return ""
} |
获取首字母
@param $arg
@return string | public static function getFirst($arg) {
$str = iconv('UTF-8', 'gb2312', $arg);//如果程序是gbk的,此行就要注释掉
if (!preg_match('/^[\x7f-\xff]/', $str)) {
return strtoupper($str[0]);
}
$firstChar=ord($str{0});
if($firstChar >= ord('A') && $firstChar <= ord('z')) {
return strtoupper($str{0});
}
$a = $str;
$val = ord($a{0}) * 256 + ord($a{1}) - 65536;
if ($val >= -20319 && $val <= -20284) {
return 'A';
}
if ($val >= -20283 && $val <= -19776) {
return 'B';
}
if ($val >= -19775 && $val <= -19219) {
return 'C';
}
if ($val >= -19218 && $val <= -18711) {
return 'D';
}
if ($val >= -18710 && $val <= -18527) {
return 'E';
}
if ($val >= -18526 && $val <= -18240) {
return 'F';
}
if ($val >= -18239 && $val <= -17923) {
return 'G';
}
if ($val >= -17922 && $val <= -17418) {
return 'H';
}
if ($val >= -17417 && $val <= -16475) {
return 'J';
}
if ($val >= -16474 && $val <= -16213) {
return 'K';
}
if ($val >= -16212 && $val <= -15641) {
return 'L';
}
if ($val >= -15640 && $val <= -15166) {
return 'M';
}
if ($val >= -15165 && $val <= -14923) {
return 'N';
}
if ($val >= -14922 && $val <= -14915) {
return 'O';
}
if ($val >= -14914 && $val <= -14631) {
return 'P';
}
if ($val >= -14630 && $val <= -14150) {
return 'Q';
}
if ($val >= -14149 && $val <= -14091) {
return 'R';
}
if ($val >= -14090 && $val <= -13319) {
return 'S';
}
if ($val >= -13318 && $val <= -12839) {
return 'T';
}
if ($val >= -12838 && $val <= -12557) {
return 'W';
}
if ($val >= -12556 && $val <= -11848) {
return 'X';
}
if ($val >= -11847 && $val <= -11056) {
return 'Y';
}
if ($val >= -11055 && $val <= -10247) {
return 'Z';
}
return strtoupper($str[0]);
} |
Loads a file content | def load_version():
""""""
filename = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"cpt", "__init__.py"))
with open(filename, "rt") as version_file:
conan_init = version_file.read()
version = re.search("__version__ = '([0-9a-z.-]+)'", conan_init).group(1)
return version |
Generates a recurrence iterator that iterates over the union of the given
recurrence iterators.
@param first the first recurrence iterator
@param rest the other recurrence iterators
@return the union iterator | public static RecurrenceIterator join(RecurrenceIterator first, RecurrenceIterator... rest) {
List<RecurrenceIterator> all = new ArrayList<RecurrenceIterator>();
all.add(first);
all.addAll(Arrays.asList(rest));
return new CompoundIteratorImpl(all, Collections.<RecurrenceIterator> emptyList());
} |
Loads {@link GroovyRunner} instances using the {@link ServiceLoader} facility.
@param classLoader used to locate provider-configuration files and classes | public void load(ClassLoader classLoader) {
Map<String, GroovyRunner> map = runnerMap; // direct read
if (map == null) {
map = getMap(); // initialize and load (recursive call), result ignored
if (classLoader == null) {
// getMap() already loaded using a null classloader
return;
}
}
writeLock.lock();
try {
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
cachedValues = null;
loadDefaultRunners();
loadWithLock(classLoader);
} catch (SecurityException se) {
LOG.log(Level.WARNING, "Failed to get the context ClassLoader", se);
} catch (ServiceConfigurationError sce) {
LOG.log(Level.WARNING, "Failed to load GroovyRunner services from ClassLoader " + classLoader, sce);
} finally {
writeLock.unlock();
}
} |
Subclasses may override this method. | def _insertSegment(self, index=None, type=None, points=None,
smooth=False, **kwargs):
onCurve = points[-1]
offCurve = points[:-1]
segments = self.segments
ptCount = sum([len(segments[s].points) for s in range(index)]) + 1
self.insertPoint(ptCount, onCurve, type=type, smooth=smooth)
for offCurvePoint in reversed(offCurve):
self.insertPoint(ptCount, offCurvePoint, type="offcurve") |
Get several objects from this index
@param objectIDs the array of unique identifier of objects to retrieve | public JSONObject getObjects(List<String> objectIDs) throws AlgoliaException {
return getObjects(objectIDs, null, RequestOptions.empty);
} |
Finds the first element.
@return the element | public WebElement find() {
checkState(webDriver != null, "No WebDriver specified.");
checkState(by != null, "No By instance for locating elements specified.");
if (!noLogging) {
log.info(toString());
}
WebElement element;
if (timeoutSeconds > 0L) {
WebDriverWait wait = createWebDriverWait();
element = wait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(final WebDriver input) {
WebElement el = input.findElement(by);
checkElement(el);
if (condition != null && !condition.apply(el)) {
throw new WebElementException(String.format("Condition not met for element %s: %s", el, condition));
}
return el;
}
@Override
public String toString() {
return WebElementFinder.this.toString();
}
});
} else {
element = webDriver.findElement(by);
checkElement(element);
if (condition != null && !condition.apply(element)) {
throw new WebElementException(String.format("Condition not met for element %s: %s", element, condition));
}
}
return element;
} |
Recursively create the function name by examining the object property.
@param obj Parsed object.
@return {string} The name of the function. | function buildName(obj) {
if (!obj) {
return parts.join('.');
}
if (obj.property && obj.property.name) {
parts.unshift(obj.property.name);
}
if (obj.object && obj.object.name) {
parts.unshift(obj.object.name);
}
return buildName(obj.object);
} |
set the logging level based on the environment
Parameters
==========
quiet: boolean if True, set to quiet. Gets overriden by environment
setting, and only exists to define default | def init_level(self, quiet=False):
'''
'''
if os.environ.get('MESSAGELEVEL') == "QUIET":
quiet = True
self.quiet = quiet |
Returns the name of this alias if path has been added
to the aliased portions of attributePath
@param path the path to test for inclusion in the alias | public String getAlias(String path)
{
if (m_allPathsAliased && m_attributePath.lastIndexOf(path) != -1)
{
return m_name;
}
Object retObj = m_mapping.get(path);
if (retObj != null)
{
return (String) retObj;
}
return null;
} |
@param string $name
@param string $value
@throws GatewayException | public function setConfigParam($name, $value)
{
if (!isset($this->configParams[$name])) {
throw new GatewayException('User undefined config param [' . $name . ']');
}
$this->configParams[$name] = $value;
} |
Register custom events. | private function registerEvents()
{
foreach ($this->getSetting('events', []) as $event => $listeners) {
foreach ($listeners as $listener) {
Event::bind($event, $listener);
}
}
} |
Get the formal version of framework.
@return string | public function version()
{
return 'Vinala v'.$this->framework->version.(!empty($this->framework->tag) ? ' '.$this->framework->tag : '').' ('.$this->framework->stat.') PHP Framework';
} |
Destination on Cloud Storage.
Generated from protobuf field <code>.google.cloud.asset.v1.GcsDestination gcs_destination = 1;</code>
@param \Google\Cloud\Asset\V1\GcsDestination $var
@return $this | public function setGcsDestination($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Asset\V1\GcsDestination::class);
$this->writeOneof(1, $var);
return $this;
} |
Generates SQL update table set ...
Returns (sql, parameters)
>>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5})
('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5]) | def sqlupdate(table, rowupdate, where):
validate_name(table)
fields = sorted(rowupdate.keys())
validate_names(fields)
values = [rowupdate[field] for field in fields]
setparts = [field + '=%s' for field in fields]
setclause = ', '.join(setparts)
sql = "update {} set ".format(table) + setclause
(whereclause, wherevalues) = sqlwhere(where)
if whereclause:
sql = sql + " where " + whereclause
return (sql, values + wherevalues) |
Show view in route call.
@param $url
@param $view
@return $this | public static function view($url, $view, $data = null)
{
$callback = function () use ($view, $data) {
$view = view($view);
if (!is_null($data)) {
foreach ($data as $key => $value) {
$view = $view->with($key, $value);
}
}
return $view;
};
static::get($url, $callback);
} |
Add the "run" button | function() {
jsBox.WiringEditor.superclass.renderButtons.call(this);
// Add the run button to the toolbar
var toolbar = YAHOO.util.Dom.get('toolbar');
var runButton = new YAHOO.widget.Button({ label:"Run", id:"WiringEditor-runButton", container: toolbar });
runButton.on("click", jsBox.run, jsBox, true);
} |
Find list of nodes with a CSS selector
@param string $selector
@param int $idx
@return NodeList|Element|null | public function find($selector, $idx = null)
{
$xPathQuery = SelectorConverter::toXPath($selector);
$xPath = new DOMXPath($this->document);
$nodesList = $xPath->query($xPathQuery);
$elements = new NodeList();
foreach ($nodesList as $node) {
$elements[] = new Element($node);
}
if (null === $idx) {
return $elements;
}
if ($idx < 0) {
$idx = count($elements) + $idx;
}
return isset($elements[$idx]) ? $elements[$idx] : null;
} |
// CreateConfigSignature creates a signature for the given client, custom signers and chConfig from channelConfigPath argument
// return ConfigSignature will be signed internally by the SDK. It can be passed to WithConfigSignatures() option | func (rc *Client) CreateConfigSignature(signer msp.SigningIdentity, channelConfigPath string) (*common.ConfigSignature, error) {
chConfig, err := readChConfigData(channelConfigPath)
if err != nil {
return nil, err
}
sigs, err := rc.createCfgSigFromIDs(chConfig, signer)
if err != nil {
return nil, err
}
if len(sigs) != 1 {
return nil, errors.New("creating a config signature for 1 identity did not return 1 signature")
}
return sigs[0], nil
} |
Gamma distribution PDF (with 0.0 for x < 0)
@param x query value
@param k Alpha
@param theta Theta = 1 / Beta
@return probability density | public static double logpdf(double x, double k, double theta) {
if(x < 0) {
return Double.NEGATIVE_INFINITY;
}
if(x == 0) {
return (k == 1.0) ? FastMath.log(theta) : Double.NEGATIVE_INFINITY;
}
if(k == 1.0) {
return FastMath.log(theta) - x * theta;
}
final double xt = x * theta;
return (xt == Double.POSITIVE_INFINITY) ? Double.NEGATIVE_INFINITY : //
FastMath.log(theta) + (k - 1.0) * FastMath.log(xt) - xt - logGamma(k);
} |
Create a new method definition with a different call handler.
@param handler to bind to a cloned instance of this.
@return a cloned instance of this with the new handler bound. | public ServerMethodDefinition<ReqT, RespT> withServerCallHandler(
ServerCallHandler<ReqT, RespT> handler) {
return new ServerMethodDefinition<>(method, handler);
} |
Get a user's language and locale.
@param string $separator
@return string | public function getLanguageLocale($separator = '-')
{
if (!is_array($this->languages)) {
LanguageDetector::detect($this, $this->getAcceptLanguage());
}
$userLanguage = $this->getLanguage();
foreach ($this->languages as $language) {
if (strlen($language) === 5 && strpos($language, $userLanguage) === 0) {
$locale = substr($language, -2);
break;
}
}
if (!empty($locale)) {
return $userLanguage . $separator . strtoupper($locale);
} else {
return $userLanguage;
}
} |
fold errors of same key to one error list, e.g. (key, error1), (key, error2) -+ (key, (error1, error2))
@return new created function | public static Function<List<Map.Entry<String, String>>, Map<String, List<String>>>
foldErrs() {
return (errors) -> {
logger.debug("folding errors");
return errors.stream()
.collect(Collectors.groupingBy(
Map.Entry::getKey,
HashMap::new,
Collectors.mapping(
Map.Entry::getValue,
Collectors.toList()
)
));
} |
Set data from an array
@param array $data
@return QueryString | protected function fromArray($data)
{
if (empty($data)) {
return $this;
}
$this->data = array_replace_recursive($this->data, $data);
return $this;
} |
If exactly one quote matches, delete it. Otherwise,
raise a ValueError. | def delete(self, lookup):
lookup, num = self.split_num(lookup)
if num:
result = self.find_matches(lookup)[num - 1]
else:
result, = self.find_matches(lookup)
self.db.delete_one(result) |
Animate in the series | function (init) {
var series = this,
chart = series.chart,
renderer = chart.renderer,
clipRect,
markerClipRect,
animation = series.options.animation,
clipBox = series.clipBox || chart.clipBox,
inverted = chart.inverted,
sharedClipKey;
// Animation option is set to true
if (animation && !isObject(animation)) {
animation = defaultPlotOptions[series.type].animation;
}
sharedClipKey = ['_sharedClip', animation.duration, animation.easing, clipBox.height].join(',');
// Initialize the animation. Set up the clipping rectangle.
if (init) {
// If a clipping rectangle with the same properties is currently present in the chart, use that.
clipRect = chart[sharedClipKey];
markerClipRect = chart[sharedClipKey + 'm'];
if (!clipRect) {
chart[sharedClipKey] = clipRect = renderer.clipRect(
extend(clipBox, { width: 0 })
);
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
series.group.clip(clipRect);
series.markerGroup.clip(markerClipRect);
series.sharedClipKey = sharedClipKey;
// Run the animation
} else {
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
}
} |
Implement MP CLI.
Usage::
import ocrd_click_cli from ocrd.utils
@click.command()
@ocrd_click_cli
def cli(mets_url):
print(mets_url) | def ocrd_cli_options(f):
params = [
click.option('-m', '--mets', help="METS URL to validate"),
click.option('-w', '--working-dir', help="Working Directory"),
click.option('-I', '--input-file-grp', help='File group(s) used as input.', default='INPUT'),
click.option('-O', '--output-file-grp', help='File group(s) used as output.', default='OUTPUT'),
click.option('-g', '--page-id', help="ID(s) of the pages to process"),
click.option('-p', '--parameter', type=click.Path()),
click.option('-J', '--dump-json', help="Dump tool description as JSON and exit", is_flag=True, default=False),
loglevel_option,
click.option('-V', '--version', help="Show version", is_flag=True, default=False)
]
for param in params:
param(f)
return f |
// SetAttachmentType sets the AttachmentType field's value. | func (s *GatewayAttachment) SetAttachmentType(v string) *GatewayAttachment {
s.AttachmentType = &v
return s
} |
Get the value of a hash field. | function hget(key, field, req) {
// get at db level
var val = this.getKey(key, req);
if(!val) return null;
// get at hash level
val = val.getKey(field)
if(!val) return null;
return val;
} |
If we are quoting a message | public function getQuoteMessage($qid, $tid)
{
$retVal = '';
// fire hook
$retVal = Container::get('hooks')->fire('model.post.begin_quote_message', $retVal, $qid, $tid);
$quote = DB::forTable('posts')->select_many(['poster', 'message'])
->where('id', $qid)
->where('topic_id', $tid);
$quote = Container::get('hooks')->fireDB('model.post.get_quote_message_query', $quote);
$quote = $quote->find_one();
if (!$quote) {
throw new RunBBException(__('Bad request'), 404);
}
// If the message contains a code tag we have to split it up (text within [code][/code] shouldn't be touched)
// if (strpos($quote->message, '[code]') !== false && strpos($quote->message, '[/code]') !== false) {
// list($inside, $outside) = split_text($quote->message, '[code]', '[/code]');
//
// $quote->message = implode("\1", $outside);
// }
// Remove [img] tags from quoted message
$quote->message = preg_replace(
'%\[img(?:=(?:[^\[]*?))?\]((ht|f)tps?://)([^\s<"]*?)\[/img\]%U',
'\1\3',
$quote->message
);
// If we split up the message before we have to concatenate it together again (code tags)
// if (isset($inside)) {
// $outside = explode("\1", $quote->message);
// $quote->message = '';
//
// $num_tokens = count($outside);
// for ($i = 0; $i < $num_tokens; ++$i) {
// $quote->message .= $outside[$i];
// if (isset($inside[$i])) {
// $quote->message .= '[code]'.$inside[$i].'[/code]';
// }
// }
//
// unset($inside);
// }
if (ForumSettings::get('o_censoring') == '1') {
$quote->message = Utils::censor($quote->message);
}
$quote->message = Utils::escape($quote->message);
if (ForumSettings::get('p_message_bbcode') == '1') { // Sanitize username for inclusion within QUOTE
// BBCode attribute.
// This is a bit tricky because a username can have any "special"
// characters such as backslash \ square brackets [] and quotes '".
// if (preg_match('/[[\]\'"]/S', $quote->poster)) {
// // Check if we need to quote it.
// // Post has special chars. Escape escapes and quotes then wrap in quotes.
// if (strpos($quote->poster, '"') !== false && strpos($quote->poster, '\'') === false)
// { // If there are double quotes but no single quotes, use single quotes,
// $quote->poster = Utils::escape(str_replace('\\', '\\\\', $quote->poster));
// $quote->poster = '\''. $quote->poster .'#'. $qid .'\'';
// } else { // otherwise use double quotes.
// $quote->poster = Utils::escape(str_replace(array('\\', '"'), array('\\\\', '\\"'),
// $quote->poster));
// $quote->poster = '"'. $quote->poster .'#'. $qid .'"';
// }
// } else {
// $quote->poster = $quote->poster .'#'. $qid;
// }
// $retVal = '[quote='. $quote->poster .']'.$quote->message.'[/quote]'."\n";
$retVal .= '> --- **'.$quote->poster.'** *['.__('wrote').']('.
Router::pathFor('viewPost', ['pid' => $qid]).'#p'.$qid.')*'."\n";
// ^ - beginning of a string. m - multiline.
$retVal .= preg_replace('/^/m', '>', $quote->message);
} else {
$quote->message .= preg_replace('/^/m', '>', $quote->message);
$retVal = '> --- '.$quote->poster.' '.__('wrote')."\n".$quote->message."\n";
}
$retVal = Container::get('hooks')->fire('model.post.finish_quote_message', $retVal);
return $retVal;
} |
Get the full Elasticsearch url
@param hostOrKey
@param index
@param type
@param id
@param query
@return | protected String getQueryUrl(String hostOrKey, String index, String type, String id, Object query) {
return getElasticSearchUrl(hostOrKey) + formatQueryUrl(index, type, id, query);
} |
Checks if the memory limit is exceeded and if so prunes the classifiers in the ensemble. | protected void enforceMemoryLimit() {
double memoryLimit = this.maxByteSizeOption.getValue() / (double) (this.ensemble.length + 1);
for (int i = 0; i < this.ensemble.length; i++) {
((HoeffdingTree) this.ensemble[(int) this.weights[i][1]].classifier).maxByteSizeOption.setValue((int) Math
.round(memoryLimit));
((HoeffdingTree) this.ensemble[(int) this.weights[i][1]].classifier).enforceTrackerLimit();
}
} |
@param SocialMediaTagsInterface $socialTags
@return $this | public function addSocialTags(SocialMediaTagsInterface $socialTags)
{
return $this
// Open Graph data
->addMeta([
'property' => 'og:title',
'content' => $socialTags->getOgTitle(),
'name' => 'og:title',
])->addMeta([
'property' => 'og:type',
'content' => $socialTags->getOgType(),
'name' => 'og:type',
])->addMeta([
'property' => 'og:url',
'content' => $socialTags->getOgUrl(),
'name' => 'og:url',
])->addMeta([
'property' => 'og:image',
'content' => $socialTags->getOgImage(),
'name' => 'og:image',
])->addMeta([
'property' => 'og:description',
'content' => $socialTags->getOgDescription(),
'name' => 'og:description',
])
// Schema.org markup for Google+
->addMeta([
'itemprop' => 'name',
'content' => $socialTags->getOgTitle(),
'name' => 'google:name',
])->addMeta([
'itemprop' => 'description',
'content' => $socialTags->getOgDescription(),
'name' => 'google:description',
])->addMeta([
'itemprop' => 'image',
'content' => $socialTags->getOgImage(),
'name' => 'google:image',
]);
} |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AppProjectList. | func (in *AppProjectList) DeepCopy() *AppProjectList {
if in == nil {
return nil
}
out := new(AppProjectList)
in.DeepCopyInto(out)
return out
} |
@param array $array
@return string | protected function buildMapDefinitions(array $array) {
$result = [];
foreach ($array as $alias => $value) {
$result[] = "\t\t\t" . "'" . str_replace("'", "\'", $alias) . "' => " . $value . ',';
}
return implode(PHP_EOL, $result);
} |
\
Creates a geo location URI.
:param float lat: Latitude
:param float lng: Longitude
:rtype: str | def make_geo_data(lat, lng):
def float_to_str(f):
return '{0:.8f}'.format(f).rstrip('0')
return 'geo:{0},{1}'.format(float_to_str(lat), float_to_str(lng)) |