comment
stringlengths
16
255
code
stringlengths
52
3.87M
Return the callbacks associated with a message template.
def get_callbacks_from_message(self, msg): """""" callbacks = [] for key in self._find_matching_keys(msg): for callback in self[key]: callbacks.append(callback) return callbacks
Find Denon and marantz devices advertising their services by upnp. @param {function} callback . @constructor
function MarantzDenonUPnPDiscovery(callback) { var that = this; var foundDevices = {}; // only report a device once // create socket var socket = dgram.createSocket({type: 'udp4', reuseAddr: true}); socket.unref(); const search = new Buffer([ 'M-SEARCH * HTTP/1.1', 'HOST: 239.255.255.250:1900', 'ST: upnp:rootdevice', 'MAN: "ssdp:discover"', 'MX: 3', '', '' ].join('\r\n')); socket.on('error', function(err) { console.log(`server error:\n${err.stack}`); socket.close(); }); socket.on('message', function(message, rinfo) { var messageString = message.toString(); console.log(messageString); if (messageString.match(/(d|D)enon/)) { location = messageString.match(/LOCATION: (.*?)(\d+\.\d+\.\d+\.\d+)(.*)/); if (location) { arp.getMAC(location[2], function(err, mac) { // lookup ip on the arp table to get the MacAddress if (!err) { if (foundDevices[mac]) { // only report foind devices once return; } var device = { friendlyName: '', ip: location[2], location: (location[1] + location[2] + location[3]).trim(), mac: mac, manufacturer: 'Unknown Manufacturer', model: 'Unknown Model' }; foundDevices[mac] = device; that.getUPnPInfo(device, function() { if (device.manufacturer == 'Unknown Manufacturer') { // still no info? that.getDeviceInfo(device, function() {callback(null, device);}, 80); } else { callback(null, device); } }); } }); } } }); socket.on('listening', function() { socket.addMembership('239.255.255.250'); socket.setMulticastTTL(4); const address = socket.address(); console.log(`server listening ${address.address}:${address.port}`); socket.send(search, 0, search.length, 1900, '239.255.255.250'); setTimeout(function() {socket.close();}, 5000); }); socket.bind(0); }
// ListSnapshots lists all the snapshot files in a particular directory and returns // the snapshot files in reverse lexical order (newest first)
func ListSnapshots(dirpath string) ([]string, error) { dirents, err := ioutil.ReadDir(dirpath) if err != nil { return nil, err } var snapshots []string for _, dirent := range dirents { if strings.HasSuffix(dirent.Name(), ".snap") { snapshots = append(snapshots, dirent.Name()) } } // Sort snapshot filenames in reverse lexical order sort.Sort(sort.Reverse(sort.StringSlice(snapshots))) return snapshots, nil }
Update the active marker on the marker Canvas
def update_active(self): """""" if self.active is not None: self.update_state(self.active, "normal") if self.current_iid == self.active: self._active = None return self._active = self.current_iid if self.active is not None: self.update_state(self.active, "active")
Tuns passive mode on or off. @param bool $pasv The passive mode. @return FTPClient Returns this FTP client. @throws FTPException Throws a FTP exception if an I/O error occurs.
public function pasv($pasv) { if (false === @ftp_pasv($this->getConnection(), $pasv)) { throw $this->newFTPException(sprintf("pasv from %d to %d failed", !$pasv, $pasv)); } return $this; }
encodes a String to Base64 String @param plain String to encode @return encoded String @throws CoderException @throws UnsupportedEncodingException
public static String encodeFromString(String plain, String charset) throws CoderException, UnsupportedEncodingException { return encode(plain.getBytes(charset)); }
// Encode converts a TagValue to the format in the connection.
func (v TagValue) Encode() string { ret := &bytes.Buffer{} for _, c := range v { if replacement, ok := tagEncodeMap[c]; ok { ret.WriteString(replacement) } else { ret.WriteRune(c) } } return ret.String() }
// Terms returns which languages the source repository was // built with
func (info *SourceRepositoryInfo) Terms() []string { terms := []string{} for i := range info.Types { terms = append(terms, info.Types[i].Term()) } return terms }
Acquire a MethodDesc from a type descriptor.
public static MethodDesc forDescriptor(String desc) throws IllegalArgumentException { try { int cursor = 0; char c; if ((c = desc.charAt(cursor++)) != '(') { throw invalidDescriptor(desc); } StringBuffer buf = new StringBuffer(); List<TypeDesc> list = new ArrayList<TypeDesc>(); while ((c = desc.charAt(cursor++)) != ')') { switch (c) { case 'V': case 'I': case 'C': case 'Z': case 'D': case 'F': case 'J': case 'B': case 'S': buf.append(c); break; case '[': buf.append(c); continue; case 'L': while (true) { buf.append(c); if (c == ';') { break; } c = desc.charAt(cursor++); } break; default: throw invalidDescriptor(desc); } list.add(TypeDesc.forDescriptor(buf.toString())); buf.setLength(0); } TypeDesc ret = TypeDesc.forDescriptor(desc.substring(cursor)); TypeDesc[] tds = list.toArray(new TypeDesc[list.size()]); return intern(new MethodDesc(desc, ret, tds)); } catch (NullPointerException e) { throw invalidDescriptor(desc); } catch (IndexOutOfBoundsException e) { throw invalidDescriptor(desc); } }
// SetRevisionId sets the RevisionId field's value.
func (s *CreateRobotApplicationOutput) SetRevisionId(v string) *CreateRobotApplicationOutput { s.RevisionId = &v return s }
Process callbacks from `call_from_executor` in eventloop.
def _process_callbacks(self): # Flush all the pipe content. os.read(self._schedule_pipe[0], 1024) # Process calls from executor. calls_from_executor, self._calls_from_executor = self._calls_from_executor, [] for c in calls_from_executor: c()
Clean and fire onWsConnect(). @param Swoole\Request $request @param Swoole\Response $response
function afterResponse(Swoole\Request $request, Swoole\Response $response) { if ($request->isWebSocket()) { $conn = array('header' => $request->header, 'time' => time()); $this->connections[$request->fd] = $conn; if (count($this->connections) > $this->max_connect) { $this->cleanConnection(); } $this->onWsConnect($request->fd, $request); } parent::afterResponse($request, $response); }
Creates a Memcached instance from the session options. @param OptionsBag $sessionOptions @return Memcached
public function create(OptionsBag $sessionOptions) { $options = $this->parseOptions($sessionOptions); $connections = $this->parse($sessionOptions); $persistentId = null; if ($options['persistent']) { $persistentId = $this->parsePersistentId($connections, $options, $sessionOptions); } $class = $this->class; /** @var Memcached $memcached */ $memcached = new $class( $persistentId, function (Memcached $memcached) use ($connections, $options) { $this->configure($memcached, $connections, $options); } ); return $memcached; }
Publication state. @return string
public function published() { $class = $this->entity->published ? 'fa fa-check-circle-o' : 'fa fa-circle-o'; $state = $this->entity->published ? 'Published' : 'Unpublished'; return html()->tag('i', '', ["class" => $class, "data-toggle" => "tooltip", "data-title" => $state]); }
Callback for 'routesTrigger' event. @param ModuleEvent $e @throws \Exception if the module returns an invalid route type @return $this
public function routesTrigger(ModuleEvent $e) { $module = $e->getModule(); if (is_callable(array($module, 'getRoutes'))) { $routes = $module->getRoutes(); $this->routes[$e->getModuleName()] = $routes; } return $this; }
Set the low and high watermarks for the read buffer.
def set_buffer_limits(self, high=None, low=None): """""" if high is None: high = self.default_buffer_size if low is None: low = high // 2 self._buffer_high = high self._buffer_low = low
GetMethodVariables.
public String getMethodVariables(String strMethodInterface) { int endChar = 0, startChar = 0; String strMethodVariables = ""; int i = 0; boolean bBracketFound = false; for (i = 0; i < strMethodInterface.length(); i++) { if (strMethodInterface.charAt(i) == '<') bBracketFound = true; if (strMethodInterface.charAt(i) == '>') bBracketFound = false; if (bBracketFound) continue; // Skip the area between the brackets. if (strMethodInterface.charAt(i) == ' ') startChar = i + 1; if (strMethodInterface.charAt(i) == ',') { endChar = i; if (endChar > startChar) { if (strMethodVariables.length() != 0) strMethodVariables += ", "; strMethodVariables += strMethodInterface.substring(startChar, endChar); } } } endChar = i; if (endChar > startChar) { if (strMethodVariables.length() != 0) strMethodVariables += ", "; strMethodVariables += strMethodInterface.substring(startChar, endChar); } return strMethodVariables; }
Tests if an alert is present @return: True if alert is present, False otherwise
def is_alert_present(self): current_frame = None try: current_frame = self.driver.current_window_handle a = self.driver.switch_to_alert() a.text except NoAlertPresentException: # No alert return False except UnexpectedAlertPresentException: # Alert exists return True finally: if current_frame: self.driver.switch_to_window(current_frame) return True
Generate a unique ID - that is friendly for a URL or file system @return a unique id
public String generateSanitizedId() { String result = this.generateId(); result = result.replace(':', '-'); result = result.replace('_', '-'); result = result.replace('.', '-'); return result; }
// Build and return package.xml
func (pb PackageBuilder) PackageXml() []byte { p := createPackage() for _, metaType := range pb.Metadata { p.Types = append(p.Types, metaType) } byteXml, _ := xml.MarshalIndent(p, "", " ") byteXml = append([]byte(xml.Header), byteXml...) //if err := ioutil.WriteFile("mypackage.xml", byteXml, 0644); err != nil { //ErrorAndExit(err.Error()) //} return byteXml }
Get all configuration values in a Properties object @return the properties
public Properties asProperties() { final Properties props = new Properties(); other.forEach(props::setProperty); props.setProperty("bootstrap.servers", bootstrapServers); return props; }
Main `ybt` console script entry point - run YABT from command-line.
def main(): """""" conf = init_and_get_conf() logger = make_logger(__name__) logger.info('YaBT version {}', __version__) handlers = { 'build': YabtCommand(func=cmd_build, requires_project=True), 'dot': YabtCommand(func=cmd_dot, requires_project=True), 'test': YabtCommand(func=cmd_test, requires_project=True), 'tree': YabtCommand(func=cmd_tree, requires_project=True), 'version': YabtCommand(func=cmd_version, requires_project=False), 'list-builders': YabtCommand(func=cmd_list, requires_project=False), } command = handlers[conf.cmd] if command.requires_project and not conf.in_yabt_project(): fatal('Not a YABT project (or any of the parent directories): {}', BUILD_PROJ_FILE) try: command.func(conf) except Exception as ex: fatal('{}', ex)
returns the home folder and program root depending on OS
def get_root_folder(): locations = { 'linux':{'hme':'/home/duncan/', 'core_folder':'/home/duncan/dev/src/python/AIKIF'}, 'win32':{'hme':'T:\\user\\', 'core_folder':'T:\\user\\dev\\src\\python\\AIKIF'}, 'cygwin':{'hme':os.getcwd() + os.sep, 'core_folder':os.getcwd()}, 'darwin':{'hme':os.getcwd() + os.sep, 'core_folder':os.getcwd()} } hme = locations[sys.platform]['hme'] core_folder = locations[sys.platform]['core_folder'] if not os.path.exists(core_folder): hme = os.getcwd() core_folder = os.getcwd() print('config.py : running on CI build (or you need to modify the paths in config.py)') return hme, core_folder
</editor-fold>//GEN-END:initComponents
private void menuAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAboutActionPerformed JOptionPane.showMessageDialog(Main.getApplicationFrame(), new AboutPanel(), "About", JOptionPane.PLAIN_MESSAGE); }
Returns the next color. Currently returns a random color from the Colorbrewer 11-class diverging BrBG palette. Returns ------- next_rgb_color: tuple of ImageColor
def next_color(self): next_rgb_color = ImageColor.getrgb(random.choice(BrBG_11.hex_colors)) return next_rgb_color
// SetContributor sets the Contributor field's value.
func (s *CommentMetadata) SetContributor(v *User) *CommentMetadata { s.Contributor = v return s }
Remove tags from a file. Args: filething (filething) Raises: mutagen.MutagenError
def delete(filething): dsf_file = DSFFile(filething.fileobj) if dsf_file.dsd_chunk.offset_metdata_chunk != 0: id3_location = dsf_file.dsd_chunk.offset_metdata_chunk dsf_file.dsd_chunk.offset_metdata_chunk = 0 dsf_file.dsd_chunk.write() filething.fileobj.seek(id3_location) filething.fileobj.truncate()
Filter the array according callback @param array $arr The array to be used @param callable $callback Function fired in array elements @return array The array filtered
public static function filter(array $arr, callable $callback): array { $arrResult = []; foreach ($arr as $index => $value) { if ($callback($value, $index) === true) { $arrResult[] = $value; } } return $arrResult; }
Fills the struct with the default parameter values as defined in provided parameter definition collection.
private function fillDefault(ParameterDefinitionCollectionInterface $definitionCollection): void { foreach ($definitionCollection->getParameterDefinitions() as $name => $definition) { $this->setParameterValue($name, $definition->getDefaultValue()); if ($definition instanceof CompoundParameterDefinition) { $this->fillDefault($definition); } } }
@param mixed $val @return float @throws \frictionlessdata\tableschema\Exceptions\FieldValidationException;
protected function validateCastValue($val) { if (isset($this->descriptor()->bareNumber) && $this->descriptor()->bareNumber === false) { return mb_ereg_replace('((^\D*)|(\D*$))', '', $val); } $isPercent = false; if (is_string($val)) { if (substr($val, -1) == '%') { $val = rtrim($val, '%'); $isPercent = true; } if (isset($this->descriptor()->groupChar)) { $val = str_replace($this->descriptor()->groupChar, '', $val); } if (isset($this->descriptor()->decimalChar) && $this->descriptor()->decimalChar != '.') { $val = str_replace($this->descriptor()->decimalChar, '.', $val); } } if (!is_numeric($val)) { throw $this->getValidationException('value must be numeric', $val); } else { $val = (float) $val; if ($isPercent) { $val = $val / 100; } return $val; } }
Registers all provider implementations for this {@code ServiceRegistry} found in the application classpath. @throws ServiceConfigurationError if an error occurred during registration
public void registerApplicationClasspathSPIs() { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Iterator<Class<?>> categories = categories(); while (categories.hasNext()) { Class<?> category = categories.next(); try { // Find all META-INF/services/ + name on class path String name = SERVICES + category.getName(); Enumeration<URL> spiResources = loader.getResources(name); while (spiResources.hasMoreElements()) { URL resource = spiResources.nextElement(); registerSPIs(resource, category, loader); } } catch (IOException e) { throw new ServiceConfigurationError(e); } } }
Get indices of neighbour simplices for each simplex and arc indices. Identical to get_neighbour_simplices() but also returns an array of indices that reside on boundary hull, -1 denotes no neighbour.
def neighbour_and_arc_simplices(self): nt, ltri, lct, ierr = _tripack.trlist(self.lst, self.lptr, self.lend, nrow=9) if ierr != 0: raise ValueError('ierr={} in trlist\n{}'.format(ierr, _ier_codes[ierr])) ltri = ltri.T[:nt] - 1 return ltri[:,3:6], ltri[:,6:]
Returns {@code true} if succeed to drop table, otherwise {@code false} is returned. @param tableName @return
public boolean dropTableIfExists(final String tableName) { Connection conn = getConnection(); try { return JdbcUtil.dropTableIfExists(conn, tableName); } finally { closeQuietly(conn); } }
@param bool $reset @return array
protected function getPins( $reset = false ) { if ( $reset ) { $this->_pins = []; } if ( empty( $this->_pins ) ) { $pins = get_transient( self::PIN ); if ( ! is_array( $pins ) ) { $pins = []; } $this->_pins = $pins; } return $this->_pins; }
Returns a dict that represents the user who prints the ws Keys: username, fullname, email
def _printedby_data(self, ws): data = {} member = self.context.portal_membership.getAuthenticatedMember() if member: username = member.getUserName() data['username'] = username data['fullname'] = to_utf8(self.user_fullname(username)) data['email'] = to_utf8(self.user_email(username)) c = [x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == username] if c: sf = c[0].getObject().getSignature() if sf: data['signature'] = sf.absolute_url() + "/Signature" return data
Execute a set of batched queries on the lighthouse schema and return a collection of ExecutionResults. @param \Nuwave\Lighthouse\Execution\GraphQLRequest $request @return mixed[]
public function executeRequest(GraphQLRequest $request): array { $result = $this->executeQuery( $request->query(), $this->createsContext->generate( app('request') ), $request->variables(), null, $request->operationName() ); return $this->applyDebugSettings($result); }
// Run implements Command.Run.
func (c *ListCommand) Run(ctx *cmd.Context) error { return c.RunWithAPI(ctx, func(api SpaceAPI, ctx *cmd.Context) error { spaces, err := api.ListSpaces() if err != nil { if errors.IsNotSupported(err) { ctx.Infof("cannot list spaces: %v", err) } return errors.Annotate(err, "cannot list spaces") } if len(spaces) == 0 { ctx.Infof("no spaces to display") if c.out.Name() == "tabular" { return nil } } if c.Short { result := formattedShortList{} for _, space := range spaces { result.Spaces = append(result.Spaces, space.Name) } return c.out.Write(ctx, result) } // Construct the output list for displaying with the chosen // format. result := formattedList{ Spaces: make(map[string]map[string]formattedSubnet), } for _, space := range spaces { result.Spaces[space.Name] = make(map[string]formattedSubnet) for _, subnet := range space.Subnets { subResult := formattedSubnet{ Type: typeUnknown, ProviderId: subnet.ProviderId, Zones: subnet.Zones, } // Display correct status according to the life cycle value. // // TODO(dimitern): Do this on the apiserver side, also // do the same for params.Space, so in case of an // error it can be displayed. switch subnet.Life { case params.Alive: subResult.Status = statusInUse case params.Dying, params.Dead: subResult.Status = statusTerminating } // Use the CIDR to determine the subnet type. // TODO(dimitern): Do this on the apiserver side. if ip, _, err := net.ParseCIDR(subnet.CIDR); err != nil { // This should never happen as subnets will be // validated before saving in state. msg := fmt.Sprintf("error: invalid subnet CIDR: %s", subnet.CIDR) subResult.Status = msg } else if ip.To4() != nil { subResult.Type = typeIPv4 } else if ip.To16() != nil { subResult.Type = typeIPv6 } result.Spaces[space.Name][subnet.CIDR] = subResult } } return c.out.Write(ctx, result) }) }
TODO: move this to IonConstants or IonUTF8
static final public int makeUTF8IntFromScalar(int c) throws IOException { // TO DO: check this encoding, it is from: // http://en.wikipedia.org/wiki/UTF-8 // we probably should use some sort of Java supported // library for this. this class might be of interest: // CharsetDecoder(Charset cs, float averageCharsPerByte, float maxCharsPerByte) // in: java.nio.charset.CharsetDecoder int value = 0; // first the quick, easy and common case - ascii if (c < 0x80) { value = (0xff & c ); } else if (c < 0x800) { // 2 bytes characters from 0x000080 to 0x0007FF value = ( 0xff & (0xC0 | (c >> 6) ) ); value |= ( 0xff & (0x80 | (c & 0x3F)) ) << 8; } else if (c < 0x10000) { // 3 byte characters from 0x800 to 0xFFFF // but only 0x800...0xD7FF and 0xE000...0xFFFF are valid if (c > 0xD7FF && c < 0xE000) { throwUTF8Exception(); } value = ( 0xff & (0xE0 | (c >> 12) ) ); value |= ( 0xff & (0x80 | ((c >> 6) & 0x3F)) ) << 8; value |= ( 0xff & (0x80 | (c & 0x3F)) ) << 16; } else if (c <= 0x10FFFF) { // 4 byte characters 0x010000 to 0x10FFFF // these are are valid value = ( 0xff & (0xF0 | (c >> 18)) ); value |= ( 0xff & (0x80 | ((c >> 12) & 0x3F)) ) << 8; value |= ( 0xff & (0x80 | ((c >> 6) & 0x3F)) ) << 16; value |= ( 0xff & (0x80 | (c & 0x3F)) ) << 24; } else { throwUTF8Exception(); } return value; }
// RankMatchFold is a case-insensitive version of RankMatch.
func RankMatchFold(source, target string) int { return rank(source, target, unicode.ToLower) }
Is column searched @param string $column @return bool
public function isColumnSearched( $column ) { $store = $this->getStore(); if ( isset( $store['search'][$column] ) ) { foreach ( $store['search'][$column] as $search ) { if ( ! empty( $search ) ) { return true; } } } return false; }
// DefineStatus converts the check result status from an integer to a string.
func DefineStatus(status int) string { eCode := "UNDEFINED_STATUS" for k, v := range sensuutil.MonitoringErrorCodes { if status == v { eCode = k } } return eCode }
// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
func (da *da_DK) WeekdayNarrow(weekday time.Weekday) string { return da.daysNarrow[weekday] }
Method called once every second by the scheduled job. @see #start(ScheduledExecutorService)
@SuppressWarnings( "fallthrough" ) private void rollup() { DateTime now = timeFactory.create(); Window largest = null; for (DurationHistory history : durations.values()) { largest = history.rollup(); } for (ValueHistory history : values.values()) { largest = history.rollup(); } if ( largest == null ) return; // Note that we do expect to fall through, as the 'largest' represents the largest window that was changed, // while all smaller windows were also changed ... switch (largest) { case PREVIOUS_52_WEEKS: this.weeksStartTime.set(now); // fall through!! case PREVIOUS_7_DAYS: this.daysStartTime.set(now); // fall through!! case PREVIOUS_24_HOURS: this.hoursStartTime.set(now); // fall through!! case PREVIOUS_60_MINUTES: this.minutesStartTime.set(now); // fall through!! case PREVIOUS_60_SECONDS: this.secondsStartTime.set(now); } }
@param string $name @param string $locale @return AttributeValueTranslation
protected function createAttributeValueTranslation($name, $locale) { $translation = new AttributeValueTranslation(); $translation->setName($name); $translation->setLocale($locale); return $translation; }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
public EClass getIfcRadiusDimension() { if (ifcRadiusDimensionEClass == null) { ifcRadiusDimensionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(419); } return ifcRadiusDimensionEClass; }
Sets the device_key of this DeviceData. The fingerprint of the device certificate. :param device_key: The device_key of this DeviceData. :type: str
def device_key(self, device_key): if device_key is not None and len(device_key) > 512: raise ValueError("Invalid value for `device_key`, length must be less than or equal to `512`") self._device_key = device_key
1. Fetch URL 2. Run automation. 3. Return HTML. 4. Close the tab.
def fetch(self, conf): url = conf['url'] # If Firefox is broken, it will raise here, causing kibitzr restart: self.driver.set_window_size(1366, 800) self.driver.implicitly_wait(2) self.driver.get(url) try: self._run_automation(conf) html = self._get_html() except: logger.exception( "Exception occurred while fetching" ) return False, traceback.format_exc() finally: self._close_tab() return True, html
/*Rocr100 - Rate of change ratio 100 scale: (price/prevPrice)*100 Input = double Output = double Optional Parameters ------------------- optInTimePeriod:(From 1 to 100000) Number of period */
func Rocr100(real []float64, timePeriod int32) []float64 { var outBegIdx C.int var outNBElement C.int outReal := make([]float64, len(real)) C.TA_ROCR100(0, C.int(len(real)-1), (*C.double)(unsafe.Pointer(&real[0])), C.int(timePeriod), &outBegIdx, &outNBElement, (*C.double)(unsafe.Pointer(&outReal[0]))) return outReal[:outNBElement] }
Creates a FLUSH_REQ message. @param body the data of the request. @return a protobuf message.
public static Message buildFlushRequest(ByteBuffer body) { ZabMessage.FlushRequest flushReq = ZabMessage.FlushRequest.newBuilder().setBody(ByteString.copyFrom(body)) .build(); return Message.newBuilder().setType(MessageType.FLUSH_REQ) .setFlushRequest(flushReq) .build(); }
Brand parent API URL arg. @since 160629 Brand URL args. @param string $arg Arg to create. @return string URL arg.
public function brandParentApiArg(string $arg = ''): string { return $this->App->Parent ? $this->App->Parent->Utils->§BrandUrl->brandApiArg($arg) : $this->brandApiArg($arg); }
Parse PDF files text content for keywords. Args: path: PDF file path. Returns: match: set of unique occurrences of every match.
def grepPDF(self, path): with open(path, 'rb') as pdf_file_obj: match = set() text = '' pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj) pages = pdf_reader.numPages for page in range(pages): page_obj = pdf_reader.getPage(page) text += '\n' + page_obj.extractText() match.update(set(x.lower() for x in re.findall( self._keywords, text, re.IGNORECASE))) return match
// Keys returns a new Array object that may be used to inspect objects keys. // // Example: // object := NewObject(t, map[string]interface{}{"foo": 123, "bar": 456}) // object.Keys().ContainsOnly("foo", "bar")
func (o *Object) Keys() *Array { keys := []interface{}{} for k := range o.value { keys = append(keys, k) } return &Array{o.chain, keys} }
Add a route for DOM event - IOS bugfix version @param {string} event_name @param {_cTarget} target
function(event_name, target) { if (this._is_inDOM && event_name == 'click' && !(event_name in this._events)) { this.getDOMElement().onclick = Lava.noop; } this.addEventTarget_Normal(event_name, target) }
// PingHandler is a simple handler that always responds with pong as text
func PingHandler(w http.ResponseWriter, r *http.Request) { if methodSupported(w, r) { fmt.Fprintf(w, "pong") } }
Defines wich actions will be inherited from the inherited controller. Syntax is borrowed from resource_controller. actions :index, :show, :edit actions :all, :except => :index
def actions(*actions_to_keep) raise ArgumentError, 'Wrong number of arguments. You have to provide which actions you want to keep.' if actions_to_keep.empty? options = actions_to_keep.extract_options! actions_to_remove = Array(options[:except]) actions_to_remove += ACTIONS - actions_to_keep.map { |a| a.to_sym } unless actions_to_keep.first == :all actions_to_remove.map! { |a| a.to_sym }.uniq! (instance_methods.map { |m| m.to_sym } & actions_to_remove).each do |action| undef_method action, "#{action}!" end end
Gather all information about dimensions and available space, called before every repositioning @private @returns {object}
function() { var self = this, $target = self._$origin, originIsArea = self._$origin.is('area'); // if this._$origin is a map area, the target we'll need // the dimensions of is actually the image using the map, // not the area itself if (originIsArea) { var mapName = self._$origin.parent().attr('name'); $target = $('img[usemap="#'+ mapName +'"]'); } var bcr = $target[0].getBoundingClientRect(), $document = $(env.window.document), $window = $(env.window), $parent = $target, // some useful properties of important elements geo = { // available space for the tooltip, see down below available: { document: null, window: null }, document: { size: { height: $document.height(), width: $document.width() } }, window: { scroll: { // the second ones are for IE compatibility left: env.window.scrollX || env.window.document.documentElement.scrollLeft, top: env.window.scrollY || env.window.document.documentElement.scrollTop }, size: { height: $window.height(), width: $window.width() } }, origin: { // the origin has a fixed lineage if itself or one of its // ancestors has a fixed position fixedLineage: false, // relative to the document offset: {}, size: { height: bcr.bottom - bcr.top, width: bcr.right - bcr.left }, usemapImage: originIsArea ? $target[0] : null, // relative to the window windowOffset: { bottom: bcr.bottom, left: bcr.left, right: bcr.right, top: bcr.top } } }, geoFixed = false; // if the element is a map area, some properties may need // to be recalculated if (originIsArea) { var shape = self._$origin.attr('shape'), coords = self._$origin.attr('coords'); if (coords) { coords = coords.split(','); $.map(coords, function(val, i) { coords[i] = parseInt(val); }); } // if the image itself is the area, nothing more to do if (shape != 'default') { switch(shape) { case 'circle': var circleCenterLeft = coords[0], circleCenterTop = coords[1], circleRadius = coords[2], areaTopOffset = circleCenterTop - circleRadius, areaLeftOffset = circleCenterLeft - circleRadius; geo.origin.size.height = circleRadius * 2; geo.origin.size.width = geo.origin.size.height; geo.origin.windowOffset.left += areaLeftOffset; geo.origin.windowOffset.top += areaTopOffset; break; case 'rect': var areaLeft = coords[0], areaTop = coords[1], areaRight = coords[2], areaBottom = coords[3]; geo.origin.size.height = areaBottom - areaTop; geo.origin.size.width = areaRight - areaLeft; geo.origin.windowOffset.left += areaLeft; geo.origin.windowOffset.top += areaTop; break; case 'poly': var areaSmallestX = 0, areaSmallestY = 0, areaGreatestX = 0, areaGreatestY = 0, arrayAlternate = 'even'; for (var i = 0; i < coords.length; i++) { var areaNumber = coords[i]; if (arrayAlternate == 'even') { if (areaNumber > areaGreatestX) { areaGreatestX = areaNumber; if (i === 0) { areaSmallestX = areaGreatestX; } } if (areaNumber < areaSmallestX) { areaSmallestX = areaNumber; } arrayAlternate = 'odd'; } else { if (areaNumber > areaGreatestY) { areaGreatestY = areaNumber; if (i == 1) { areaSmallestY = areaGreatestY; } } if (areaNumber < areaSmallestY) { areaSmallestY = areaNumber; } arrayAlternate = 'even'; } } geo.origin.size.height = areaGreatestY - areaSmallestY; geo.origin.size.width = areaGreatestX - areaSmallestX; geo.origin.windowOffset.left += areaSmallestX; geo.origin.windowOffset.top += areaSmallestY; break; } } } // user callback through an event var edit = function(r) { geo.origin.size.height = r.height, geo.origin.windowOffset.left = r.left, geo.origin.windowOffset.top = r.top, geo.origin.size.width = r.width }; self._trigger({ type: 'geometry', edit: edit, geometry: { height: geo.origin.size.height, left: geo.origin.windowOffset.left, top: geo.origin.windowOffset.top, width: geo.origin.size.width } }); // calculate the remaining properties with what we got geo.origin.windowOffset.right = geo.origin.windowOffset.left + geo.origin.size.width; geo.origin.windowOffset.bottom = geo.origin.windowOffset.top + geo.origin.size.height; geo.origin.offset.left = geo.origin.windowOffset.left + geo.window.scroll.left; geo.origin.offset.top = geo.origin.windowOffset.top + geo.window.scroll.top; geo.origin.offset.bottom = geo.origin.offset.top + geo.origin.size.height; geo.origin.offset.right = geo.origin.offset.left + geo.origin.size.width; // the space that is available to display the tooltip relatively to the document geo.available.document = { bottom: { height: geo.document.size.height - geo.origin.offset.bottom, width: geo.document.size.width }, left: { height: geo.document.size.height, width: geo.origin.offset.left }, right: { height: geo.document.size.height, width: geo.document.size.width - geo.origin.offset.right }, top: { height: geo.origin.offset.top, width: geo.document.size.width } }; // the space that is available to display the tooltip relatively to the viewport // (the resulting values may be negative if the origin overflows the viewport) geo.available.window = { bottom: { // the inner max is here to make sure the available height is no bigger // than the viewport height (when the origin is off screen at the top). // The outer max just makes sure that the height is not negative (when // the origin overflows at the bottom). height: Math.max(geo.window.size.height - Math.max(geo.origin.windowOffset.bottom, 0), 0), width: geo.window.size.width }, left: { height: geo.window.size.height, width: Math.max(geo.origin.windowOffset.left, 0) }, right: { height: geo.window.size.height, width: Math.max(geo.window.size.width - Math.max(geo.origin.windowOffset.right, 0), 0) }, top: { height: Math.max(geo.origin.windowOffset.top, 0), width: geo.window.size.width } }; while ($parent[0].tagName.toLowerCase() != 'html') { if ($parent.css('position') == 'fixed') { geo.origin.fixedLineage = true; break; } $parent = $parent.parent(); } return geo; }
// GetSuccessCount returns the number of successful controller runs
func (c *Controller) GetSuccessCount() int { c.mutex.RLock() defer c.mutex.RUnlock() return c.successCount }
// Update DataMin and DataMax according to the RangeModes.
func (r *Range) autoscale(x float64) { if x < r.DataMin && !r.MinMode.Fixed { if !r.MinMode.Constrained { // full autoscaling r.DataMin = x } else { r.DataMin = fmin(fmax(x, r.MinMode.Lower), r.DataMin) } } if x > r.DataMax && !r.MaxMode.Fixed { if !r.MaxMode.Constrained { // full autoscaling r.DataMax = x } else { r.DataMax = fmax(fmin(x, r.MaxMode.Upper), r.DataMax) } } }
Render layout from view @since 1.0 @return string|bool Return View content if success or false if error
public function render() { $viewPath = $this->getDirectory() . '/'. $this->getName() . '.' . $this->getExtension(); if (!file_exists($viewPath)) { trigger_error('View file "' . $viewPath . '" doesn\'t exist.', E_USER_ERROR); return false; } if (Configuration::read('mvc.autoload_shared_var') && !empty($this->variableList)) { foreach ($this->variableList as $varName => $varValue) { ${$varName} = $varValue; } } ob_start(); require($viewPath); echo PHP_EOL; return ob_get_clean(); }
format phone number in E123 national format with cursor position handling. @param pphoneNumber phone number as String to format with cursor position @param pcountryCode iso code of country @return formated phone number as String with new cursor position
public final ValueWithPos<String> formatE123NationalWithPos( final ValueWithPos<String> pphoneNumber, final String pcountryCode) { return valueWithPosDefaults( this.formatE123NationalWithPos(this.parsePhoneNumber(pphoneNumber, pcountryCode)), pphoneNumber); }
// GetAWSBatchJobDefinitionWithName retrieves all AWSBatchJobDefinition items from an AWS CloudFormation template // whose logical ID matches the provided name. Returns an error if not found.
func (t *Template) GetAWSBatchJobDefinitionWithName(name string) (*resources.AWSBatchJobDefinition, error) { if untyped, ok := t.Resources[name]; ok { switch resource := untyped.(type) { case *resources.AWSBatchJobDefinition: return resource, nil } } return nil, fmt.Errorf("resource %q of type AWSBatchJobDefinition not found", name) }
// HasIP provides a mock function with given fields: ctx, poolID, ipAddr
func (_m *FacadeInterface) HasIP(ctx datastore.Context, poolID string, ipAddr string) (bool, error) { ret := _m.Called(ctx, poolID, ipAddr) var r0 bool if rf, ok := ret.Get(0).(func(datastore.Context, string, string) bool); ok { r0 = rf(ctx, poolID, ipAddr) } else { r0 = ret.Get(0).(bool) } var r1 error if rf, ok := ret.Get(1).(func(datastore.Context, string, string) error); ok { r1 = rf(ctx, poolID, ipAddr) } else { r1 = ret.Error(1) } return r0, r1 }
@param Validator $validator @param mixed $object @param $forScenario @return bool
public function validate(Validator $validator, $object, $forScenario) { if (!is_array($object) && !$object instanceof \Traversable) { return false; } foreach ($object as $v) { if(!$this->rule->validate($validator, $v, $forScenario)) { return false; } } return true; }
Called when new data received @return void
protected function onRead() { start: if ($this->getInputLength() < 5) { return; } /* @TODO: refactoring Binary::* to support direct buffer calls */ $pct = $this->read(4096); $h = Binary::getDWord($pct); if ($h !== 0xFFFFFFFF) { $this->finish(); return; } $type = Binary::getChar($pct); if (($type === Pool::S2A_INFO) || ($type === Pool::S2A_INFO_SOURCE)) { $result = self::parseInfo($pct, $type); } elseif ($type === Pool::S2A_PLAYER) { $result = self::parsePlayers($pct); } elseif ($type === Pool::S2A_SERVERQUERY_GETCHALLENGE) { $result = mb_orig_substr($pct, 0, 4); $pct = mb_orig_substr($pct, 5); } elseif ($type === Pool::S2A_PONG) { $result = true; } else { $result = null; } $this->onResponse->executeOne($this, $result); $this->checkFree(); goto start; }
Useful for triggering a subset of the benchmark in a profiler.
public static void main(String[] argv) throws Exception { StreamingResponseBandwidthBenchmark bench = new StreamingResponseBandwidthBenchmark(); bench.setup(); Thread.sleep(30000); bench.teardown(); System.exit(0); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
public function handle($request, Closure $next) { $route = Route::currentRouteName(); $method = $request->method(); $parameters = Route::current()->parameters(); $hackedRoute = routeHack($route,$parameters); // if user destroy route if ( $method == 'GET' && in_array($route, $this->userDestroyRoutes) && !is_null(Request::route('users')) && Request::route('users')->id === Sentinel::getUser()->id ) { abort(403); } // dd($hackedRoute); if ( $method == 'GET' && ! in_array($route, $this->exceptRoutes) && ! Sentinel::getUser()->is_super_admin && ( ( ! in_array($route, $this->userRoutes) || is_null(Request::route('users')) || Request::route('users')->id !== Sentinel::getUser()->id ) && ! hasPermission($hackedRoute) ) ) { abort(403); } return $next($request); }
returns an array of every folder that is a component
def components return @components if @components @components = {} app_folders do |app_folder| Dir["#{app_folder}/*"].sort.each do |folder| if File.directory?(folder) folder_name = folder[/[^\/]+$/] # Add in the folder if it's not alreay in there folders = (@components[folder_name] ||= []) folders << folder unless folders.include?(folder) end end end @components end
Function to extract the template lists @static @access public @param string $sListName @return void
public static function ExtractList($sListName){ $oThis = self::CreateInstanceIfNotExists(); $iStart = strpos($oThis->sBuffer, "{list:{$sListName}}"); if($iStart > 0) $iEnd = strpos($oThis->sBuffer, "{end}", $iStart); if($iStart > 0 && $iEnd > 0){ $sNewBuffer = substr($oThis->sBuffer, $iStart, $iEnd-$iStart); $oThis->sBuffer = $sNewBuffer."{end}"; } }
// Create implements resource create
func (command HelloWorldResource) Create(awsSession *session.Session, event *CloudFormationLambdaEvent, logger *logrus.Logger) (map[string]interface{}, error) { requestPropsErr := json.Unmarshal(event.ResourceProperties, &command) if requestPropsErr != nil { return nil, requestPropsErr } logger.Info("create: Hello ", command.Message.Literal) return map[string]interface{}{ "Resource": "Created message: " + command.Message.Literal, }, nil }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public void eUnset(int featureID) { switch (featureID) { case SarlPackage.SARL_BEHAVIOR__EXTENDS: setExtends((JvmParameterizedTypeReference)null); return; } super.eUnset(featureID); }
Add the requested post parameters to the Request. @param request Request to add post params to
private void addPostParams(final Request request) { if (language != null) { request.addPostParam("Language", language); } if (taggedText != null) { request.addPostParam("TaggedText", taggedText); } if (sourceChannel != null) { request.addPostParam("SourceChannel", sourceChannel); } }
Write log @param string $state State of the payment process @param array $data Data of the log @param string $orderId External ID of order @return void
public function logFunc($state = '', $data = array(), $orderId = 0) { if ($this->logger) { $date = @date('Y-m-d H:i:s', time()); $logFile = $this->logPath . '/' . @date('Ymd', time()) . '.log'; if (!is_writable($this->logPath)) { $msg = 'LOG: log folder (' . $this->logPath . ') is not writable '; if (!in_array($msg, $this->debugMessage)) { $this->debugMessage[] = $msg; } return false; } if (file_exists($logFile)) { if (!is_writable($logFile)) { $msg = 'LOG: log file (' . $logFile . ') is not writable '; if (!in_array($msg, $this->debugMessage)) { $this->debugMessage[] = $msg; } return false; } } $logtext = $orderId . ' ' . $state . ' ' . $date . ' RUN_MODE=' . $this->runMode . "\n"; foreach ($data as $logkey => $logvalue) { if (is_object($logvalue)) { $logvalue = (array) $logvalue; } if (is_array($logvalue)) { foreach ($logvalue as $subvalue) { if (is_object($subvalue)) { $subvalue = (array) $subvalue; } if (is_array($subvalue)) { foreach ($subvalue as $subvalue2Key => $subvalue2Value) { $logtext .= $orderId . ' ' . $state . ' ' . $date . ' ' . $subvalue2Key . '=' . $subvalue2Value . "\n"; } } else { $logtext .= $orderId . ' ' . $state . ' ' . $date . ' ' . $logkey . '=' . $subvalue . "\n"; } } } elseif (!is_array($logvalue)) { $logtext .= $orderId . ' ' . $state . ' ' . $date . ' ' . $logkey . '=' . $logvalue . "\n"; } } file_put_contents($logFile, $logtext, FILE_APPEND | LOCK_EX); } }
This method validates if the user object is valid. A user is valid if username and password exist OR oauth integration exists.
def valid_user if (self.username.blank? || self.password_digest.blank?) && (self.oauth_provider.blank? || self.oauth_uid.blank?) errors.add(:username, " and password OR oauth must be specified") end end
Marshall the given parameter object.
public void marshall(LambdaFunctionFailedEventAttributes lambdaFunctionFailedEventAttributes, ProtocolMarshaller protocolMarshaller) { if (lambdaFunctionFailedEventAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(lambdaFunctionFailedEventAttributes.getScheduledEventId(), SCHEDULEDEVENTID_BINDING); protocolMarshaller.marshall(lambdaFunctionFailedEventAttributes.getStartedEventId(), STARTEDEVENTID_BINDING); protocolMarshaller.marshall(lambdaFunctionFailedEventAttributes.getReason(), REASON_BINDING); protocolMarshaller.marshall(lambdaFunctionFailedEventAttributes.getDetails(), DETAILS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Marshall the given parameter object.
public void marshall(DescribeNotebookInstanceRequest describeNotebookInstanceRequest, ProtocolMarshaller protocolMarshaller) { if (describeNotebookInstanceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeNotebookInstanceRequest.getNotebookInstanceName(), NOTEBOOKINSTANCENAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Generates a TSIG record with a specific error for a message and adds it to the message. @param m The message @param error The error @param old If this message is a response, the TSIG from the request
public void apply(Message m, int error, TSIGRecord old) { Record r = generate(m, m.toWire(), error, old); m.addRecord(r, Section.ADDITIONAL); m.tsigState = Message.TSIG_SIGNED; }
// Iterate is a set of helpers for iteration. Context may be used to cancel execution. // Iterator will be optimized and closed after execution. // // By default, iteration has no limit and includes sub-paths.
func Iterate(ctx context.Context, it Iterator) *IterateChain { if ctx == nil { ctx = context.Background() } return &IterateChain{ ctx: ctx, it: it, limit: -1, paths: true, optimize: true, } }
Given the H,S,B (equivalent to H,S,V) values for the HSB color mode, convert them into the R,G,B values for the RGB color mode and return a color tuple. This conversion is necessary because Cairo understands only RGB(A).
def colorHSB(h, s, b): H, S, B = float(h), float(s/100), float(b/100) if S == 0.0: return (B, B, B) # achromatic (grey) h = H / 60 i = math.floor(h) f = h - i v = B p = v * (1 - S) q = v * (1 - S * f) t = v * (1 - S * (1 - f)) if i == 0: return (v, t, b) elif i == 1: return (q, v, p) elif i == 2: return (p, v, t) elif i == 3: return (p, q, v) elif i == 4: return (t, p, v) else: # i == 5 (or i == 6 for the case of H == 360) return (v, p, q)
// readStats reads the query statisitcs off the response trailers.
func (s *statsResultIterator) readStats() { data := s.resp.Trailer.Get(queryStatisticsTrailer) if data != "" { s.err = json.Unmarshal([]byte(data), &s.statisitcs) } }
// Return a context that inherits all values from the parent ctx and specifies // the login provider name given here. Intended to be invoked before calls to // Login().
func WithLoginProvider(ctx context.Context, providerName string) context.Context { return context.WithValue(ctx, loginProviderNameKey, providerName) }
Attach a remote entry to a local entry
def attach(self, remote_entry): """""" self.name = remote_entry.name self.sha = remote_entry.sha self.url = remote_entry.url self.author = remote_entry.author return self
Convert bytes into a human-readable format. For example: $bytes = 1024 would return 1KB, $bytes = 1048576 would return 1MB, etc. @param int $bytes The number of bytes to convert. @return string The human readable representation of the bytes.
public static function make_human_readable_filesize($bytes) { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); $num_units = count($units); $size = $bytes; foreach ($units as $i => $unit) { if ($size < 1024 || (($i + 1) === $num_units)) { return round($size, 2).$unit; } $size = $size / 1024; } return $size; }
Renames the specified document. Args: - did (str): Document ID - name (str): New document name Returns: - requests.Response: Onshape response data
def rename_document(self, did, name): ''' ''' payload = { 'name': name } return self._api.request('post', '/api/documents/' + did, body=payload)
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this.
def value_to_python(self, value): if not isinstance(value, bytes): raise tldap.exceptions.ValidationError("should be a bytes") try: value = int(value) except (TypeError, ValueError): raise tldap.exceptions.ValidationError("is invalid integer") try: value = datetime.date.fromtimestamp(value * 24 * 60 * 60) except OverflowError: raise tldap.exceptions.ValidationError("is too big a date") return value
Extract required data only from CIU database @param {Object} data Raw Can I Use database @return {Object} Optimized database
function optimize(data) { if (typeof data == 'string') { data = JSON.parse(data); } return { vendors: parseVendors(data), css: parseCSS(data), era: parseEra(data) }; }
// CryptEncoderSSHA1 encodes a password with SHA1 with the // configured salt.
func CryptEncoderSSHA1(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha1.Sum(p) return h[:] } }
@param string $fid @return array @throws InvalidFidException
public static function getTypes($fid) { $parts = explode(':', $fid); switch(count($parts)) { case 5: return [$parts[1], $parts[2]]; case 4: return [$parts[1], $parts[1]]; default: throw new InvalidFidException("Invalid FID Passed '$fid'", 500); } }
Add listeners @param \Illuminate\Events\Dispatcher $obEvent
public function subscribe($obEvent) { parent::subscribe($obEvent); Product::extend(function ($obModel) { /** @var Product $obModel */ $bSlugIsTranslatable = Settings::getValue('slug_is_translatable'); if ($bSlugIsTranslatable) { $obModel->translatable[] = ['slug', 'index' => true]; } }); }
// HasKey calls a HasKey method to RPC server.
func (s *GlobalStore) HasKey(addr common.Address, key []byte) bool { var has bool if err := s.client.Call(&has, "mockStore_hasKey", addr, key); err != nil { log.Error(fmt.Sprintf("mock store HasKey: addr %s, key %064x: %v", addr, key, err)) return false } return has }
Create a function that can be used to insert nodes after the one given as argument.
function pointAt(node){ var parent = node.parentNode; var next = node.nextSibling; return function(newnode) { parent.insertBefore(newnode, next); }; }
Getter EVRs dictionary
def evrs(self): """""" if self._evrs is None: import ait.core.evr as evr self._evrs = evr.getDefaultDict() return self._evrs
Registers a {@link MessageHandler} that handles the received messages of the specified <code>type</code>. @return the old handler if there is already a registered handler for the specified <tt>type</tt>. <tt>null</tt> otherwise.
@SuppressWarnings("unchecked") public <E> MessageHandler<? super E> addReceivedMessageHandler(Class<E> type, MessageHandler<? super E> handler) { receivedMessageHandlerCache.clear(); return (MessageHandler<? super E>) receivedMessageHandlers.put(type, handler); }
Read bits and interpret as an octal string.
def _readoct(self, length, start): """""" if length % 3: raise InterpretError("Cannot convert to octal unambiguously - " "not multiple of 3 bits.") if not length: return '' # Get main octal bit by converting from int. # Strip starting 0 or 0o depending on Python version. end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:] if end.endswith('L'): end = end[:-1] middle = '0' * (length // 3 - len(end)) return middle + end
Method: clone Create a clone of this layer Paramters: obj - {Object} An optional layer (is this ever used?) Returns: {<OpenLayers.Layer.Image>} An exact copy of this layer
function(obj) { if(obj == null) { obj = new OpenLayers.Layer.Image(this.name, this.url, this.extent, this.size, this.getOptions()); } //get all additions from superclasses obj = OpenLayers.Layer.prototype.clone.apply(this, [obj]); // copy/set any non-init, non-simple values here return obj; }
Return the referrer hostname.
def _get_cookie_referrer_host(self): '''''' referer = self._original_request.fields.get('Referer') if referer: return URLInfo.parse(referer).hostname else: return None
返回用户感兴趣的标签 对应API:{@link http://open.weibo.com/wiki/2/tags/suggestions tags/suggestions} @access public @param int $count 单页大小。缺省值10,最大值10。可选。 @return array
function get_suggest_tags( $count = 10) { $params = array(); $params['count'] = intval($count); return $this->oauth->get( 'tags/suggestions', $params ); }
Done action. @param Request $request @return Response
public function doneAction(Request $request) { $debug = $this->container->getParameter('kernel.debug'); $token = $this->getHttpRequestVerifier()->verify($request); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); $gateway->execute($done = new Done($token)); if (!$debug) { $this->getHttpRequestVerifier()->invalidate($token); } /** @var \Ekyna\Component\Sale\Payment\PaymentInterface $payment */ $payment = $done->getFirstModel(); $event = new PaymentEvent($payment); $this->getDispatcher()->dispatch(PaymentEvents::DONE, $event); if (null !== $response = $event->getResponse()) { return $response; } if ($debug) { return $this->render('EkynaPaymentBundle:Payment:done.html.twig', [ 'payment' => $payment, ]); } return $this->redirect('/'); }
Create a PHP script returning the cached value @param mixed $value @param int|null $ttl @return string
public function createScript($value, ?int $ttl): string { $macro = var_export($value, true); if (strpos($macro, 'stdClass::__set_state') !== false) { $macro = preg_replace_callback("/('([^'\\\\]++|''\\.)')|stdClass::__set_state/", $macro, function($match) { return empty($match[1]) ? '(object)' : $match[1]; }); } return $ttl !== null ? "<?php return time() < {$ttl} ? {$macro} : false;" : "<?php return {$macro};"; }
Deprecated. Returns the data as a `list`
def data(self): """""" import warnings warnings.warn( '`data` attribute is deprecated and will be removed in a future release, ' 'use %s as an iterable instead' % (PaginatedResponse,), category=DeprecationWarning, stacklevel=2 # log wherever '.data' is referenced, rather than this line ) return list(self)
Remove routing group from the storage.
def group_remove(name, **kwargs): ctx = Context(**kwargs) ctx.execute_action('group:remove', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, })