answer
stringlengths
15
1.25M
<?php namespace Protalk\MediaBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class ProtalkMediaBundle extends Bundle { }
let Mousetrap = require('mousetrap'); export default function trapMice() { Mousetrap.bind('alt+f', function () { $("#<API key>").focus(); }); }
/** * @author UCSD MOOC development team * * Abstract grader class that includes methods common to concrete graders. * */ package ucsd.graph.grader; import java.io.PrintWriter; public abstract class Grader implements Runnable { public String feedback = ""; public int correct = 0; protected static final int TESTS = 10; /* Formats output to look nice */ public static String makeOutput(double score, String feedback) { return "Score: " + score + "\nFeedback: " + feedback; } /* Print test descriptions neatly */ public static String appendFeedback(int num, String test) { return "\n**Test #" + num + ": " + test + "..."; } }
# This file is part of beets. # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # included in all copies or substantial portions of the Software. """Allows beets to embed album art into file metadata.""" import os.path import logging import imghdr import subprocess import platform from tempfile import NamedTemporaryFile from beets.plugins import BeetsPlugin from beets import mediafile from beets import ui from beets.ui import decargs from beets.util import syspath, normpath, displayable_path from beets.util.artresizer import ArtResizer from beets import config log = logging.getLogger('beets') class EmbedCoverArtPlugin(BeetsPlugin): """Allows albumart to be embedded into the actual files. """ def __init__(self): super(EmbedCoverArtPlugin, self).__init__() self.config.add({ 'maxwidth': 0, 'auto': True, 'compare_threshold': 0, }) if self.config['maxwidth'].get(int) and not ArtResizer.shared.local: self.config['maxwidth'] = 0 log.warn(u"embedart: ImageMagick or PIL not found; " u"'maxwidth' option ignored") if self.config['compare_threshold'].get(int) and not \ ArtResizer.shared.can_compare: self.config['compare_threshold'] = 0 log.warn(u"embedart: ImageMagick 6.8.7 or higher not installed; " u"'compare_threshold' option ignored") def commands(self): # Embed command. embed_cmd = ui.Subcommand( 'embedart', help='embed image files into file metadata' ) embed_cmd.parser.add_option( '-f', '--file', metavar='PATH', help='the image file to embed' ) maxwidth = config['embedart']['maxwidth'].get(int) compare_threshold = config['embedart']['compare_threshold'].get(int) def embed_func(lib, opts, args): if opts.file: imagepath = normpath(opts.file) for item in lib.items(decargs(args)): embed_item(item, imagepath, maxwidth, None, compare_threshold) else: for album in lib.albums(decargs(args)): embed_album(album, maxwidth) embed_cmd.func = embed_func # Extract command. extract_cmd = ui.Subcommand('extractart', help='extract an image from file metadata') extract_cmd.parser.add_option('-o', dest='outpath', help='image output file') def extract_func(lib, opts, args): outpath = normpath(opts.outpath or 'cover') item = lib.items(decargs(args)).get() extract(outpath, item) extract_cmd.func = extract_func # Clear command. clear_cmd = ui.Subcommand('clearart', help='remove images from file metadata') def clear_func(lib, opts, args): clear(lib, decargs(args)) clear_cmd.func = clear_func return [embed_cmd, extract_cmd, clear_cmd] @EmbedCoverArtPlugin.listen('album_imported') def album_imported(lib, album): """Automatically embed art into imported albums. """ if album.artpath and config['embedart']['auto']: embed_album(album, config['embedart']['maxwidth'].get(int)) def embed_item(item, imagepath, maxwidth=None, itempath=None, compare_threshold=0): """Embed an image into the item's media file. """ if compare_threshold: if not <API key>(item, imagepath, compare_threshold): log.warn('Image not similar, skipping it.') return try: log.info(u'embedart: writing %s', displayable_path(imagepath)) item['images'] = [_mediafile_image(imagepath, maxwidth)] except IOError as exc: log.error(u'embedart: could not read image file: {0}'.format(exc)) else: # We don't want to store the image in the database item.try_write(itempath) del item['images'] def embed_album(album, maxwidth=None): """Embed album art into all of the album's items. """ imagepath = album.artpath if not imagepath: log.info(u'No album art present: {0} - {1}'. format(album.albumartist, album.album)) return if not os.path.isfile(imagepath): log.error(u'Album art not found at {0}' .format(imagepath)) return log.info(u'Embedding album art into {0.albumartist} - {0.album}.' .format(album)) for item in album.items(): embed_item(item, imagepath, maxwidth, None, config['embedart']['compare_threshold'].get(int)) def <API key>(item, imagepath, compare_threshold): """A boolean indicating if an image is similar to embedded item art. """ with NamedTemporaryFile(delete=True) as f: art = extract(f.name, item) if art: # Converting images to grayscale tends to minimize the weight # of colors in the diff score cmd = 'convert {0} {1} -colorspace gray MIFF:- | ' \ 'compare -metric PHASH - null:'.format(syspath(imagepath), syspath(art)) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=platform.system() != 'Windows', shell=True) stdout, stderr = proc.communicate() if proc.returncode: if proc.returncode != 1: log.warn(u'embedart: IM phashes compare failed for {0}, \ {1}'.format(displayable_path(imagepath), displayable_path(art))) return phashDiff = float(stderr) else: phashDiff = float(stdout) log.info(u'embedart: compare PHASH score is {0}'.format(phashDiff)) if phashDiff > compare_threshold: return False return True def _mediafile_image(image_path, maxwidth=None): """Return a `mediafile.Image` object for the path. If maxwidth is set the image is resized if necessary. """ if maxwidth: image_path = ArtResizer.shared.resize(maxwidth, syspath(image_path)) with open(syspath(image_path), 'rb') as f: data = f.read() return mediafile.Image(data, type=mediafile.ImageType.front) # 'extractart' command. def extract(outpath, item): if not item: log.error(u'No item matches query.') return # Extract the art. try: mf = mediafile.MediaFile(syspath(item.path)) except mediafile.UnreadableFileError as exc: log.error(u'Could not extract art from {0}: {1}'.format( displayable_path(item.path), exc )) return art = mf.art if not art: log.error(u'No album art present in {0} - {1}.' .format(item.artist, item.title)) return # Add an extension to the filename. ext = imghdr.what(None, h=art) if not ext: log.error(u'Unknown image type.') return outpath += '.' + ext log.info(u'Extracting album art from: {0.artist} - {0.title} ' u'to: {1}'.format(item, displayable_path(outpath))) with open(syspath(outpath), 'wb') as f: f.write(art) return outpath # 'clearart' command. def clear(lib, query): log.info(u'Clearing album art from items:') for item in lib.items(query): log.info(u'{0} - {1}'.format(item.artist, item.title)) try: mf = mediafile.MediaFile(syspath(item.path), config['id3v23'].get(bool)) except mediafile.UnreadableFileError as exc: log.error(u'Could not clear art from {0}: {1}'.format( displayable_path(item.path), exc )) continue mf.art = None mf.save()
# JewelCraft jewelry design toolkit for Blender. # This program is free software: you can redistribute it and/or modify # (at your option) any later version. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from mathutils import Matrix from .. import var from ..lib import unit, mesh, asset class DataCollect: def data_collect(self, context): import collections scene = context.scene depsgraph = context.depsgraph props = scene.jewelcraft UScale = unit.Scale() _from_scene = UScale.from_scene data = { "size": 0.0, "shank": [], "dim": [], "weight": 0.0, "gems": collections.defaultdict(int), "warn": [], } # Size if props.<API key>: ob = props.<API key> size = max(ob.dimensions) data["size"] = _from_scene(size) # Shank if props.<API key>: ob = props.<API key> asset.mod_curve_off(ob, reverse=True) dim = list(ob.dimensions) scene.update() dim.remove(max(dim)) data["shank"] = _from_scene(dim, batch=True) # Dimensions if props.<API key>: ob = props.<API key> data["dim"] = _from_scene(ob.dimensions.to_tuple(), batch=True) # Weight if props.<API key>: ob = props.<API key> if ob.type == "MESH": data["weight"] = _from_scene(mesh.est_volume((ob,)), volume=True) # Gems gems = data["gems"] known_stones = var.STONE_DENSITY.keys() known_cuts = var.<API key>.keys() ob_data = [] df_leftovers = False deprecated_id = False unknown_id = False instance_orig = set(dup.instance_object.original for dup in depsgraph.object_instances if dup.is_instance) for dup in depsgraph.object_instances: if dup.is_instance: ob = dup.instance_object.original else: ob = dup.object.original if not deprecated_id: deprecated_id = ob.type == "MESH" and "gem" in ob.data if "gem" not in ob or (not dup.is_instance and ob in instance_orig): continue # Gem stone = ob["gem"]["stone"] cut = ob["gem"]["cut"] size = tuple(round(x, 2) for x in _from_scene(ob.dimensions, batch=True)) gems[(stone, cut, size)] += 1 # Warnings loc = dup.matrix_world.to_translation() rad = max(ob.dimensions[:2]) / 2 if dup.is_instance: mat = dup.matrix_world.copy() else: mat_loc = Matrix.Translation(loc) mat_rot = dup.matrix_world.to_quaternion().to_matrix().to_4x4() mat = mat_loc @ mat_rot loc.freeze() mat.freeze() ob_data.append((loc, rad, mat)) if stone not in known_stones: stone = "*" + stone unknown_id = True if cut not in known_cuts: cut = "*" + cut unknown_id = True if ( not df_leftovers and ob.parent and ob.parent.type == "MESH" and ob.parent.instance_type == "NONE" ): df_leftovers = True # Find overlaps overlaps = False if self.prefs.<API key>: thold = UScale.to_scene(0.1) overlaps = asset.gem_overlap(ob_data, threshold=thold, first_match=True) # Find hidden gems hidden = False if self.prefs.<API key>: for ob in scene.objects: if "gem" in ob and not ob.visible_get(): hidden = True break # Warnings if hidden: data["warn"].append("Hidden gems (use Show Hidden/Alt H)") if df_leftovers: data["warn"].append("Possible gem dupli-face leftovers") if overlaps: data["warn"].append("Overlapping gems") if deprecated_id: data["warn"].append("Deprecated gem IDs (use Convert Deprecated Gem IDs from Operator Search menu)") if unknown_id: data["warn"].append("Unknown gem IDs, carats are not calculated for marked gems (*)") return data
# samsaara [![Build Status](https: **Note:** *This module is NOT ready to be used. If you happen to have stumbled across it, know that it's a Work in Process.* ![samsaara title image](https://raw.githubusercontent.com/arjunmehta/node-samsaara/image/image/splash.png) A functional, object-oriented bridge to manage, manipulate and interact with large sets of real-time connections. But it does oh so much more! More specifically: - **Extends websockets, or websockets based interfaces (sockjs, engine.io etc.) to infinite extensibility.** - **Execute client methods from server and server methods on client using classic functional patterns (including the passing of callbacks).** - **Middleware engine for object-oriented extensibility.** - **A very simple, easy to use, scalable interface.** ## Installation bash npm install --save samsaara ## Basic Usage Client Side Using browserify or any other commonjs packager, just require samsaara in your client script and initialize with your socket. Use the `core` object to perform actions on the samsaara core server. javascript var WebSocket = require('ws') var ws = new WebSocket('ws://localhost') var samsaara = require('samsaara').initialize({ socket: ws }) // Execute a method on core samsaara.core.execute('testMethod')('testing samsaara', [111, 222, 333]) Core (Server) Side javascript var WebSocketServer = require('ws').Server var wss = new WebSocketServer({ port: 8080 }) var samsaara = require('samsaara').initialize({ socketType: 'ws' }) wss.on('connection', function connection(ws) { var connection = samsaara.newConnection(ws) }) samsaara.expose({ testMethod: function(a_string, number_array) { console.log('Test Method Executed', a_string, number_array); } }) ## Primitive Components There are 3 main components to interact with when using samsaara: connections; namespaces; and exposed methods. Middleware modules handle the rest (grouping, resources, ipc, authentication etc.) but they're all based on these fundamental components. Connections A `connection` is just a representation of a connected client and is the most fundamental and important object in the system. Samsaara uses a realtime channel (either websockets, sockjs, engine.io etc.) to communicate with the connection and pass messages between client and server processes. Refer to the API to see details on interfacing with the connection and its events. Exposures In the same way routes are exposed interfaces to http clients, samsaara can `expose` methods to connections. This simple action allow you to seamlessly work between client and server, pass arguments between them, and program as if each were native, local* objects. Data types include all the basic javascript types: Strings, Objects, Arrays, Numbers and even Function Callbacks (as a final argument) and any combination thereof. Refer to the API to see details on using exposed methods (exposures) to interact with connections. *(uhmmm we're trying anyway.) Namespaces A `nameSpace` is a discrete space for exposed methods. Namespaces basically allow you to separate groups of exposed methods. But even more importantly they allow for almost infinite extensibility, giving modules the ability to have custom configurations without worrying about overlapping names. Refer to the API to see details on using nameSpaces. ## Server API Items denoted with * are optional Server: Key Events While slightly verbose, events in samsaara are meant to share a common syntax and are related to **objects** instead of messages. # samsaara.on('connection', function(connection){}) Called when a new connection connects to the system. Passes through a `connection` reference to the handler. # samsaara.on('disconnect', function(connection){}) Called when a connection disconnects from the system. Passes through a `connection` reference to the handler. # samsaara.on('initialized', function(connection){}) Called when a connection has completed initialization after connecting. This is called after it has completed ng with the Passes through a `connection` reference to the handler. Server: Interacting with Connections While you are welcome to find ways of organizing and accessing connections, natively samsaara keeps things simple. # samsaara.connections A list of all connections. # samsaara.connection(connection_id) Returns the connection with the supplied connection ID. # connection.execute(method_name, args,..., callback) Executes on the client the exposed method of the given string `method_name`. Pass in any number of arguments that the receiving function might expect, and end the call with a callback(!) if you'd like. Currently, only the last argument can be a function. # connection.nameSpace(namespace_name).execute(method_name, args,..., callback) Executes a method within a namespace on the connection. Server: Exposing Methods Exposing methods to clients is what makes samsaara so powerful and fun. Methods that are exposed can take any non-circular javascript primitive, and even allows for callbacks. Just use the standard syntax for dealing with callbacks as the last argument to your functions. # samsaara.expose(method_set); Exposes a set of methods to clients. These are placed in the main namespace. Server: Using Namespaces Namespaces are powerful because the enable so many things that might not be fully apparent at first. With namespaces you can create other primitive objects that route messages to specific namespaces. OR, they're also just a good way to keep your exposed methods organized. # samsaara.createNamespace(name, exposedSet) # samsaara.nameSpace(name) # samsaara.nameSpace(name).expose() ## Connection API The client API is quite similar to the server's API. There's just less to it :) Client: Interacting with the Core Process Currently clients are only connected to a single server process at a time. Perhaps someone would like to write an extension that connects to multiple? :) # samsaara.execute(method_name, args,..., callback) # samsaara.nameSpace(name).execute(method_name, args,..., callback); Client: Exposing Methods Exposing methods to the server works much the same way it works on the server. # samsaara.expose(method_set); Client: Using Namespaces Namespaces are powerful because they enable so many things that might not be fully apparent at first. With namespaces you can create other primitive objects that route messages to specific namespaces. OR, they're also just a good way to keep your exposed methods organized. # samsaara.createNamespace(name, exposedSet) # samsaara.nameSpace(name) # samsaara.nameSpace(name).expose() The MIT License (MIT) Copyright (c) 2015 Arjun Mehta
from neo.Storage.Common.DataCache import DataCache class CloneCache(DataCache): def __init__(self, innerCache): super(CloneCache, self).__init__() self.innerCache = innerCache def AddInternal(self, key, value): self.innerCache.Add(key, value) def DeleteInternal(self, key): self.innerCache.Delete(key) def FindInternal(self, key_prefix): for k, v in self.innerCache.Find(key_prefix): yield k, v.Clone() def GetInternal(self, key): return self.innerCache[key].Clone() def TryGetInternal(self, key): res = self.innerCache.TryGet(key) if res is None: return None else: return res.Clone() def UpdateInternal(self, key, value): self.innerCache.GetAndChange(key).FromReplica(value)
package Game; import java.awt.Graphics; import java.awt.Image; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.CropImageFilter; import java.awt.image.FilteredImageSource; //import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JPanel; @SuppressWarnings("serial") public class Tileset extends JPanel { public Image tileset; public Image[] tiles; public int tilesLoaded = 0; public Tileset(String src) throws <API key> { tiles = new Image[64]; tileset = new ImageIcon(this.getClass().getResource(src)).getImage(); //System.out.println(tilesLoaded); for(int q = 0; q != 64; q = q + 16) { System.out.println(q); for(int w = 0; w != 64; w = w + 16) { for(int o = 0; o != 4; o++) { tiles[tilesLoaded] = createImage(new FilteredImageSource(tileset.getSource(), new CropImageFilter(w, q, 16, 16))); new ImageIcon(tiles[tilesLoaded]); double locationX = ToBuffImage(tiles[tilesLoaded]).getWidth() / 2; double locationY = ToBuffImage(tiles[tilesLoaded]).getHeight() / 2; AffineTransform tx = AffineTransform.getRotateInstance(Math.toRadians (o * 90), locationX, locationY); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); tiles[tilesLoaded] = op.filter(ToBuffImage(tiles[tilesLoaded]), null); tilesLoaded++; Main.loaded++; Main.game.repaint(); Thread.sleep(10); //System.out.println(tilesLoaded); } } } } public BufferedImage rotate180( BufferedImage inputImage ) { int width = inputImage.getWidth(); int height = inputImage.getHeight(); BufferedImage returnImage = new BufferedImage( width, height, inputImage.getType() ); for( int x = 0; x < width; x++ ) { for( int y = 0; y < height; y++ ) { returnImage.setRGB(width - x - 1, height - y - 1, inputImage.getRGB(x, y)); } } return returnImage; } public static BufferedImage ToBuffImage(Image im) { BufferedImage bi = new BufferedImage (im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB); Graphics bg = bi.getGraphics(); bg.drawImage(im, 0, 0, null); bg.dispose(); return bi; } }
# Lab Pack _A Collection of Methods for Data Collection & Processing_ by [Collective Acuity](http://collectiveacuity.com) <table> <tbody> <tr> <td><b>Downloads</b></td> <td><a href="http: </tr> <tr> <td><b>Source</b></td> <td><a href="https: </tr> <tr> <td><b>Documentation</b></td> <td><a href="https: </tr> </tbody> </table> ## Introduction Lab Pack is designed to make the process of retrieving, managing and processing data more uniform across a variety of different sources and structures. The classes and methods in this module aggregate and curate python resources and online APIs to provide a set of best practices for handling data across laboratory projects. ## Installation From PyPi bash $ pip install labpack From GitHub bash $ git clone https://github.com/collectiveacuity/labpack $ cd labpack $ python setup.py install ## Getting Started This module contains a variety of classes, clients and packages for use in laboratory projects. For example to store records in an indexed file store on the local device, you can use the following methods: Create an unique ID for records:: from labpack.records.id import labID id = labID() url_safe_id_string = id.id48 id_datetime = id.epoch id_mac_address = id.mac Save record data in local user data:: from labpack.storage.appdata import appdataClient msg_key = '%s/%s.yaml' % (id_mac_address, id_datetime) msg_details = { 'dt': id_datetime, 'mac': id_mac_address, 'msg': 'Text me back' } msg_client = appdataClient('Outgoing', 'My Team', 'My App') mgs_client.create(msg_key, msg_details) ## Further Reading For a list of the methods in this module, refer to the [Classes](classes.md), [Clients](clients.md) and [Packages](packages.md) pages.
<?php namespace Phalcon\Validation\Message; use Phalcon\Validation\Message; use Phalcon\Validation\Exception; use Phalcon\Validation\MessageInterface; class Group implements \Countable, \ArrayAccess, \Iterator { protected $_position; protected $_messages; /** * Phalcon\Validation\Message\Group constructor * * @param array $messages * */ public function __construct($messages=null) {} /** * Gets an attribute a message using the array syntax * *<code> * print_r($messages[0]); *</code> * * @param int $index * * @return Message|boolean */ public function offsetGet($index) {} /** * Sets an attribute using the array-syntax * *<code> * $messages[0] = new \Phalcon\Validation\Message('This is a message'); *</code> * * @param int $index * @param mixed $message * * * @return void */ public function offsetSet($index, $message) {} /** * Checks if an index exists * *<code> * var_dump(isset($message['database'])); *</code> * * @param string $index * * @return boolean */ public function offsetExists($index) {} /** * Removes a message from the list * *<code> * unset($message['database']); *</code> * * @param string $index * * * @return mixed */ public function offsetUnset($index) {} /** * Appends a message to the group * *<code> * $messages->appendMessage(new \Phalcon\Validation\Message('This is a message')); *</code> * * @param MessageInterface $message * * @return void */ public function appendMessage(MessageInterface $message) {} /** * Appends an array of messages to the group * *<code> * $messages->appendMessages($messagesArray); *</code> * * @param \Phalcon\Validation\MessageInterface[] $messages * * * @return void */ public function appendMessages($messages) {} /** * An array of messages is simply merged into the current one * * @param string $fieldName * * @return mixed */ public function filter($fieldName) {} /** * A group of messages is iterated and appended one-by-one to the current list * * @return int */ public function count() {} /** * Rewinds the internal iterator * * @return void */ public function rewind() {} /** * Returns the current message in the iterator * * @return Message|boolean */ public function current() {} /** * Returns the current position/key in the iterator * * @return int */ public function key() {} /** * Moves the internal iteration pointer to the next position * * @return void */ public function next() {} /** * Check if the current message in the iterator is valid * * @return boolean */ public function valid() {} /** * Magic __set_state helps to re-build messages variable when exporting * * @param array $group * * @return Group */ public static function __set_state($group) {} }
'use strict'; var yeoman = require('yeoman-generator'); // var chalk = require('chalk'); // var yosay = require('yosay'); module.exports = yeoman.generators.Base.extend({ // method1: function () { // console.log('method 1 just run'); // method2: function () { // console.log('method 2 just run'); prompting: function () { var done = this.async(); // Have Yeoman greet the user. // this.log(yosay( // 'Welcome to the great ' + chalk.red('generator-h-4-gens') + ' generator!' // var prompts = [{ // type: 'confirm', // name: 'someOption', // message: 'Would you like to enable this option?', // default: true var prompts = [{ name: 'checked', type: 'checkbox', message: 'choose which items to install', choices: [{ name: 'git', value: 'git', checked: true }, { name: 'npm', value: 'npm', checked: true }, { name: 'mocha', value: 'mocha', checked: true }, { name: 'gulp', value: 'gulp', checked: true }, { name: 'babel', value: 'babel', checked: true }, { name: 'eslint', value: 'eslint', checked: true }] }]; this.prompt(prompts, function (props) { // console.log('props', props); this.props = props; // To access props later use this.props.someOption; done(); }.bind(this)); }, writing: function () { console.log(this.props.checked); // var context = { // // name: this.name, // this.template('dummyfile.txt', 'dummyfile.txt', {context}); this.directory('app', 'app'); //TODO let self = this; this.props.checked.forEach(function(gen){ self.composeWith('h4gens:'+gen); }) // let c = this.props.checked; // if(c.indexOf('git') !== -1) { // this.composeWith('h4gens:git'); // if(c.indexOf('npm') !== -1) { // this.composeWith('h4gens:npm'); // if(c.indexOf('mocha') !== -1){ // this.composeWith('h4gens:mocha'); // if(c.indexOf('gulp') !== -1){ // this.composeWith('h4gens:gulp'); // if(c.indexOf('babel') !== -1){ // this.composeWith('h4gens:babel'); // this.fs.copy( // this.templatePath('dummyfile.txt'), // this.destinationPath('dummyfile.txt') } // install: function () { // this.installDependencies(); });
# reauth Another authentication plugin for CaddyServer (v1) For CaddyServer V2 Please [caddy2-reauth](https://github.com/freman/caddy2-reauth) ## Contents - [reauth](#reauth) * [Abstract](#abstract) * [Supported backends](#supported-backends) * [Supported failure handlers](#<API key>) * [Configuration](#configuration) + [Spaces in configuration](#<API key>) * [Backends](#backends) + [Simple](#simple) + [Upstream](#upstream) + [Refresh](#refresh) + [GitlabCI](#gitlabci) + [LDAP](#ldap) * [Failure handlers](#failure-handlers) + [HTTPBasic](#httpbasic) + [Redirect](#redirect) + [Status](#status) * [Todo](#todo) * [Other notes](#other-notes) ## Abstract Provides a common basis for various and multiple authentication systems. This came to be as we wanted to dynamically authenticate our docker registry against gitlab-ci and avoid storing credentials in gitlab while still permitting users to log in with their own credentials. ## Supported backends The following backends are supported. * [Simple](#simple) * [Upstream](#upstream) * [Refresh](#refresh) * [GitlabCI](#gitlabci) * [LDAP](#ldap) With more to come... ## Supported failure handlers The following failure handlers are supported. * [HTTPBasic](#httpbasic) * [Redirect](#redirect) * [Status](#status) ## Configuration The core of the plugin supports the following arguments: | Parameter-Name | Description | | | path | the path to protect, may be repeated but be aware of strange interactions with `except` (required) | | except | sub path to permit unrestricted access to (optional, can be repeated) | | failure | what to do on failure (see failure handlers, default is [HTTPBasic](#httpbasic)) | Example: reauth { path / except /public except /not_so_secret } Along with these two arguments you are required to specify at least one backend. Spaces in configuration Through experimentation by [@mh720 (Mike Holloway)](https://github.com/mh720) it has been discovered that if you need spaces in your configuration that the best bet is to use unicode escaping. For example: OU=GROUP\u0020NAME I imagine this would allow you to escape any character you need this way including quotes. ## Backends Simple This is the simplest plugin, taking just a list of username=password[,username=password]. Example: simple user1=password1,user2=password2 Upstream Authentication against an upstream http server by performing a http basic authenticated request and checking the response for a http 200 OK status code. Anything other than a 200 OK status code will result in a failure to authenticate. Parameters for this backend: | Parameter-Name | Description | | | url | http/https url to call | | skipverify | true to ignore TLS errors (optional, false by default) | | timeout | request timeout (optional 1m by default, go duration syntax is supported) | | follow | follow redirects (disabled by default as redirecting to a login page might cause a 200) | | cookies | true to pass cookies to the upstream server | | match | used with follow, match string against the redirect url, if found then not logged in | Examples upstream url=https://google.com,skipverify=true,timeout=5s upstream url=https://google.com,skipverify=true,timeout=5s,follow=true,match=login Refresh Authentication with Refresh Token against configurable endpoints with response caching and cache entry expiration times. If failure conditions in the configuration file are met a 401 is returned otherwise result will be successful. This module is designed to be used with the [caddy-secrets](https://github.com/startsmartlabs/caddy-secrets) plugin, a yaml file with a `reauth` object with an `endpoints` array will hold configurations for endpoints and how they work together for auth service. Parameters for this backend: | Parameter-Name | Description | | | url | http/https url to call | | skipverify | true to ignore TLS errors (optional, false by default) | | timeout | request timeout (optional 1m by default, go duration syntax is supported) | | follow | follow redirects (disabled by default as redirecting to a login page might cause a 200) | | cookies | true to pass cookies to the upstream server | | limit | int to set response size limit for endpoint requests (default 1000) | | lifetime | time interval that a file cached by this module will remain valid (default 3 hours) | | cleaninterval | time interval to clean cache of expired entries (default 1 second) | Examples - Caddyfile refresh url=https://example.com,skipverify=true,timeout=5s,lifetime=3h,cleaninterval=1s,limit=1000 - Secrets file re<API key>: 1 # authorization flag (required) - 0/1 whether to check for Authorization header, 2 will throw 500 if missing Authorization access token stored in 'ResultsMap' under 'client_token' key endpoints # endpoints array (required) - name: refresh # endpoint of name 'refresh' (required) url: null path: "/access_token" method: POST # auth request method (required) - at the moment only POST and GET are handled (value must be in caps) data: # data array (required) - key: grant_type value: refresh_token - key: refresh_token # object with 'refresh_token' key (required) value: <refresh token to get access token> # value (required) - holds actual refresh token to request access token with cachekey: refresh_token headers: - key: Content-Type value: "application/<API key>" skipverify: true cookies: true responsekey: jwt_token failures: - validation: equality # there are 3 types of validation, 'equality' will have auth fail if key: message # response body value under failure object key equality failure object value value: Forbidden valuemessage: false message: "Refresh access token failed" # access token is stored in 'ResultsMap' under 'refresh' key - name: security_context # endpoint responses get stored in 'ResultsMap' under the name of the endpoint url: https://different.example.com # url value should be set if endpoint uses different url than one in Caddyfile path: "/security_context" # path is concatenated after url for request method: GET # request method, GET will put data params in query, POST will encode form data: # data needed for request - key: access_token value: "{client_token}" # surrounding keys with {}'s will have them replaced by values in 'ResultsMap' cachekey: client_token # cache entry key headers: # keys and values to set on endpoint request headers - key: Authorization value: "Bearer {refresh}" # surrounding keys with {}'s will have them replaced by values in 'ResultsMap' skipverify: true # whether endpoint request should use Caddyfile skipverify configuration cookies: true # whether endpoint request should use Caddyfile cookies configuration responsekey: null # if set, the key will be used to pull value from endpoint response failures: - validation: presence # 'presence' validation will have auth fail if response body has failure object key key: error value: ~ valuemessage: true # if valuemessage bool is true, response object value under failure object key message: "Security context error: " is concatenated to failure message - validataion: status # 'status' validation will have auth fail if endpoint response status key: ~ matches failure object value value: 401 valuemessage: false message: "Security context unauthorized" resultkey: security_context # last endpoint response stored in 'ResultsMap' is passed down caddy filter chain in a query param with the key named after 'resultkey' value GitlabCI Authenticate against Gitlab as the gitlab-ci-user for the purposes of letting the gitlab-ci access otherwise protected resources without storing credentials in gitlab or gitlab-ci.yml. Works basically like the [Upstream]#upstream backend except the username you provide is the project path Parameters for this backend: | Parameter-Name | Description | | | url | http/https url to call | | skipverify | true to ignore TLS errors (optional, false by default) | | timeout | request timeout (optional 1m by default, go duration syntax is supported) | Example gitlabci url=https://gitlab.example.com,skipverify=true,timeout=5s Example of logging in via gitlab-ci.yml docker login docker.example.com -u "$CI_PROJECT_PATH" -p "$CI_BUILD_TOKEN" LDAP Authenticate against a specified LDAP server - for example a Microsoft AD server. Parameters for this backend: | Parameter-Name | Description | | | url | url, required - i.e. ldap://ldap.example.com:389 | | tls | should StartTLS be used? (default false) | | username | (read-only) bind username - i.e. ldap-auth | | password | the password for the bind username | | insecure | true to ignore TLS errors (optional, false by default) | | timeout | request timeout (optional 1m by default, go duration syntax is supported) | | base | Search base, for example "OU=Users,OU=Company,DC=example,DC=com" | | filter | Filter the users, eg "(&(memberOf=CN=group,OU=Users,OU=Company,DC=example,DC=com)(objectClass=user)(sAMAccountName=%s))" | | principal_suffix | suffix to append to usernames (eg: @example.com) | | pool_size | size of the connection pool, default is 10 | Example ldap url=ldap://ldap.example.com:389,timeout=5s,base="OU=Users,OU=Company,DC=example,DC=com",filter="(&(memberOf=CN=group,OU=Users,OU=Company,DC=example,DC=com)(objectClass=user)(sAMAccountName=%s))" ## Failure handlers HTTPBasic This is the default failure handler and is by default configured to send the requested host as the realm Parameters for this handler: | Parameter-Name | Description | | | realm | name of the realm to authenticate against - defaults to host | Example failure basicauth realm=example.org Redirect Redirect the user, perhaps to a login page? Parameters for this handler: | Parameter-Name | Description | | | target | target url for the redirection, supports {uri} for redirection (required) | | code | the http status code to use, defaults to 302 | Example failure redirect target=example.org,code=303 Example with uri failure redirect target=/auth?redir={uri},code=303 Status Simplest possible failure handler, return http status $code Parameters for this handler: | Parameter-Name | Description | | | code | the http status code to use, defaults to 401 | Example failure status code=418 ## Todo Modularise the failure handlers... ## Other notes * Have embedded [https:
function initMap() { var uluru = { lat: 12.8447287, lng: 77.6623789 }; var map = new google.maps.Map(document.getElementById('map'), { zoom: 18, center: uluru }); var marker = new google.maps.Marker({ position: uluru, map: map }); }
package edu.vu.isis.ammo.api; import java.util.Arrays; import java.util.EnumSet; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.<API key>; import android.content.ServiceConnection; import android.net.Uri; import android.os.DeadObjectException; import android.os.IBinder; import android.os.Parcel; import android.os.<API key>; import android.os.Parcelable; import android.os.RemoteException; import android.util.SparseArray; import edu.vu.isis.ammo.api.type.Action; import edu.vu.isis.ammo.api.type.BroadIntent; import edu.vu.isis.ammo.api.type.ChannelFilter; import edu.vu.isis.ammo.api.type.DeliveryScope; import edu.vu.isis.ammo.api.type.Form; import edu.vu.isis.ammo.api.type.Limit; import edu.vu.isis.ammo.api.type.Notice; import edu.vu.isis.ammo.api.type.Notice.Via; import edu.vu.isis.ammo.api.type.Oid; import edu.vu.isis.ammo.api.type.Order; import edu.vu.isis.ammo.api.type.Payload; import edu.vu.isis.ammo.api.type.Provider; import edu.vu.isis.ammo.api.type.Quantifier; import edu.vu.isis.ammo.api.type.Query; import edu.vu.isis.ammo.api.type.Selection; import edu.vu.isis.ammo.api.type.SerialMoment; import edu.vu.isis.ammo.api.type.TimeInterval; import edu.vu.isis.ammo.api.type.TimeStamp; import edu.vu.isis.ammo.api.type.TimeTrigger; import edu.vu.isis.ammo.api.type.Topic; /** * see docs/dev-guide/developer-guide.pdf The request has many options. Option * usage: */ public class AmmoRequest implements IAmmoRequest, Parcelable { private static final Logger logger = LoggerFactory.getLogger("api.request"); private static final Logger plogger = LoggerFactory.getLogger("api.parcel"); /** * Typically logging by clients is suppressed. */ private static final boolean CLIENT_LOGGING = false; // PUBLIC PROPERTIES final public Action action; final public String uuid; // the request globally unique identifier final public String uid; // the application object unique identifier /** * the data store which holds the object. */ final public Provider provider; /** * the data is to be sent as a broadcast intent. */ final public BroadIntent intent; /** * the serialized content data. */ final public Payload payload; final public SerialMoment moment; /** * the general uid and data type. This is a prefix match pattern. */ final public Topic topic; final public Topic subtopic; final public Quantifier quantifier; final public Integer downsample; /** * indicates the volatility of the value. It amounts to deciding the allowed * sources of the content. It can be considered a measure of number of * sources. */ final public Integer durability; /** * the preferred delivery order for the content. This is used to select * between objects of differing types. */ final public Integer priority; /** * the preferred delivery order for the content. Unlike priority, this is * used when there are multiple versions of the same item. */ final public Order order; /** * states from which time 'missed' data should be retrieved. This is * typically used only on the retrieve or interest actions. */ final public TimeTrigger start; /** * specifies the time until the subscription is dropped. */ final public TimeTrigger expire; /** * obtain no more than the specified number of items. */ final public Limit limit; /** * how far the request is allowed to travel. It can be considered a measure * of distance traveled. */ final public DeliveryScope scope; /** * constrains the message rate to lower the load on the network. The * parameter is the maximum number of bits per second. */ final public Integer throttle; /** * filter out (or in) the unnecessary fields. */ final public String[] project; /** * reduce the quantity of items returned. */ final public Selection select; /** * used as a check against priority. This does not affect request delivery, * but it will impact status. */ final public Integer worth; /** * provides delivery notices concerning the progress of requests which meet * the subscription type/uid. */ final public Notice notice; final public ChannelFilter channelFilter; @Override public String toString() { StringBuilder sb = new StringBuilder(); if (this.action != null) sb.append(this.action.toString()).append(" Request "); if (this.uuid != null) sb.append(this.uuid).append(" "); if (this.uid != null) sb.append(this.uid).append(" "); if (this.topic != null) sb.append(this.topic).append(' '); return sb.toString(); } public String toShow() { StringBuilder sb = new StringBuilder(); if (this.action != null) sb.append(this.action.toString()).append(" Request "); if (this.uuid != null) sb.append('[').append(this.uuid).append("]"); if (this.uid != null) sb.append(":[").append(this.uid).append("] "); if (this.topic != null) sb.append('@').append(this.topic); if (this.subtopic != null) sb.append('&').append(this.subtopic); if (this.quantifier != null) sb.append('&').append(this.quantifier); sb.append(' '); return sb.toString(); } // Parcelable Support public static final Parcelable.Creator<AmmoRequest> CREATOR = new Parcelable.Creator<AmmoRequest>() { @Override public AmmoRequest createFromParcel(Parcel source) { try { return new AmmoRequest(source); } catch (IncompleteRequest ex) { return null; } catch (Throwable ex) { final int capacity = source.dataCapacity(); // final int size = (capacity < 50) ? capacity : 50; // final byte[] data = new byte[size]; // source.unmarshall(data, 0, size); final byte[] data = source.marshall(); plogger.error("PARCEL UNMARSHALLING PROBLEM: size {} data {}", capacity, data, ex); return null; } } @Override public AmmoRequest[] newArray(int size) { return new AmmoRequest[size]; } }; /** * The this.provider.writeToParcel(dest, flags) form is not used rather * Class.writeToParcel(this.provider, dest, flags) so that when the null * will will be handled correctly. */ private final byte VERSION = (byte) 0x05; public final long buildTime; /** * The first few fields are required and are positional. * <dl> * <dt>uuid</dt><dd></dd> * <dt>uid</dt><dd></dd> * <dt>action</dt><dd></dd> * </dl> * * The remainder are optional, their presence is indicated by their nominal values. */ @Override public void writeToParcel(Parcel dest, int flags) { plogger.debug("version: {}", VERSION); dest.writeByte(VERSION); plogger.debug("request: [{}:{}]", this.uuid, this.uid); dest.writeValue(this.uuid); dest.writeValue(this.uid); if (CLIENT_LOGGING) plogger.debug("action: {}", this.action); Action.writeToParcel(dest, this.action); /* OPTIONAL FIELDS BEGIN */ // PROVIDER if (CLIENT_LOGGING) plogger.debug("provider: {}", this.provider); Nominal.PROVIDER.writeToParcel(dest, flags); Provider.writeToParcel(this.provider, dest, flags); // PAYLOAD if (CLIENT_LOGGING) plogger.debug("payload: {}", this.payload); Nominal.PAYLOAD.writeToParcel(dest, flags); Payload.writeToParcel(this.payload, dest, flags); // INTENT // if (CLIENT_LOGGING) // plogger.debug("intent: {}", this.intent); // Nominal.INTENT.writeToParcel(dest, flags); // Payload.writeToParcel(this.intent, dest, flags); // SERIAL MOMENT if (CLIENT_LOGGING) plogger.debug("moment: {}", this.moment); Nominal.MOMENT.writeToParcel(dest, flags); SerialMoment.writeToParcel(this.moment, dest, flags); // TOPIC if (CLIENT_LOGGING) plogger.debug("topic: [{}]+[{}]", this.topic, this.subtopic); Nominal.TOPIC.writeToParcel(dest, flags); Topic.writeToParcel(this.topic, dest, flags); Nominal.SUBTOPIC.writeToParcel(dest, flags); Topic.writeToParcel(this.subtopic, dest, flags); // QUANTIFIER if (CLIENT_LOGGING) plogger.debug("quantifier: {}", this.quantifier); Nominal.QUANTIFIER.writeToParcel(dest, flags); Quantifier.writeToParcel(this.quantifier, dest, flags); // DOWNSAMPLE if (CLIENT_LOGGING) plogger.debug("downsample: {}", this.downsample); Nominal.DOWNSAMPLE.writeToParcel(dest, flags); dest.writeValue(this.downsample); // DURABILITY if (CLIENT_LOGGING) plogger.debug("durability: {}", this.durability); Nominal.DURABLILITY.writeToParcel(dest, flags); dest.writeValue(this.durability); // PRIORITY if (CLIENT_LOGGING) plogger.debug("priority: {}", this.priority); Nominal.PRIORITY.writeToParcel(dest, flags); dest.writeValue(this.priority); // ORDER if (CLIENT_LOGGING) plogger.debug("order: {}", this.order); Nominal.ORDER.writeToParcel(dest, flags); Order.writeToParcel(this.order, dest, flags); // START if (CLIENT_LOGGING) plogger.debug("start: {}", this.start); Nominal.START.writeToParcel(dest, flags); TimeTrigger.writeToParcel(this.start, dest, flags); // EXPIRE if (CLIENT_LOGGING) plogger.debug("expire: {}", this.expire); Nominal.EXPIRE.writeToParcel(dest, flags); TimeTrigger.writeToParcel(this.expire, dest, flags); // LIMIT if (CLIENT_LOGGING) plogger.debug("limit: {}", this.limit); Nominal.LIMIT.writeToParcel(dest, flags); Limit.writeToParcel(this.limit, dest, flags); // DELIVERY SCOPE if (CLIENT_LOGGING) plogger.debug("scope: {}", this.scope); Nominal.DELIVERY_SCOPE.writeToParcel(dest, flags); DeliveryScope.writeToParcel(this.scope, dest, flags); // THROTTLE if (CLIENT_LOGGING) plogger.debug("throttle: {}", this.throttle); Nominal.THROTTLE.writeToParcel(dest, flags); dest.writeValue(this.throttle); // WORTH if (CLIENT_LOGGING) plogger.debug("worth: {}", this.worth); Nominal.WORTH.writeToParcel(dest, flags); dest.writeValue(this.worth); // NOTICE if (CLIENT_LOGGING) plogger.debug("notice: {}", this.notice); Nominal.NOTICE.writeToParcel(dest, flags); Notice.writeToParcel(this.notice, dest, flags); // SELECTION if (CLIENT_LOGGING) plogger.debug("selection: {}", this.select); Nominal.SELECTION.writeToParcel(dest, flags); Selection.writeToParcel(this.select, dest, flags); // PROJECTION if (CLIENT_LOGGING) if (this.project != null) { plogger.debug("projection: {}", Arrays.asList(this.project)); } Nominal.PROJECTION.writeToParcel(dest, flags); dest.writeStringArray(this.project); // CHANNEL FILTER if (CLIENT_LOGGING) plogger.debug("channelFilter: [{}]", this.channelFilter); Nominal.CHANNEL_FILTER.writeToParcel(dest, flags); ChannelFilter.writeToParcel(this.channelFilter, dest, flags); } /** * When the request is placed into a parcel the fields have nominal * identifiers. */ private enum Nominal { /** The content provider uri */ PROVIDER(2), /** the serialized payload */ PAYLOAD(3), /** when should the serialization happend */ MOMENT(4), /** the topic (subtopic deprecated) and subtopic array */ TOPIC(5), SUBTOPIC(6), QUANTIFIER(7), DOWNSAMPLE(8), DURABLILITY(9), /** the relative importance of the message */ PRIORITY(10), /** With priority determines the delivery order */ ORDER(11), /** how long the request should persist */ START(12), EXPIRE(13), /** how many ? */ LIMIT(14), DELIVERY_SCOPE(15), THROTTLE(16), /** used to determine the value of the network */ WORTH(17), /** specify the type of delivery notification to generate */ NOTICE(18), /** used to filter, by content, what is to be delivered, used for pull */ SELECTION(19), PROJECTION(20), /** futher reduce the available routes beyond what is specified in the distribution policy */ CHANNEL_FILTER(21), /** When sent the intent is generated */ INTENT(22); public final int code; private Nominal(int code) { this.code = code; } public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub } public static final SparseArray<Nominal> lookup = new SparseArray<Nominal>(); static { for (Nominal nominal : EnumSet.allOf(Nominal.class)) { lookup.put(nominal.code, nominal); } } } private Nominal <API key>(Parcel in) { final int nominalRaw = in.readInt(); return Nominal.lookup.get(Integer.valueOf(nominalRaw)); } /** * @param in * @throws IncompleteRequest */ private AmmoRequest(Parcel in) throws IncompleteRequest { final byte version; this.buildTime = System.currentTimeMillis(); try { version = in.readByte(); if (version < VERSION) { plogger.info( "AMMO REQUEST VERSION MISMATCH, received {}, expected {}", version, VERSION); } else if (version > VERSION) { plogger.warn( "AMMO REQUEST VERSION MISMATCH, received {}, expected {}", version, VERSION); throw new <API key>("AMMO REQUEST VERSION MISMATCH"); } else { plogger.trace("AMMO REQUEST VERSION MATCH: {}", version); } } catch (Exception ex) { plogger.error("unmarshall on version", ex); throw new IncompleteRequest(ex); } if (version < (byte) 6) { try { this.uuid = (String) in .readValue(String.class.getClassLoader()); this.uid = (version < (byte) 3) ? this.uuid : (String) in .readValue(String.class.getClassLoader()); plogger.trace("uuid: [{}:{}]", this.uuid, this.uid); } catch (Exception ex) { plogger.error("decoding uid: {}", ex); throw new IncompleteRequest(ex); } try { this.action = Action.getInstance(in); plogger.trace("action: {}", this.action); } catch (Exception ex) { plogger.error("decoding action: {}", ex); throw new IncompleteRequest(ex); } try { this.provider = Provider.readFromParcel(in); plogger.trace("provider: {}", this.provider); } catch (Exception ex) { plogger.error("decoding provider: {}", ex); throw new IncompleteRequest(ex); } try { this.payload = Payload.readFromParcel(in); plogger.trace("payload: {}", this.payload); } catch (Exception ex) { plogger.error("decoding payload: {}", ex); throw new IncompleteRequest(ex); } try { this.moment = (version < (byte) 4) ? SerialMoment.DEFAULT : SerialMoment.readFromParcel(in); plogger.trace("moment: {}", this.moment); } catch (Exception ex) { plogger.error("decoding moment: {}", ex); throw new IncompleteRequest(ex); } try { this.topic = Topic.readFromParcel(in); plogger.trace("topic: {}", this.topic); } catch (Exception ex) { plogger.error("decoding topic: {}", ex); throw new IncompleteRequest(ex); } if (version < (byte) 3) { // unused read slack bytes this.subtopic = new Topic(""); this.quantifier = new Quantifier(Quantifier.Type.BULLETIN); } else { try { this.subtopic = Topic.readFromParcel(in); plogger.trace("subtopic: {}", this.subtopic); } catch (Exception ex) { plogger.error("decoding subtopic: {}", ex); throw new IncompleteRequest(ex); } try { this.quantifier = Quantifier.readFromParcel(in); plogger.trace("quantifier: {}", this.quantifier); } catch (Exception ex) { plogger.error("decoding quantifier: {}", ex); throw new IncompleteRequest(ex); } } try { this.downsample = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("downsample: {}", this.downsample); } catch (Exception ex) { plogger.error("decoding downsample: {}", ex); throw new IncompleteRequest(ex); } try { this.durability = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("durability: {}", this.durability); } catch (Exception ex) { plogger.error("decoding durability: {}", ex); throw new IncompleteRequest(ex); } try { this.priority = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("priority: {}", this.priority); } catch (Exception ex) { plogger.error("decoding priority: {}", ex); throw new IncompleteRequest(ex); } try { this.order = Order.readFromParcel(in); plogger.trace("order: {}", this.order); } catch (Exception ex) { plogger.error("decoding order: {}", ex); throw new IncompleteRequest(ex); } try { this.start = TimeTrigger.readFromParcel(in); plogger.trace("start: {}", this.start); } catch (Exception ex) { plogger.error("unmarshall start {}", ex); throw new IncompleteRequest(ex); } try { this.expire = TimeTrigger.readFromParcel(in); plogger.trace("expire: {}", this.expire); } catch (Exception ex) { plogger.error("decoding expire: {}", ex); throw new IncompleteRequest(ex); } try { this.limit = (version < (byte) 2) ? new Limit(100) : Limit .readFromParcel(in); plogger.trace("limit: {}", this.limit); } catch (Exception ex) { plogger.error("decoding limit: {}", ex); throw new IncompleteRequest(ex); } try { this.scope = DeliveryScope.readFromParcel(in); plogger.trace("scope: {}", this.scope); } catch (Exception ex) { plogger.error("decoding scope: {}", ex); throw new IncompleteRequest(ex); } try { this.throttle = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("throttle: {}", this.throttle); } catch (Exception ex) { plogger.error("unmarshall throttle {}", ex); throw new IncompleteRequest(ex); } try { this.worth = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("worth: {}", this.worth); } catch (Exception ex) { plogger.error("decoding worth: {}", ex); throw new IncompleteRequest(ex); } try { this.notice = (version < 4) ? new Notice() : Notice .readFromParcel(in); plogger.trace("notice: {}", this.notice); } catch (Exception ex) { plogger.error("decoding notice: {}", ex); throw new IncompleteRequest(ex); } try { this.select = Selection.readFromParcel(in); plogger.trace("select: {}", this.select); } catch (Exception ex) { plogger.error("decoding select: {}", ex); throw new IncompleteRequest(ex); } try { this.project = in.createStringArray(); if (this.project != null) { plogger.trace("projection: {}", Arrays.asList(this.project)); } } catch (Exception ex) { plogger.error("decoding projection: {}", ex); throw new IncompleteRequest(ex); } try { this.channelFilter = (version < (byte) 5) ? null : ChannelFilter.readFromParcel(in); plogger.trace("channelFilter: {}", this.channelFilter); } catch (Exception ex) { plogger.error("decoding channelFilter: {}", ex); throw new IncompleteRequest(ex); } this.intent = null; return; } try { this.uuid = ((String) in.readValue(String.class.getClassLoader())); this.uid = (String) in.readValue(String.class.getClassLoader()); plogger.trace("uuid: [{}:{}]", this.uuid, this.uid); } catch (Exception ex) { plogger.error("decoding uid: {}", ex); throw new IncompleteRequest(ex); } try { this.action = Action.getInstance(in); plogger.trace("action: {}", this.action); } catch (Exception ex) { plogger.error("decoding action: {}", ex); throw new IncompleteRequest(ex); } final Builder builder = newBuilder(null); builder.limit = new Limit(100); builder.moment = SerialMoment.DEFAULT; for (Nominal nominal = <API key>(in); nominal != null; nominal = <API key>(in)) { switch (nominal) { case PROVIDER: try { builder.provider = Provider.readFromParcel(in); plogger.trace("provider: {}", builder.provider); } catch (Exception ex) { plogger.error("decoding provider", ex); throw new IncompleteRequest(ex); } break; case PAYLOAD: try { builder.payload = Payload.readFromParcel(in); plogger.trace("payload: {}", builder.payload); } catch (Exception ex) { plogger.error("decoding payload", ex); throw new IncompleteRequest(ex); } break; case MOMENT: try { builder.moment = SerialMoment.readFromParcel(in); plogger.trace("moment: {}", builder.moment); } catch (Exception ex) { plogger.error("decoding moment", ex); throw new IncompleteRequest(ex); } break; case TOPIC: try { builder.topic = Topic.readFromParcel(in); plogger.trace("topic: {}", builder.topic); } catch (Exception ex) { plogger.error("decoding topic", ex); throw new IncompleteRequest(ex); } case SUBTOPIC: try { builder.subtopic = Topic.readFromParcel(in); plogger.trace("subtopic: {}", builder.subtopic); } catch (Exception ex) { plogger.error("decoding subtopic: {}", ex); throw new IncompleteRequest(ex); } break; case QUANTIFIER: try { builder.quantifier = Quantifier.readFromParcel(in); plogger.trace("quantifier: {}", builder.quantifier); } catch (Exception ex) { plogger.error("decoding quantifier", ex); throw new IncompleteRequest(ex); } break; case DOWNSAMPLE: try { builder.downsample = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("downsample: {}", builder.downsample); } catch (Exception ex) { plogger.error("decoding downsample", ex); throw new IncompleteRequest(ex); } break; case DURABLILITY: try { builder.durability = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("durability: {}", builder.durability); } catch (Exception ex) { plogger.error("decoding durability", ex); throw new IncompleteRequest(ex); } break; case PRIORITY: try { builder.priority = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("priority: {}", builder.priority); } catch (Exception ex) { plogger.error("decoding priority", ex); throw new IncompleteRequest(ex); } break; case ORDER: try { builder.order = Order.readFromParcel(in); plogger.trace("order: {}", builder.order); } catch (Exception ex) { plogger.error("decoding order", ex); throw new IncompleteRequest(ex); } break; case START: try { builder.start = TimeTrigger.readFromParcel(in); plogger.trace("start: {}", builder.start); } catch (Exception ex) { plogger.error("unmarshall start", ex); throw new IncompleteRequest(ex); } break; case EXPIRE: try { builder.expire = TimeTrigger.readFromParcel(in); plogger.trace("expire: {}", builder.expire); } catch (Exception ex) { plogger.error("decoding expire", ex); throw new IncompleteRequest(ex); } break; case LIMIT: try { builder.limit = Limit.readFromParcel(in); plogger.trace("limit: {}", builder.limit); } catch (Exception ex) { plogger.error("decoding limit", ex); throw new IncompleteRequest(ex); } break; case DELIVERY_SCOPE: try { builder.scope = DeliveryScope.readFromParcel(in); plogger.trace("scope: {}", builder.scope); } catch (Exception ex) { plogger.error("decoding scope", ex); throw new IncompleteRequest(ex); } break; case THROTTLE: try { builder.throttle = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("throttle: {}", builder.throttle); } catch (Exception ex) { plogger.error("unmarshall throttle", ex); throw new IncompleteRequest(ex); } break; case WORTH: try { builder.worth = (Integer) in.readValue(Integer.class .getClassLoader()); plogger.trace("worth: {}", builder.worth); } catch (Exception ex) { plogger.error("decoding worth", ex); throw new IncompleteRequest(ex); } break; case NOTICE: try { builder.notice = Notice.readFromParcel(in); plogger.trace("notice: {}", builder.notice); } catch (Exception ex) { plogger.error("decoding notice", ex); throw new IncompleteRequest(ex); } break; case SELECTION: try { builder.select = Selection.readFromParcel(in); plogger.trace("select: {}", builder.select); } catch (Exception ex) { plogger.error("decoding select", ex); throw new IncompleteRequest(ex); } break; case PROJECTION: try { builder.project = in.createStringArray(); if (builder.project != null) { plogger.trace("projection: {}", Arrays.asList(builder.project)); } } catch (Exception ex) { plogger.error("decoding projection", ex); throw new IncompleteRequest(ex); } break; case CHANNEL_FILTER: try { builder.channelFilter = ChannelFilter.readFromParcel(in); plogger.trace("channelFilter: {}", builder.channelFilter); } catch (Exception ex) { plogger.error("decoding channelFilter", ex); throw new IncompleteRequest(ex); } break; case INTENT: builder.intent = BroadIntent.readFromParcel(in); break; default: } } this.provider = builder.provider; this.intent = builder.intent; this.payload = builder.payload; this.moment = builder.moment; this.topic = builder.topic; this.subtopic = builder.subtopic; this.quantifier = builder.quantifier; this.channelFilter = builder.channelFilter; this.downsample = builder.downsample; this.durability = builder.durability; this.priority = builder.priority; this.order = builder.order; this.start = builder.start; this.expire = builder.expire; this.limit = builder.limit; this.scope = builder.scope; this.throttle = builder.throttle; this.project = builder.project; this.select = builder.select; this.worth = builder.worth; this.notice = builder.notice; } @Override public int describeContents() { return 0; } // IAmmoRequest Support private AmmoRequest(Action action, Builder builder) { this.buildTime = System.currentTimeMillis(); this.action = action; this.uid = builder.uid; this.provider = builder.provider; this.intent = builder.intent; this.payload = builder.payload; this.moment = builder.moment; this.topic = builder.topic; this.subtopic = builder.subtopic; this.quantifier = builder.quantifier; this.channelFilter = builder.channelFilter; this.downsample = builder.downsample; this.durability = builder.durability; this.priority = builder.priority; this.order = builder.order; this.start = builder.start; this.expire = builder.expire; this.limit = builder.limit; this.scope = builder.scope; this.throttle = builder.throttle; this.project = builder.project; this.select = builder.select; this.worth = builder.worth; this.notice = builder.notice; this.uuid = UUID.randomUUID().toString(); } /** * Replace the request with req. */ @Override public IAmmoRequest replace(IAmmoRequest req) { // TODO Auto-generated method stub return null; } /** * Replace the named request with ? */ @Override public IAmmoRequest replace(String uuid) { return null; } /** * The principle factory method for obtaining a request builder. * * @param context * @return */ public static Builder newBuilder(Context context) { return new AmmoRequest.Builder(context).reset(); } /** * This method is deprecated. The resolver is no longer needed. * * @param context * @param resolver * @return */ public static Builder newBuilder(Context context, BroadcastReceiver resolver) { return new AmmoRequest.Builder(context).reset(); } /** * This method (and its accompanying constructor * * @param context * @param serviceBinder * @return */ public static Builder newBuilder(Context context, IBinder serviceBinder) { return new AmmoRequest.Builder(context, serviceBinder).reset(); } // CONTROL @Override public void metricTimespan(Integer val) { // TODO Auto-generated method stub } @Override public void resetMetrics(Integer val) { // TODO Auto-generated method stub } // STATISTICS @Override public TimeStamp lastMessage() { // TODO Auto-generated method stub return null; } /** * The builder makes requests to the Distributor via AIDL methods. */ private static final Intent <API key> = new Intent( "edu.vu.isis.ammo.api.MAKE_REQUEST"); public static class Builder implements IAmmoRequest.Builder { private enum ConnectionMode { /** * For some reason the service is not running. */ UNAVAILABLE, /** * A connection has been requested but not yet granted. */ BINDING, /** * Asynchronous request to obtain a connection over which * synchronous requests are made. */ BOUND, /** Asynchronous request without a response */ UNBOUND, /** No connection */ NONE; } private final AtomicReference<ConnectionMode> mode; private final AtomicReference<IDistributorService> distributor; private final Context context; private final BlockingQueue<AmmoRequest> pendingRequestQueue; final private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { logger.info("service connected [{}] outstanding requests", Builder.this.pendingRequestQueue.size()); final IDistributorService distributor = IDistributorService.Stub .asInterface(service); try { for (final AmmoRequest request : Builder.this.pendingRequestQueue) { final String ident = distributor.makeRequest(request); logger.info("service bound : {} {}", request, ident); } } catch (RemoteException ex) { logger.error("no connection on recently bound connection", ex); return; } Builder.this.distributor.set(distributor); Builder.this.mode.set(ConnectionMode.BOUND); } @Override public void <API key>(ComponentName name) { logger.trace("service {} disconnected", name.<API key>()); Builder.this.mode.set(ConnectionMode.UNBOUND); Builder.this.distributor.set(null); } }; /** * The builder acquires a connection to the service. The status of the * connection is managed. If the connection is not ready but there is a * reasonable expectation that it will be made then requests are placed * in a queue. The queue will be drained when the connection is * established. This works with the makeRequest() and * onServiceConnected() methods. * * @param context */ protected Builder(Context context) { this.mode = new AtomicReference<ConnectionMode>( ConnectionMode.UNBOUND); this.distributor = new AtomicReference<IDistributorService>(null); this.context = context; this.pendingRequestQueue = new LinkedBlockingQueue<AmmoRequest>(); try { final boolean isBound = this.context.bindService( <API key>, this.conn, Context.BIND_AUTO_CREATE); logger.trace("is the service bound? {}", isBound); this.mode.compareAndSet(ConnectionMode.UNBOUND, (isBound ? ConnectionMode.BINDING : ConnectionMode.UNAVAILABLE)); } catch (<API key> ex) { logger.error("the service cannot be bound"); } } /** * This constructor is for direct connections to the service (not IPC). * Primarily for testing. * * @param context * @param serviceBinder */ private Builder(Context context, IBinder serviceBinder) { this.context = context; this.pendingRequestQueue = null; this.mode = new AtomicReference<ConnectionMode>( ConnectionMode.BOUND); this.distributor = new AtomicReference<IDistributorService>( IDistributorService.Stub.asInterface(serviceBinder)); } private String uid; private Provider provider; private BroadIntent intent; private Payload payload; private SerialMoment moment; private Topic topic; private Topic subtopic; private Quantifier quantifier; private ChannelFilter channelFilter; private Integer downsample; private Integer durability; private Integer priority; private Order order; private TimeTrigger start; private TimeTrigger expire; private Limit limit; private DeliveryScope scope; private Integer throttle; private String[] project; private Selection select; private Integer worth; private Notice notice; // ACTIONS /** * Generally the BOUND approach should be used as it has the best * performance. Sometimes this is not possible and the startService() * method must be used (in the case of BroadcastReceiver). It may also * be the case that the service has not yet started and the binder has * not yet been obtained. In that interim case the requests are put in a * queue in anticipation of a connection mode should be used. */ protected IAmmoRequest makeRequest(final AmmoRequest request) throws RemoteException { logger.info("make service request {} {}", this.mode, request); switch (this.mode.get()) { case BOUND: try { final String ident = this.distributor.get().makeRequest( request); logger.info("service bound : {} {}", request, ident); } catch (DeadObjectException ex) { logger.info("service unbound : {} {}", request); this.mode.set(ConnectionMode.UNBOUND); this.makeRequest(request); } break; case UNBOUND: final Intent parcelIntent = <API key> .cloneFilter(); parcelIntent.putExtra("request", request); final ComponentName componentName = this.context .startService(parcelIntent); if (componentName != null) { logger.debug("service binding : {}", componentName.getClassName()); } else { logger.error("service binding : {}", parcelIntent); } break; case BINDING: try { this.pendingRequestQueue.put(request); } catch (<API key> ex) { logger.debug("make request interrupted ", ex); } break; case NONE: case UNAVAILABLE: default: break; } return request; } @Override public IAmmoRequest base() { return new AmmoRequest(Action.NONE, this); } @Override public IAmmoRequest post() throws RemoteException { return this.makeRequest(new AmmoRequest(Action.POSTAL, this)); } @Override public IAmmoRequest unpost() throws RemoteException { return this.makeRequest(new AmmoRequest(Action.UNPOSTAL, this)); } @Override public IAmmoRequest retrieve() throws RemoteException { return this.makeRequest(new AmmoRequest(Action.RETRIEVAL, this)); } @Override public IAmmoRequest unretrieve() throws RemoteException { return this.makeRequest(new AmmoRequest(Action.UNRETRIEVAL, this)); } @Override public IAmmoRequest subscribe() throws RemoteException { return this.makeRequest(new AmmoRequest(Action.SUBSCRIBE, this)); } @Override public IAmmoRequest unsubscribe() throws RemoteException { return this.makeRequest(new AmmoRequest(Action.UNSUBSCRIBE, this)); } @Override public IAmmoRequest duplicate() throws RemoteException { // TODO Auto-generated method stub return null; } @Override public IAmmoRequest getInstance(String uuid) throws RemoteException { // TODO Auto-generated method stub return null; } @Override public void releaseInstance() { try { if (this.conn == null) return; this.context.unbindService(this.conn); } catch (<API key> ex) { logger.warn("the service is not bound or registered", ex); } } // SET PROPERTIES @Override public Builder reset() { this.downsample(DOWNSAMPLE_DEFAULT); this.durability(DURABILITY_DEFAULT); this.order(ORDER_DEFAULT); this.payload(PAYLOAD_DEFAULT); this.moment(SerialMoment.DEFAULT); this.priority(PRIORITY_DEFAULT); this.provider(PROVIDER_DEFAULT); this.scope(SCOPE_DEFAULT); this.start(START_DEFAULT); this.throttle(THROTTLE_DEFAULT); this.topic(Topic.DEFAULT); this.subtopic(Topic.DEFAULT); this.quantifier(QUANTIFIER_DEFAULT); this.uid(UID_DEFAULT); this.expire(EXPIRE_DEFAULT); this.project(PROJECT_DEFAULT); this.select(SELECT_DEFAULT); this.filter(FILTER_DEFAULT); this.worth(WORTH_DEFAULT); return this; } public Builder downsample(String max) { if (max == null) return this; this.downsample = Integer.parseInt(max); return this; } @Override public Builder downsample(Integer maxSize) { this.downsample = maxSize; return this; } public Builder durability(String val) { if (val == null) return this; this.durability = Integer.parseInt(val); return this; } @Override public Builder durability(Integer val) { this.durability = val; return this; } public Builder order(String val) { if (val == null) return this; return this.order(new Order(val)); } @Override public Builder order(Order val) { this.order = val; return this; } @Override public Builder payload(String val) { if (val == null) return this; this.payload = new Payload(val); return this; } @Override public Builder payload(byte[] val) { if (val == null) return this; this.payload = new Payload(val); return this; } @Override public Builder payload(ContentValues val) { if (val == null) return this; this.payload = new Payload(val); return this; } @Override public Builder payload(AmmoValues val) { if (val == null) return this; return this.payload(val.asContentValues()); } @Override public Builder moment(String val) { if (val == null) { return this.moment(SerialMoment.DEFAULT); } return this.moment(new SerialMoment(val)); } @Override public Builder moment(SerialMoment val) { this.moment = val; return this; } public Builder priority(String val) { if (val == null) return this; return this.priority(Integer.parseInt(val)); } @Override public Builder priority(Integer val) { this.priority = val; return this; } public Builder provider(String val) { if (val == null) { return this.provider(Provider.DEFAULT); } return this.provider(Uri.parse(val)); } @Override public Builder provider(Uri val) { this.provider = new Provider(val); return this; } public Builder scope(String val) { if (val == null) { return this.scope(DeliveryScope.DEFAULT); } return this.scope(new DeliveryScope(val)); } @Override public Builder scope(DeliveryScope val) { this.scope = val; return this; } public Builder throttle(String val) { if (val == null) return this; this.throttle = Integer.parseInt(val); return this; } @Override public Builder throttle(Integer val) { this.throttle = val; return this; } @Override public Builder topic(String val) { this.topic = new Topic(val); return this; } @Override public Builder topic(Oid val) { this.topic = new Topic(val); return this; } @Override public Builder subtopic(String val) { this.subtopic = new Topic(val); return this; } @Override public Builder subtopic(Oid val) { this.subtopic = new Topic(val); return this; } @Override public Builder quantifier(String type) { this.quantifier(type); return this; } @Override public Builder quantifier(Quantifier.Type type) { this.quantifier = new Quantifier(type); return this; } @Override public Builder topic(String topic, String subtopic, String quantifier) { this.topic(topic); this.subtopic(subtopic); this.quantifier(quantifier); return this; } @Override public Builder topic(Oid topic, Oid subtopic, Quantifier.Type quantifier) { this.topic(topic); this.subtopic(subtopic); this.quantifier(quantifier); return this; } public Builder topicFromProvider() { if (this.provider == null) { logger.error("you must first set the provider"); return this; } final String topic = this.context.getContentResolver().getType( this.provider.asUri()); this.topic(topic); return this; } @Override public Builder useChannel(String val) { if (val == null) { this.channelFilter = null; return this; } this.channelFilter = new ChannelFilter(val); return this; } @Override public Builder uid(String val) { this.uid = val; return this; } public Builder start(String val) { if (val == null) return this; return this.start(new TimeStamp(val)); } @Override public Builder start(TimeStamp val) { this.start = new TimeTrigger(val); return this; } @Override public Builder start(TimeInterval val) { this.start = new TimeTrigger(val); return this; } public Builder expire(String val) { if (val == null) return this; return this.expire(new TimeStamp(val)); } @Override public Builder expire(TimeInterval val) { this.expire = new TimeTrigger(val); return this; } @Override public Builder expire(TimeStamp val) { this.expire = new TimeTrigger(val); return this; } public Builder limit(String val) { this.limit = new Limit(val); return null; } @Override public Builder limit(int val) { this.limit = new Limit(Limit.Type.NEWEST, val); return this; } @Override public Builder limit(Limit val) { this.limit = val; return this; } public Builder project(String val) { if (val == null) return this; if (val.length() < 1) return this; this.project(val.substring(1).split(val.substring(0, 1))); return this; } @Override public Builder project(String[] val) { this.project = val; return this; } public Builder select(String val) { if (val == null) return this; this.select = new Selection(val); return this; } @Override public Builder select(Query val) { this.select = new Selection(val); return this; } @Override public Builder select(Form val) { this.select = new Selection(val); return this; } @Override public Builder filter(String val) { // this.filter = new Filter(val); return this; } public Builder worth(String val) { if (val == null) return this; this.worth = Integer.parseInt(val); return null; } @Override public Builder worth(Integer val) { this.worth = val; return this; } /** * To clear the notices use notice(Notice.RESET). */ public Builder notice(Notice.Threshold threshold, Via.Type type) { if (this.notice == null) this.notice = Notice.newInstance(); this.notice.setItem(threshold, type); plogger.trace("notice=[{}]", this.notice); return this; } /** * It replaces the current notice object with the argument. The notice * set can be cleared by using this method with the Notice.RESET object. */ @Override public Builder notice(Notice val) { this.notice = val; return this; } @Override public Builder intent(Intent val) { this.intent = new BroadIntent(val); return null; } } @Override public void cancel() { // TODO Auto-generated method stub } }
var <API key> = [ [ "all", "<API key>.html#<API key>", null ], [ "basic", "<API key>.html#<API key>", null ], [ "chains", "<API key>.html#<API key>", null ], [ "none", "<API key>.html#<API key>", null ], [ "packed", "<API key>.html#<API key>", null ], [ "parent", "<API key>.html#<API key>", null ], [ "spread", "<API key>.html#<API key>", null ], [ "spread_inside", "<API key>.html#<API key>", null ] ];
#pragma once #include "DataRef.h" #include "<API key>.h" #include "SVGRenderStyleDefs.h" #include "WindRule.h" namespace WebCore { class SVGRenderStyle : public RefCounted<SVGRenderStyle> { public: static Ref<SVGRenderStyle> createDefaultStyle(); static Ref<SVGRenderStyle> create() { return adoptRef(*new SVGRenderStyle); } Ref<SVGRenderStyle> copy() const; ~SVGRenderStyle(); bool inheritedNotEqual(const SVGRenderStyle&) const; void inheritFrom(const SVGRenderStyle&); void <API key>(const SVGRenderStyle&); StyleDifference diff(const SVGRenderStyle&) const; bool operator==(const SVGRenderStyle&) const; bool operator!=(const SVGRenderStyle& other) const { return !(*this == other); } // Initial values for all the properties static EAlignmentBaseline <API key>() { return AB_AUTO; } static EDominantBaseline <API key>() { return DB_AUTO; } static EBaselineShift <API key>() { return BS_BASELINE; } static EVectorEffect initialVectorEffect() { return VE_NONE; } static EBufferedRendering <API key>() { return BR_AUTO; } static WindRule initialClipRule() { return RULE_NONZERO; } static EColorInterpolation <API key>() { return CI_SRGB; } static EColorInterpolation <API key>() { return CI_LINEARRGB; } static EColorRendering <API key>() { return CR_AUTO; } static WindRule initialFillRule() { return RULE_NONZERO; } static EShapeRendering <API key>() { return SR_AUTO; } static ETextAnchor initialTextAnchor() { return TA_START; } static EGlyphOrientation <API key>() { return GO_0DEG; } static EGlyphOrientation <API key>() { return GO_AUTO; } static float initialFillOpacity() { return 1; } static SVGPaintType <API key>() { return <API key>; } static Color <API key>() { return Color::black; } static String initialFillPaintUri() { return String(); } static float <API key>() { return 1; } static SVGPaintType <API key>() { return SVG_PAINTTYPE_NONE; } static Color <API key>() { return Color(); } static String <API key>() { return String(); } static Vector<SVGLengthValue> <API key>() { return { }; } static float initialStopOpacity() { return 1; } static Color initialStopColor() { return Color(0, 0, 0); } static float initialFloodOpacity() { return 1; } static Color initialFloodColor() { return Color(0, 0, 0); } static Color <API key>() { return Color(255, 255, 255); } static ShadowData* initialShadow() { return nullptr; } static String <API key>() { return String(); } static String <API key>() { return String(); } static String <API key>() { return String(); } static String <API key>() { return String(); } static String <API key>() { return String(); } static EMaskType initialMaskType() { return MT_LUMINANCE; } static SVGLengthValue <API key>(); static SVGLengthValue initialKerning(); // SVG CSS Property setters void <API key>(EAlignmentBaseline val) { m_nonInheritedFlags.flagBits.alignmentBaseline = val; } void setDominantBaseline(EDominantBaseline val) { m_nonInheritedFlags.flagBits.dominantBaseline = val; } void setBaselineShift(EBaselineShift val) { m_nonInheritedFlags.flagBits.baselineShift = val; } void setVectorEffect(EVectorEffect val) { m_nonInheritedFlags.flagBits.vectorEffect = val; } void <API key>(EBufferedRendering val) { m_nonInheritedFlags.flagBits.bufferedRendering = val; } void setClipRule(WindRule val) { m_inheritedFlags.clipRule = val; } void <API key>(EColorInterpolation val) { m_inheritedFlags.colorInterpolation = val; } void <API key>(EColorInterpolation val) { m_inheritedFlags.<API key> = val; } void setColorRendering(EColorRendering val) { m_inheritedFlags.colorRendering = val; } void setFillRule(WindRule val) { m_inheritedFlags.fillRule = val; } void setShapeRendering(EShapeRendering val) { m_inheritedFlags.shapeRendering = val; } void setTextAnchor(ETextAnchor val) { m_inheritedFlags.textAnchor = val; } void <API key>(EGlyphOrientation val) { m_inheritedFlags.<API key> = val; } void <API key>(EGlyphOrientation val) { m_inheritedFlags.<API key> = val; } void setMaskType(EMaskType val) { m_nonInheritedFlags.flagBits.maskType = val; } void setCx(const Length&); void setCy(const Length&); void setR(const Length&); void setRx(const Length&); void setRy(const Length&); void setX(const Length&); void setY(const Length&); void setFillOpacity(float); void setFillPaint(SVGPaintType, const Color&, const String& uri, bool applyToRegularStyle = true, bool <API key> = false); void setStrokeOpacity(float); void setStrokePaint(SVGPaintType, const Color&, const String& uri, bool applyToRegularStyle = true, bool <API key> = false); void setStrokeDashArray(const Vector<SVGLengthValue>&); void setStrokeDashOffset(const Length&); void setKerning(const SVGLengthValue&); void setStopOpacity(float); void setStopColor(const Color&); void setFloodOpacity(float); void setFloodColor(const Color&); void setLightingColor(const Color&); void <API key>(const SVGLengthValue&); void setShadow(std::unique_ptr<ShadowData>&& data) { m_shadowData.access().shadow = WTFMove(data); } // Setters for non-inherited resources void setClipperResource(const String&); void setMaskerResource(const String&); // Setters for inherited resources void <API key>(const String&); void <API key>(const String&); void <API key>(const String&); // Read accessors for all the properties EAlignmentBaseline alignmentBaseline() const { return (EAlignmentBaseline) m_nonInheritedFlags.flagBits.alignmentBaseline; } EDominantBaseline dominantBaseline() const { return (EDominantBaseline) m_nonInheritedFlags.flagBits.dominantBaseline; } EBaselineShift baselineShift() const { return (EBaselineShift) m_nonInheritedFlags.flagBits.baselineShift; } EVectorEffect vectorEffect() const { return (EVectorEffect) m_nonInheritedFlags.flagBits.vectorEffect; } EBufferedRendering bufferedRendering() const { return (EBufferedRendering) m_nonInheritedFlags.flagBits.bufferedRendering; } WindRule clipRule() const { return (WindRule) m_inheritedFlags.clipRule; } EColorInterpolation colorInterpolation() const { return (EColorInterpolation) m_inheritedFlags.colorInterpolation; } EColorInterpolation <API key>() const { return (EColorInterpolation) m_inheritedFlags.<API key>; } EColorRendering colorRendering() const { return (EColorRendering) m_inheritedFlags.colorRendering; } WindRule fillRule() const { return (WindRule) m_inheritedFlags.fillRule; } EShapeRendering shapeRendering() const { return (EShapeRendering) m_inheritedFlags.shapeRendering; } ETextAnchor textAnchor() const { return (ETextAnchor) m_inheritedFlags.textAnchor; } EGlyphOrientation <API key>() const { return (EGlyphOrientation) m_inheritedFlags.<API key>; } EGlyphOrientation <API key>() const { return (EGlyphOrientation) m_inheritedFlags.<API key>; } float fillOpacity() const { return m_fillData->opacity; } const SVGPaintType& fillPaintType() const { return m_fillData->paintType; } const Color& fillPaintColor() const { return m_fillData->paintColor; } const String& fillPaintUri() const { return m_fillData->paintUri; } float strokeOpacity() const { return m_strokeData->opacity; } const SVGPaintType& strokePaintType() const { return m_strokeData->paintType; } const Color& strokePaintColor() const { return m_strokeData->paintColor; } const String& strokePaintUri() const { return m_strokeData->paintUri; } Vector<SVGLengthValue> strokeDashArray() const { return m_strokeData->dashArray; } const Length& strokeDashOffset() const { return m_strokeData->dashOffset; } SVGLengthValue kerning() const { return m_textData->kerning; } float stopOpacity() const { return m_stopData->opacity; } const Color& stopColor() const { return m_stopData->color; } float floodOpacity() const { return m_miscData->floodOpacity; } const Color& floodColor() const { return m_miscData->floodColor; } const Color& lightingColor() const { return m_miscData->lightingColor; } SVGLengthValue baselineShiftValue() const { return m_miscData->baselineShiftValue; } ShadowData* shadow() const { return m_shadowData->shadow.get(); } const Length& cx() const { return m_layoutData->cx; } const Length& cy() const { return m_layoutData->cy; } const Length& r() const { return m_layoutData->r; } const Length& rx() const { return m_layoutData->rx; } const Length& ry() const { return m_layoutData->ry; } const Length& x() const { return m_layoutData->x; } const Length& y() const { return m_layoutData->y; } const String& clipperResource() const { return <API key>->clipper; } const String& maskerResource() const { return <API key>->masker; } const String& markerStartResource() const { return <API key>->markerStart; } const String& markerMidResource() const { return <API key>->markerMid; } const String& markerEndResource() const { return <API key>->markerEnd; } EMaskType maskType() const { return (EMaskType) m_nonInheritedFlags.flagBits.maskType; } const SVGPaintType& <API key>() const { return m_fillData-><API key>; } const Color& <API key>() const { return m_fillData-><API key>; } const String& <API key>() const { return m_fillData->visitedLinkPaintUri; } const SVGPaintType& <API key>() const { return m_strokeData-><API key>; } const Color& <API key>() const { return m_strokeData-><API key>; } const String& <API key>() const { return m_strokeData->visitedLinkPaintUri; } // convenience bool hasClipper() const { return !clipperResource().isEmpty(); } bool hasMasker() const { return !maskerResource().isEmpty(); } bool hasMarkers() const { return !markerStartResource().isEmpty() || !markerMidResource().isEmpty() || !markerEndResource().isEmpty(); } bool hasStroke() const { return strokePaintType() != SVG_PAINTTYPE_NONE; } bool hasFill() const { return fillPaintType() != SVG_PAINTTYPE_NONE; } bool isolatesBlending() const { return hasMasker() || shadow(); } private: SVGRenderStyle(); SVGRenderStyle(const SVGRenderStyle&); enum CreateDefaultType { CreateDefault }; SVGRenderStyle(CreateDefaultType); // Used to create the default style. void setBitDefaults(); struct InheritedFlags { bool operator==(const InheritedFlags&) const; bool operator!=(const InheritedFlags& other) const { return !(*this == other); } unsigned colorRendering : 2; // EColorRendering unsigned shapeRendering : 2; // EShapeRendering unsigned clipRule : 1; // WindRule unsigned fillRule : 1; // WindRule unsigned textAnchor : 2; // ETextAnchor unsigned colorInterpolation : 2; // EColorInterpolation unsigned <API key> : 2; // EColorInterpolation unsigned <API key> : 3; // EGlyphOrientation unsigned <API key> : 3; // EGlyphOrientation }; struct NonInheritedFlags { // 32 bit non-inherited, don't add to the struct, or the operator will break. bool operator==(const NonInheritedFlags& other) const { return flags == other.flags; } bool operator!=(const NonInheritedFlags& other) const { return flags != other.flags; } union { struct { unsigned alignmentBaseline : 4; // EAlignmentBaseline unsigned dominantBaseline : 4; // EDominantBaseline unsigned baselineShift : 2; // EBaselineShift unsigned vectorEffect: 1; // EVectorEffect unsigned bufferedRendering: 2; // EBufferedRendering unsigned maskType: 1; // EMaskType // 18 bits unused } flagBits; uint32_t flags; }; }; InheritedFlags m_inheritedFlags; NonInheritedFlags m_nonInheritedFlags; // inherited attributes DataRef<StyleFillData> m_fillData; DataRef<StyleStrokeData> m_strokeData; DataRef<StyleTextData> m_textData; DataRef<<API key>> <API key>; // non-inherited attributes DataRef<StyleStopData> m_stopData; DataRef<StyleMiscData> m_miscData; DataRef<StyleShadowSVGData> m_shadowData; DataRef<StyleLayoutData> m_layoutData; DataRef<StyleResourceData> <API key>; }; inline SVGLengthValue SVGRenderStyle::<API key>() { SVGLengthValue length; length.<API key>(LengthTypeNumber, 0); return length; } inline SVGLengthValue SVGRenderStyle::initialKerning() { SVGLengthValue length; length.<API key>(LengthTypeNumber, 0); return length; } inline void SVGRenderStyle::setCx(const Length& length) { if (!(m_layoutData->cx == length)) m_layoutData.access().cx = length; } inline void SVGRenderStyle::setCy(const Length& length) { if (!(m_layoutData->cy == length)) m_layoutData.access().cy = length; } inline void SVGRenderStyle::setR(const Length& length) { if (!(m_layoutData->r == length)) m_layoutData.access().r = length; } inline void SVGRenderStyle::setRx(const Length& length) { if (!(m_layoutData->rx == length)) m_layoutData.access().rx = length; } inline void SVGRenderStyle::setRy(const Length& length) { if (!(m_layoutData->ry == length)) m_layoutData.access().ry = length; } inline void SVGRenderStyle::setX(const Length& length) { if (!(m_layoutData->x == length)) m_layoutData.access().x = length; } inline void SVGRenderStyle::setY(const Length& length) { if (!(m_layoutData->y == length)) m_layoutData.access().y = length; } inline void SVGRenderStyle::setFillOpacity(float opacity) { if (!(m_fillData->opacity == opacity)) m_fillData.access().opacity = opacity; } inline void SVGRenderStyle::setFillPaint(SVGPaintType type, const Color& color, const String& uri, bool applyToRegularStyle, bool <API key>) { if (applyToRegularStyle) { if (!(m_fillData->paintType == type)) m_fillData.access().paintType = type; if (!(m_fillData->paintColor == color)) m_fillData.access().paintColor = color; if (!(m_fillData->paintUri == uri)) m_fillData.access().paintUri = uri; } if (<API key>) { if (!(m_fillData-><API key> == type)) m_fillData.access().<API key> = type; if (!(m_fillData-><API key> == color)) m_fillData.access().<API key> = color; if (!(m_fillData->visitedLinkPaintUri == uri)) m_fillData.access().visitedLinkPaintUri = uri; } } inline void SVGRenderStyle::setStrokeOpacity(float opacity) { if (!(m_strokeData->opacity == opacity)) m_strokeData.access().opacity = opacity; } inline void SVGRenderStyle::setStrokePaint(SVGPaintType type, const Color& color, const String& uri, bool applyToRegularStyle, bool <API key>) { if (applyToRegularStyle) { if (!(m_strokeData->paintType == type)) m_strokeData.access().paintType = type; if (!(m_strokeData->paintColor == color)) m_strokeData.access().paintColor = color; if (!(m_strokeData->paintUri == uri)) m_strokeData.access().paintUri = uri; } if (<API key>) { if (!(m_strokeData-><API key> == type)) m_strokeData.access().<API key> = type; if (!(m_strokeData-><API key> == color)) m_strokeData.access().<API key> = color; if (!(m_strokeData->visitedLinkPaintUri == uri)) m_strokeData.access().visitedLinkPaintUri = uri; } } inline void SVGRenderStyle::setStrokeDashArray(const Vector<SVGLengthValue>& array) { if (!(m_strokeData->dashArray == array)) m_strokeData.access().dashArray = array; } inline void SVGRenderStyle::setStrokeDashOffset(const Length& offset) { if (!(m_strokeData->dashOffset == offset)) m_strokeData.access().dashOffset = offset; } inline void SVGRenderStyle::setKerning(const SVGLengthValue& kerning) { if (!(m_textData->kerning == kerning)) m_textData.access().kerning = kerning; } inline void SVGRenderStyle::setStopOpacity(float opacity) { if (!(m_stopData->opacity == opacity)) m_stopData.access().opacity = opacity; } inline void SVGRenderStyle::setStopColor(const Color& color) { if (!(m_stopData->color == color)) m_stopData.access().color = color; } inline void SVGRenderStyle::setFloodOpacity(float opacity) { if (!(m_miscData->floodOpacity == opacity)) m_miscData.access().floodOpacity = opacity; } inline void SVGRenderStyle::setFloodColor(const Color& color) { if (!(m_miscData->floodColor == color)) m_miscData.access().floodColor = color; } inline void SVGRenderStyle::setLightingColor(const Color& color) { if (!(m_miscData->lightingColor == color)) m_miscData.access().lightingColor = color; } inline void SVGRenderStyle::<API key>(const SVGLengthValue& shiftValue) { if (!(m_miscData->baselineShiftValue == shiftValue)) m_miscData.access().baselineShiftValue = shiftValue; } inline void SVGRenderStyle::setClipperResource(const String& resource) { if (!(<API key>->clipper == resource)) <API key>.access().clipper = resource; } inline void SVGRenderStyle::setMaskerResource(const String& resource) { if (!(<API key>->masker == resource)) <API key>.access().masker = resource; } inline void SVGRenderStyle::<API key>(const String& resource) { if (!(<API key>->markerStart == resource)) <API key>.access().markerStart = resource; } inline void SVGRenderStyle::<API key>(const String& resource) { if (!(<API key>->markerMid == resource)) <API key>.access().markerMid = resource; } inline void SVGRenderStyle::<API key>(const String& resource) { if (!(<API key>->markerEnd == resource)) <API key>.access().markerEnd = resource; } inline void SVGRenderStyle::setBitDefaults() { m_inheritedFlags.clipRule = initialClipRule(); m_inheritedFlags.colorRendering = <API key>(); m_inheritedFlags.fillRule = initialFillRule(); m_inheritedFlags.shapeRendering = <API key>(); m_inheritedFlags.textAnchor = initialTextAnchor(); m_inheritedFlags.colorInterpolation = <API key>(); m_inheritedFlags.<API key> = <API key>(); m_inheritedFlags.<API key> = <API key>(); m_inheritedFlags.<API key> = <API key>(); m_nonInheritedFlags.flags = 0; m_nonInheritedFlags.flagBits.alignmentBaseline = <API key>(); m_nonInheritedFlags.flagBits.dominantBaseline = <API key>(); m_nonInheritedFlags.flagBits.baselineShift = <API key>(); m_nonInheritedFlags.flagBits.vectorEffect = initialVectorEffect(); m_nonInheritedFlags.flagBits.bufferedRendering = <API key>(); m_nonInheritedFlags.flagBits.maskType = initialMaskType(); } inline bool SVGRenderStyle::InheritedFlags::operator==(const InheritedFlags& other) const { return colorRendering == other.colorRendering && shapeRendering == other.shapeRendering && clipRule == other.clipRule && fillRule == other.fillRule && textAnchor == other.textAnchor && colorInterpolation == other.colorInterpolation && <API key> == other.<API key> && <API key> == other.<API key> && <API key> == other.<API key>; } } // namespace WebCore
#include <gab/chromosome.hpp> using namespace gab; chromosome::chromosome(const chromosome::container_type::size_type size) : _genes(size) { } chromosome::chromosome(const chromosome &other) : _genes(other._genes) { } chromosome::value_type &chromosome::operator[](const chromosome::container_type::size_type i) { return _genes[i]; } const chromosome::value_type &chromosome::operator[](const chromosome::container_type::size_type i) const { return _genes[i]; } const chromosome::container_type &chromosome::genes() const noexcept { return _genes; } chromosome::container_type &chromosome::genes() noexcept { return _genes; } typename chromosome::container_type::size_type chromosome::size() const noexcept { return _genes.size(); } bool chromosome::valid() const noexcept { return !_genes.empty(); } bool chromosome::operator ==(const chromosome &rhs) const { return _genes == rhs._genes; } chromosome &chromosome::operator =(const chromosome &rhs) { _genes = rhs._genes; return *this; }
using Microsoft.EntityFrameworkCore.Storage; using System.Threading; using System.Threading.Tasks; namespace LINQtoGremlin.Core.Storage.Internal { public class GDbDatabaseCreator : IDatabaseCreator , IGDbDatabaseCreator { #region Constructors public GDbDatabaseCreator( IGDbDatabase database) => _gDatabase = database; #endregion #region Methods public virtual bool EnsureCreated() => _gDatabase .<API key>(); public virtual Task<bool> EnsureCreatedAsync( Cancellation<API key> = default(CancellationToken)) => Task .FromResult( EnsureCreated()); public virtual bool EnsureDeleted() => _gDatabase .<API key>(); public virtual Task<bool> EnsureDeletedAsync( Cancellation<API key> = default(CancellationToken)) => Task .FromResult( EnsureDeleted()); #endregion #region Fields private readonly IGDbDatabase _gDatabase; #endregion } }
*** HTTP GET http://139.196.28.108/Laputa_admin_demo/code/api/ci/index.php?c=DataRegion&m=getDataRegionInfo | | | | | | | : | access_token | true | string | null | | | region_id | true | int | null | ID | http://139.196.28.108/Laputa_admin_demo/code/api/ci/index.php?c=DataRegion&m=getDataRegionInfo | | | | | | | : | code | | | int | | | msg | | | string | | | data | | | array | | | | info | | array | | | | | region_id | int | ID | | | | parent_id | int | ID | | | | region_name | string | | | | | english_name | string | | | | | abbr | string | / | | | | code | string | | | | | zipcode | string | | | | | area_code | string | | | | | time_zone | string | | { "code": "0", "msg": "Success", "data": { "info": { "region_id": "4", "parent_id": null, "region_name": "", "english_name": "beijing", "abbr": "BJ", "code": null, "zipcode": null, "area_code": null, "time_zone": null } } }
$LOAD_PATH.unshift 'lib/' begin require 'rubygems' gem 'mocha', '>= 0.4.0' require 'mocha' gem 'test-spec' require 'test/spec' require 'active_support' rescue LoadError puts '=> has_representations tests depend on the following gems: mocha (0.4.0+), test-spec and rails.' end begin require 'redgreen' rescue LoadError nil end Test::Spec::Should.send :alias_method, :have, :be Test::Spec::ShouldNot.send :alias_method, :have, :be # ActiveRecord::Base.disconnect! require 'has_representations' Object.send :include, HasRepresentations # Fake out ActiveRecord so that we can conduct our testing in peace. class Action attr_accessor :actor_id, :actee_id, :action, :<API key>, :<API key> def initialize(attributes = {}) attributes.each { |key, value| <API key>("@#{key}", value) } end %w(before_save after_destroy).each do |callback| eval <<-"end_eval" def self.#{callback}(&block) @#{callback}_callbacks ||= [] @#{callback}_callbacks << block if block_given? @#{callback}_callbacks end end_eval end end
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function <API key>(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = <API key>(_react); var <API key> = require('../stores/QuestionStore'); var <API key> = <API key>(<API key>); var <API key> = require('../stores/AnswerStore.js'); var <API key> = <API key>(<API key>); var <API key> = require('../actions/<API key>'); var <API key> = <API key>(<API key>); var _AppJsx = require('./App.jsx'); var _AppJsx2 = <API key>(_AppJsx); exports['default'] = _react2['default'].createClass({ displayName: 'AppContainer', /* * attempted validation, fail */ //propTypes: { // // You can also specify a custom validator. It should return an Error // // object if the validation fails. Don't `console.warn` or throw, as this // // won't work inside `oneOfType`. // scores: function(props, propName, componentName) { // var keys = Object.keys(props[scores]); // //if (!/matchme/.test(props[propName])) { // return new Error('Validation failed!'); _onChange: function _onChange() { this.setState(<API key>['default'].getAll()); this.setState({ scores: <API key>['default'].getAll() }); }, getInitialState: function getInitialState() { return { questions: <API key>['default'].<API key>(), score: 0, scores: {}, alertVisible: false, resultVisible: false }; }, componentDidMount: function componentDidMount() { <API key>['default'].addChangeListener(this._onChange); <API key>['default'].addChangeListener(this._onChange); }, <API key>: function <API key>() { <API key>['default'].<API key>(this._onChange); <API key>['default'].<API key>(this._onChange); }, /* * method that will handle submit button and determine which view to display, * probably would be refactored to hold business logic away from client, but outside of * scope of current assignment */ handleTally: function handleTally() { //var scores = AnswerStore.getAll() var keys = Object.keys(this.state.scores.scores); var allScores = this.state.scores.scores; // make sure all questions are answered. if (keys.length === 9) { // calculates score. var score = keys.reduce(function (sum, key) { sum += +allScores[key]; return sum; }, 0); //if(score > 10){ this.setState({ resultVisible: true }); this.setState({ score: score }); //ActionCreator.tally(score); } else { this.setState({ alertVisible: true }); } }, render: function render() { var _state = this.state; var questions = _state.questions; var alertVisible = _state.alertVisible; var resultVisible = _state.resultVisible; var score = _state.score; return _react2['default'].createElement(_AppJsx2['default'], { onTally: this.handleTally, questions: questions, onAlert: alertVisible, onResult: resultVisible, <API key>: this.handleAlertDismiss, onHandleAlertShow: this.handleAlertShow, score: score }); } }); module.exports = exports['default']; //# sourceMappingURL=<API key>.js.map
import React, { Component } from 'react'; import Card from '../../partials/card'; import styles from './style.scss'; class Index extends Component { render() { return ( <div className={styles.home}> <Card> 1 </Card> <Card> 1 </Card> <Card> 1 </Card> <Card> 1 </Card> </div> ); } } export default Index;
package net.fortytwo.ripple.sail; import info.aduna.iteration.CloseableIteration; import net.fortytwo.ripple.RippleException; import net.fortytwo.ripple.libs.control.ControlLibrary; import net.fortytwo.ripple.model.ModelConnection; import net.fortytwo.ripple.model.Operator; import net.fortytwo.ripple.model.RippleList; import net.fortytwo.ripple.model.impl.sesame.<API key>; import net.fortytwo.ripple.query.<API key>; import org.openrdf.model.IRI; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.Value; import org.openrdf.query.BindingSet; import org.openrdf.query.Dataset; import org.openrdf.query.<API key>; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.evaluation.EvaluationStrategy; import org.openrdf.query.algebra.evaluation.TripleSource; import org.openrdf.query.algebra.evaluation.impl.<API key>; import org.openrdf.sail.SailException; import org.openrdf.sail.helpers.<API key>; public class <API key> extends <API key> { private final ModelConnection modelConnection; private final RippleValueFactory valueFactory; public <API key>(final ModelConnection modelConnection, final RippleValueFactory valueFactory) { super(((<API key>) modelConnection).getSailConnection()); this.modelConnection = modelConnection; this.valueFactory = valueFactory; } @Override public CloseableIteration<? extends BindingSet, <API key>> evaluate( final TupleExpr query, final Dataset dataset, final BindingSet bindings, final boolean includeInferred) throws SailException { try { TripleSource tripleSource = new <API key>(this, valueFactory, includeInferred); EvaluationStrategy strategy = new <API key>(tripleSource, dataset, null); return strategy.evaluate(query, bindings); } catch (<API key> e) { throw new SailException(e); } } @Override public CloseableIteration<? extends Resource, SailException> getContextIDs() throws SailException { // When implementing this method, make sure that only RippleSesameValues are passed up throw new <API key>(); } @Override public void addStatement(final Resource subject, final IRI predicate, final Value object, final Resource... contexts) throws SailException { // When implementing this method, make sure that only RippleSesameValues are passed down throw new <API key>(); } @Override public void removeStatements(final Resource subject, final IRI predicate, final Value object, final Resource... contexts) throws SailException { // Implement this method if/when addStatement is implemented throw new <API key>(); } @Override public void clear(final Resource... contexts) throws SailException { // Implement this method if/when addStatement is implemented throw new <API key>(); } @Override public CloseableIteration<? extends Statement, SailException> getStatements( Resource subject, IRI predicate, Value object, final boolean includeInferred, final Resource... contexts) throws SailException { // An "all wildcards" query, or a query with a wildcard predicate, just goes to the base SailConnection if (null == predicate || (null == subject && null == object)) { return <API key>().getStatements(subject, predicate, object, includeInferred, contexts); } // Forward traversal else if (null != subject && null == object) { if (!(subject instanceof RippleSesameValue)) { subject = (Resource) valueFactory.nativize(subject); } RippleList stack = ((RippleSesameValue) subject).getStack(); if (null == stack) { stack = modelConnection.list().push(modelConnection.canonicalValue(subject)); // Note: this may or may not be worth the extra CPU cycles. ((RippleSesameValue) subject).setStack(stack); } stack = stack.push(modelConnection.canonicalValue( valueFactory.nativize(predicate))).push(Operator.OP); CloseableIteration<RippleList, RippleException> solutions = new <API key>(stack, modelConnection); return new SolutionIteration(solutions, false, subject, predicate, object, contexts); } // Backward traversal else if (null == subject) { if (!(object instanceof RippleSesameValue)) { object = valueFactory.nativize(object); } RippleList stack = ((RippleSesameValue) object).getStack(); if (null == stack) { stack = modelConnection.list().push(modelConnection.canonicalValue(object)); // Note: this may or may not be worth the extra CPU cycles. ((RippleSesameValue) object).setStack(stack); } stack = stack.push(modelConnection.canonicalValue(predicate)) .push(ControlLibrary.getInverseValue()) .push(Operator.OP) .push(Operator.OP); CloseableIteration<RippleList, RippleException> solutions = new <API key>(stack, modelConnection); return new SolutionIteration(solutions, true, subject, predicate, object, contexts); } else { return <API key>().getStatements(subject, predicate, object, includeInferred, contexts); } } private class SolutionIteration implements CloseableIteration<Statement, SailException> { private final CloseableIteration<RippleList, RippleException> iter; private final boolean inverse; private final Resource subject; private final IRI predicate; private final Value object; private Statement nextStatement; public SolutionIteration(CloseableIteration<RippleList, RippleException> iter, boolean inverse, Resource subject, IRI predicate, Value object, Resource... contexts) throws SailException { this.iter = iter; this.inverse = inverse; this.subject = subject; this.predicate = predicate; this.object = object; advanceToNext(); } @Override public void close() throws SailException { try { iter.close(); } catch (RippleException e) { throw new SailException(e); } } @Override public boolean hasNext() throws SailException { return null != nextStatement; } private void advanceToNext() throws SailException { try { nextStatement = null; if (iter.hasNext()) { RippleList stack = iter.next(); if (inverse) { Value subj = modelConnection.toRDF(stack.getFirst()); RippleSesameValue s = (RippleSesameValue) valueFactory.nativize(subj); s.setStack(stack); nextStatement = valueFactory.createStatement((Resource) s, predicate, object); } else { Value r = modelConnection.toRDF(stack.getFirst()); Value obj; RippleSesameValue o; if (null == r) { o = new RippleBNode(); o.setStack(stack); } else { obj = r; o = (RippleSesameValue) valueFactory.nativize(obj); o.setStack(stack); } nextStatement = valueFactory.createStatement(subject, predicate, (Value) o); } } } catch (RippleException e) { throw new SailException(e); } } @Override public Statement next () throws SailException { Statement s = nextStatement; advanceToNext(); return s; } @Override public void remove() throws SailException { throw new <API key>(); } } @Override public void begin() { // Do nothing; adapt to SesameModel, which begins transactions implicitly } }
#include <vector> #include <limits> #include <algorithm> #include "wave.h" #ifdef max # undef max #endif class WayFinder { private: Maze* maze; Matrix<int> dist; Matrix<Point2d> last; //std::vector<Point2d> *way; std::vector<Point2d> *wave0, *wave1, *wavex; public: WayFinder(Maze* maze): maze(maze), dist(maze->getX(), maze->getY()), last(maze->getX(), maze->getY()) { dist.fill(std::numeric_limits<int>::max()); } void step(Point2d from, Point2d to) { if (maze->at(to) == 0 && dist[to.x][to.y] > dist[from.x][from.y] + 1) { this->wave1->push_back(to); this->last[to.x][to.y] = from; this->dist[to.x][to.y] = this->dist[from.x][from.y] + 1; } } void findWay(std::vector<Point2d>* way) { //this->way = way; this->wave0 = new std::vector<Point2d>; this->wave1 = new std::vector<Point2d>; wave0->push_back(Point2d(0, 0)); last[0][0] = Point2d(0, 0); dist[0][0] = 0; while (wave0->size() != 0) { for (std::vector<Point2d>::iterator i = wave0->begin(); i != wave0->end(); i++) { step(*i, Point2d(i->x + 1, i->y)); step(*i, Point2d(i->x - 1, i->y)); step(*i, Point2d(i->x, i->y + 1)); step(*i, Point2d(i->x, i->y - 1)); } wavex = wave1; wave1 = wave0; wave0 = wavex; wave1->clear(); } if (dist[maze->getX() - 1][maze->getY() - 1] < std::numeric_limits<int>::max()) { Point2d pos(maze->getX() - 1, maze->getY() - 1); way->push_back(pos); while (!(pos.x == 0 && pos.y == 0)) { pos = last[pos.x][pos.y]; way->push_back(pos); } std::reverse(way->begin(), way->end()); } delete this->wave0; delete this->wave1; } }; void FindWay(std::vector<Point2d>* way, Maze* maze) { WayFinder finder(maze); finder.findWay(way); }
## DNTagView [![Version](https: [![License](https: [![Platform](https: This library is derived from [SKTagView](https://github.com/zsk425/SKTagView), which tries to build a view displaying tags without using UICollectionView and supports Autolayout. It supports to add tags by UITextField now, and using UIMenuController to delete tag. Installation with CocoaPods ruby platform :ios, '8.0' pod 'DNTagView' ## Usage # Create tag view container objc self.tagView = ({ DNTagView *view = [DNTagView new]; view.backgroundColor = [UIColor cyanColor]; view.padding = UIEdgeInsetsMake(10, 25, 10, 25); view.interitemSpacing = 8; view.lineSpacing = 10; // set delegate view.delegate = self; view; }); # Build tag [@[@"Python", @"Javascript", @"HTML", @"Go", @"Objective-C", @"C", @"PHP"] <API key>:^(NSString *text, NSUInteger idx, BOOL *stop) { DNTag *tag = [DNTag tagWithText:text]; tag.textColor = [UIColor blackColor]; tag.fontSize = 15; tag.padding = UIEdgeInsetsMake(5, 5, 5, 5); tag.bgColor = [UIColor <API key>:@"0x017E66" alpha:0.08]; tag.cornerRadius = 3; [self.tagView addTag:tag]; }]; # Delegate - optional objc - (void)didInputText:(NSString *)text { // you input text; } - (void)completeInputText:(NSString *)text { // clicked return key } - (void)deleteTag:(NSInteger)index { // you have deleted the indexth tag; } ## ScreenShot ![](https://raw.githubusercontent.com/dawnnnnn/DNTagView/master/screenshots/screenshot.gif) License DNTagView is available under the MIT license. See the LICENSE file for more info.
body { background-color: #000; margin: 0px; overflow: hidden; color: #fff; font-size: 13px; padding:10px; font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; } #controls{ position:absolute; background-color: #000; top: 230px; right:10px; width:250px; } #audioDebug{ position:absolute; background-color: #000; width: calc(100% - 270px); height: calc(100% - 20px); } #info{ position:absolute; background-color: #000; top: 0px; right:10px; width:250px; height: 150px; line-height: 20px; } a { color: #fff; text-decoration: none; border-bottom:thin dotted #999; } h2{ font-weight: 100; font-size: 24px; } #preloader{ position: absolute; width: 40px; height: 40px; top: 50%; left: 50%; margin-left: -20px; margin-top:-20px; background:url(loader.gif) center center no-repeat; }
<script> (function (root, factory) { root.Elliptical.Behaviors=root.Elliptical.Behaviors || {}; root.Elliptical.Behaviors.Navbar=factory(); }(this, function () { return { /** * @private */ _setData: function () { this._data.set('height', null); this._data.set('drawer', null); this._data.set('input', null); this._data.set('touchInput', null); this._data.set('open', false); this._data.set('toggle', null); this._data.set('element', null); }, /** * private method to show the drawer menu * @private */ _show: function () { if(this._mq.touch && !this._data.get('open') && this._data.get('drawer')){ var self = this; this._triggerEvent('showing', {}); this._data.set('open', true); var element = this.element; element.css({ position: 'absolute' }); var toggle = this._data.get('toggle'); toggle.addClass('active'); this._openDrawer(function () { self._triggerEvent('show', {}); }, function(){ self._hide(); }); } }, /** * private method to hide drawer menu * @private */ _hide: function () { if(this._mq.touch && this._data.get('open') && this._data.get('drawer')){ var self = this; this._triggerEvent('hiding', {}); this._data.set('open', false); var element = this.element; var toggle = this._data.get('toggle'); toggle.removeClass('active'); this._closeDrawer(function(){ element.css({ position: '', top:'' }); self._resetMenu(); self._triggerEvent('hide', {}); }); } }, /** * * @private */ <API key>:function(){ if (this._mq.touch) { var currHeight = this._device.viewport.height; var height = this._data.get('height'); if (height != currHeight) { if (this._data.get('open')) this._hide(); } this._data.set('height', currHeight); } }, /** * * @private */ <API key>:function(){ var self=this; setTimeout(function () { self._show(); }, self.touchDelay) }, /** * * @param {string} query * @param {object} mq * @private */ _onMediaQuery: function(query,mq){ if(query==='touch'){ if (mq.matches) { //create navigation this.<API key>(this.element, this.dataClass); //reset open state this._data.set('open', false); //bind the events this._touchMenuEvents(); } }else{ if (mq.matches) { //reset open state this._data.set('open', false); //remove navigation this.<API key>(); } } }, <API key>:function(){ if (this._mq.touch) { this.<API key>(); this.<API key>(this.element, this.dataClass); //reset open state this._data.set('open', false); //bind the events this._touchMenuEvents(); } }, /** * element desktop events * @private */ _desktopEvents: function () { /* events for desktop testing */ //desktop 'resize' var self = this; //media queries to fire build,destroy drawer on screen change var mq = window.matchMedia(this._mq.touchQuery); mq.addListener(function () { self._onMediaQuery('touch',mq) }); var mql = window.matchMedia(this._mq.desktopQuery); mql.addListener(function () { self._onMediaQuery('desktop',mql); }); }, /** * * @param {object} event * @param {string} tag * @private */ _onTouchMenuEvent:function(event,tag){ event.preventDefault(); var item = $(event.target); this._touchMenuItem(item); }, /** * link element triggers location or a dev handled event * @param a {object} link element * @param handleTouchEvents {Boolean} * @private */ _touchMenuItem:function(a,handleTouchEvents){ var self=this; var duration=(this.options) ? this.options.transformDuration : this.transformDuration; duration+=100; var href = a.attr('href'); /* close the drawer */ this._hide(); console.log(this._location); //if href, location redirect if (typeof href != 'undefined' && href != ' /* trigger location after the drawer has closed */ setTimeout(function(){ self._location(href); },duration); } }, /** * toggles touch sub-menu * @param item {Object} * @private */ <API key>:function(item){ var selector=this.__dropdownSelector(); var dropdown=item.find(selector); if (dropdown.hasClass('show')) { item.removeClass('close'); dropdown.removeClass('show'); } else { item.addClass('close'); dropdown.addClass('show'); } }, /** * element touch menu events * @private */ _touchMenuEvents: function () { var press=('ontouchend' in document) ? 'touchend' : 'click'; var self = this; var drawer = this._data.get('drawer'); if (!drawer) { return false; } this._event(drawer,press,'menu-item-dropdown:not(touch-ui-dropdown)',function(event){ self.<API key>($(event.target)); }); if(!this.disableTouchEvents){ this._event(drawer,press,'touch-ui-menu>menu-item>a:not([data-ignore])',function(event){ self._onTouchMenuEvent(event); }); } }, /** * * @private */ _unbindMQListeners:function(){ var self = this; var mq = window.matchMedia(this._.mq.touchQuery); mq.removeListener(function () { self._onMediaQuery('touch',mq) }); var mql = window.matchMedia(this._mq.desktopQuery); mql.removeListener(function () { self._onMediaQuery('desktop',mql); }); }, /** * * @private */ _navbarDispose:function(){ this._unbindMQListeners(); }, /** * public method to show drawer menu * @public */ show: function () { var navScrollTop='navScrollTop' + this.eventNamespace; this.<API key>(0, navScrollTop); }, /** * append menu items from model * @public */ addMenuModel: function(model){ this._addMenuModel(model); } }; })); </script>
package com.owncloud.android.lib.resources.files; import java.io.File; import org.apache.jackrabbit.webdav.client.methods.DavMethodBase; import android.util.Log; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.network.WebdavUtils; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.<API key>; import com.owncloud.android.lib.common.operations.<API key>.ResultCode; /** * Remote operation performing the rename of a remote file or folder in the ownCloud server. * * @author David A. Velasco * @author masensio */ public class <API key> extends RemoteOperation { private static final String TAG = <API key>.class.getSimpleName(); private static final int RENAME_READ_TIMEOUT = 10000; private static final int <API key> = 5000; private String mOldName; private String mOldRemotePath; private String mNewName; private String mNewRemotePath; /** * Constructor * * @param oldName Old name of the file. * @param oldRemotePath Old remote path of the file. * @param newName New name to set as the name of file. * @param isFolder 'true' for folder and 'false' for files */ public <API key>(String oldName, String oldRemotePath, String newName, boolean isFolder) { mOldName = oldName; mOldRemotePath = oldRemotePath; mNewName = newName; String parent = (new File(mOldRemotePath)).getParent(); parent = (parent.endsWith(FileUtils.PATH_SEPARATOR)) ? parent : parent + FileUtils.PATH_SEPARATOR; mNewRemotePath = parent + mNewName; if (isFolder) { mNewRemotePath += FileUtils.PATH_SEPARATOR; } } /** * Performs the rename operation. * * @param client Client object to communicate with the remote ownCloud server. */ @Override protected <API key> run(OwnCloudClient client) { <API key> result = null; LocalMoveMethod move = null; boolean noInvalidChars = FileUtils.isValidPath(mNewRemotePath); if (noInvalidChars) { try { if (mNewName.equals(mOldName)) { return new <API key>(ResultCode.OK); } // check if a file with the new name already exists if (client.existsFile(mNewRemotePath)) { return new <API key>(ResultCode.INVALID_OVERWRITE); } move = new LocalMoveMethod( client.getWebdavUri() + WebdavUtils.encodePath(mOldRemotePath), client.getWebdavUri() + WebdavUtils.encodePath(mNewRemotePath)); int status = client.executeMethod(move, RENAME_READ_TIMEOUT, <API key>); move.<API key>(); // exhaust response, although not interesting result = new <API key>(move.succeeded(), status, move.getResponseHeaders()); Log.i(TAG, "Rename " + mOldRemotePath + " to " + mNewRemotePath + ": " + result.getLogMessage()); } catch (Exception e) { result = new <API key>(e); Log.e(TAG, "Rename " + mOldRemotePath + " to " + ((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " + result.getLogMessage(), e); } finally { if (move != null) move.releaseConnection(); } } else { result = new <API key>(ResultCode.<API key>); } return result; } /** * Move operation * */ private class LocalMoveMethod extends DavMethodBase { public LocalMoveMethod(String uri, String dest) { super(uri); addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest)); } @Override public String getName() { return "MOVE"; } @Override protected boolean isSuccess(int status) { return status == 201 || status == 204; } } }
<?php session_start(); if (!isset($_SESSION['user_id'])) { // redirect header('Location: index.php'); } else { $userID = $_SESSION['user_id']; } require_once 'config/connection.php'; require 'src/User.php'; $user = User::loadUserById($conn, $userID); if ($_SERVER['REQUEST_METHOD'] === 'POST') { /** * @ToDo: Filter received data * @ToDo: Add error messages */ $pass = $_POST['old-password']; if (password_verify($pass, $user->getHashPass())) { $somethingChange = false; $newUsername = trim($_POST['username']); if (strlen($newUsername) > 0 && $newUsername != $user->getUsername()) { $user->setUsername($newUsername); $somethingChange = true; } $newEmail = trim($_POST['email']); if (strlen($newEmail) > 0 && $newEmail != $user->getEmail()) { $user->setEmail($newEmail); $somethingChange = true; } $newPass = trim($_POST['new-password']); $retypedNewPass = trim($_POST['<API key>']); if (strlen($newPass) > 0 && $newPass == $retypedNewPass) { $user->setPass($newPass); $somethingChange = true; } elseif (strlen($newPass) > 0 && $newPass != $retypedNewPass) { $errorMessage = 'New password and retyped new password doesn\'t match.'; } if ($somethingChange) { $user->saveToDB($conn); // update user data in session $_SESSION['username'] = $user->getUsername(); $_SESSION['user_email'] = $user->getEmail(); $successMessage = 'New user data has been successfully saved.'; } } else { $errorMessage = 'To change data You have to enter correct current password.'; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Something Like Twitter - User Edit Page</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" href="css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <!--NAV START <?php include('includes/nav.php'); ?> <!--NAV END <div class="container"> <div class="edit-user"> <div class="row"> <?php if (isset($successMessage)) { echo '<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 alert alert-success">'; echo $successMessage; echo '</div>'; } ?> </div> <div class="row"> <?php if (isset($errorMessage)) { echo '<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 alert alert-danger">'; echo $errorMessage; echo '</div>'; } ?> </div> <div class="row"> <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <div class="form-group"> <form action="" method="post" role="form"> <label for="username">Username</label> <input type="text" name="username" id="username" class="form-control" value="<?php echo $user->getUsername(); ?>"> <br> <label for="email">Email</label> <input type="text" name="email" id="email" class="form-control" value="<?php echo $user->getEmail(); ?>"> <br> <label for="password">Old password</label> <input type="password" name="old-password" id="old-password" class="form-control"> <br> <label for="password">New password</label> <input type="password" name="new-password" id="new-password" class="form-control"> <br> <label for="password">Retype new password</label> <input type="password" name="<API key>" id="<API key>" class="form-control"> <br> <button type="submit" class="btn btn-default">Save</button> </form> </div> <p><a href="index.php">Return to main page</a></p> </div> </div> </div> </div> </body> </html>
import React, {Component, PropTypes} from 'react'; class PassageClick extends Component { render() { return ( <div> PassageClick </div> ); } } PassageClick.propTypes = { }; export default PassageClick;
import * as assert2 from "../base/assert2.js"; import * as url2 from "../base/url2.js"; describe('url', function () { it('should succeed', function () { const params = {a: 10}; const params2 = {a: 10, b: 'big'}; assert2.e(url2.url('http: assert2.e(url2.url('http: assert2.e(url2.url('http: }); }); describe("UrlMaker", function () { it("url should succeed", function () { assert2.e(new url2.UrlMaker('/thread').done(), '/thread'); }); it("query param should succeed", function () { assert2.e(new url2.UrlMaker('/thread').add('p', 10).done(), '/thread?p=10'); }); it("query params should succeed", function () { assert2.e(new url2.UrlMaker('/thread').add('p', 10).add('ps', 16).done(), '/thread?p=10&ps=16'); }); it("default value should succeed", function () { assert2.e(new url2.UrlMaker('/thread').add('p', 0, 0).add('ps', 16, 32).done(), '/thread?ps=16'); }); });
$(function () { $('.navbar-toggle').click(function () { $('.navbar-nav').toggleClass('slide-in'); $('.side-body').toggleClass('body-slide-in'); $('#search').removeClass('in').addClass('collapse').slideUp(200); uncomment code for absolute positioning tweek see top comment in css //$('.absolute-wrapper').toggleClass('slide-in'); }); $('.dropdown_artist').click(function () { $('.side-menu-container .nav_sub_artist').toggleClass('open'); }); });
#ifndef <API key> #define <API key> #include "script/interpreter.h" #include <vector> class CPubKey; class <API key> : public <API key> { private: bool store; public: <API key>(const CTransaction* txToIn, unsigned int nInIn, bool storeIn=true) : <API key>(txToIn, nInIn), store(storeIn) {} bool VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const; }; #endif // <API key>
// JavaScript Document // jQuery 1.8.2 plug-in // set point by star ;(function($){ /*code here*/ $.fn.extend({ "star":function(point,fun){ //point, //1. 5<li>, var dat; var init_data=["0px 17px","0px 17px","0px 17px","0px 17px","0px 17px"]; for(var init=0;init<point;init++){ init_data[init]="0px 0px"; } var picurl="../img/star.png"; var html='<li style="left:0px;position: absolute;width: 18px;height: 17px;list-style: none;background: url('+picurl+');background-position:'+init_data[0]+';"></li><li style="left:18px;position: absolute;width: 18px;height: 17px;list-style: none;background: url('+picurl+');background-position:'+init_data[1]+';"></li><li style="left:36px;position: absolute;width: 18px;height: 17px;list-style: none;background: url('+picurl+');background-position:'+init_data[2]+';" ></li><li style="left:54px;position: absolute;width: 18px;height: 17px;list-style: none;background: url('+picurl+');background-position:'+init_data[3]+';" ></li><li style="left:72px;position: absolute;width: 18px;height: 17px;list-style: none;background: url('+picurl+');background-position:'+init_data[4]+';" ></li>'; this.append(html);//thisjQuery var liEleArray=this.children("li"); this.mouseout(function(e) { for(var r=0;r<5;r++){ $(liEleArray[r]).css("background-position",init_data[r]); } }); for(var i=0;i<5;i++){ $(liEleArray[i]).data("data",i+1); $(liEleArray[i]).mouseover(function(e) {//mouseover $(this).nextAll().css("background-position","0px 17px"); $(this).css("background-position","0px 0px"); $(this).prevAll().css("background-position","0px 0px"); }); $(liEleArray[i]).mouseout(function(e) {//mouseout $(this).css("background-position","0px 17px"); $(this).prevAll().css("background-position","0px 17px"); }); $(liEleArray[i]).click(function(e) {//click dat=$(this).data("data"); //clickfun /*Run fun*/fun(dat);//datfun //mouseover,mouseout,click liEleArray.unbind("mouseover"); liEleArray.unbind("mouseout"); liEleArray.unbind("click"); }); } return this;//jQueryjQuery } }); })(jQuery);
<?php defined('BASEPATH') OR exit('No direct script access allowed'); $route['default_controller'] = 'principal'; $route['404_override'] = ''; $route['<API key>'] = FALSE; $route['filme/(:any)/editar'] = 'filme/editar/$1'; $route['usuario/(:any)/editar'] = 'usuario/editar/$1';
{% load i18n %} <p> {% trans "Click on the primary key value to access the individual Crc's page." %} </p> <table class='table table-bordered table-striped'> <thead> <tr> <th> Id </th> <th> Code </th> <th> Crc </th> <th> Block </th> </tr> </thead> <tbody> {% for object in object_list %} <tr> <td> <a href='{% url "school_crc_detail" pk=object.pk %}'> {{ object.id|stringformat:".3d" }} </a> </td> <td>{{ object.code }}</td> <td>{{ object.crc }}</td> <td>{{ object.block }}</td> </tr> {% endfor %} </tbody> </table>
#include "<API key>.h" #include "facilecoinunits.h" #include "clientversion.h" #include "guiutil.h" #include "optionsmodel.h" #include "streams.h" #include <boost/foreach.hpp> <API key>::<API key>(CWallet *wallet, WalletModel *parent) : walletModel(parent) { Q_UNUSED(wallet); <API key> = 0; // Load entries from wallet std::vector<std::string> vReceiveRequests; parent->loadReceiveRequests(vReceiveRequests); BOOST_FOREACH(const std::string& request, vReceiveRequests) addNewRequest(request); /* These columns must match the indices in the ColumnIndex enumeration */ columns << tr("Date") << tr("Label") << tr("Message") << getAmountTitle(); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } <API key>::~<API key>() { /* Intentionally left empty */ } int <API key>::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return list.length(); } int <API key>::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant <API key>::data(const QModelIndex &index, int role) const { if(!index.isValid() || index.row() >= list.length()) return QVariant(); const RecentRequestEntry *rec = &list[index.row()]; if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Date: return GUIUtil::dateTimeStr(rec->date); case Label: if(rec->recipient.label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->recipient.label; } case Message: if(rec->recipient.message.isEmpty() && role == Qt::DisplayRole) { return tr("(no message)"); } else { return rec->recipient.message; } case Amount: if (rec->recipient.amount == 0 && role == Qt::DisplayRole) return tr("(no amount)"); else if (role == Qt::EditRole) return FacileCoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount, false, FacileCoinUnits::separatorNever); else return FacileCoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount); } } else if (role == Qt::TextAlignmentRole) { if (index.column() == Amount) return (int)(Qt::AlignRight|Qt::AlignVCenter); } return QVariant(); } bool <API key>::setData(const QModelIndex &index, const QVariant &value, int role) { return true; } QVariant <API key>::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void <API key>::<API key>() { columns[Amount] = getAmountTitle(); emit headerDataChanged(Qt::Horizontal,Amount,Amount); } /** Gets title for amount column including current display unit if optionsModel reference available. */ QString <API key>::getAmountTitle() { QString amountTitle = tr("Amount"); if (this->walletModel->getOptionsModel() != NULL) { amountTitle += " ("+FacileCoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")"; } return amountTitle; } QModelIndex <API key>::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); return createIndex(row, column); } bool <API key>::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); if(count > 0 && row >= 0 && (row+count) <= list.size()) { const RecentRequestEntry *rec; for (int i = 0; i < count; ++i) { rec = &list[row+i]; if (!walletModel->saveReceiveRequest(rec->recipient.address.toStdString(), rec->id, "")) return false; } beginRemoveRows(parent, row, row + count - 1); list.erase(list.begin() + row, list.begin() + row + count); endRemoveRows(); return true; } else { return false; } } Qt::ItemFlags <API key>::flags(const QModelIndex &index) const { return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } // called when adding a request from the GUI void <API key>::addNewRequest(const SendCoinsRecipient &recipient) { RecentRequestEntry newEntry; newEntry.id = ++<API key>; newEntry.date = QDateTime::currentDateTime(); newEntry.recipient = recipient; CDataStream ss(SER_DISK, CLIENT_VERSION); ss << newEntry; if (!walletModel->saveReceiveRequest(recipient.address.toStdString(), newEntry.id, ss.str())) return; addNewRequest(newEntry); } // called from ctor when loading from wallet void <API key>::addNewRequest(const std::string &recipient) { std::vector<char> data(recipient.begin(), recipient.end()); CDataStream ss(data, SER_DISK, CLIENT_VERSION); RecentRequestEntry entry; ss >> entry; if (entry.id == 0) // should not happen return; if (entry.id > <API key>) <API key> = entry.id; addNewRequest(entry); } // actually add to table in GUI void <API key>::addNewRequest(RecentRequestEntry &recipient) { beginInsertRows(QModelIndex(), 0, 0); list.prepend(recipient); endInsertRows(); } void <API key>::sort(int column, Qt::SortOrder order) { qSort(list.begin(), list.end(), <API key>(column, order)); emit dataChanged(index(0, 0, QModelIndex()), index(list.size() - 1, NUMBER_OF_COLUMNS - 1, QModelIndex())); } void <API key>::updateDisplayUnit() { <API key>(); } bool <API key>::operator()(RecentRequestEntry &left, RecentRequestEntry &right) const { RecentRequestEntry *pLeft = &left; RecentRequestEntry *pRight = &right; if (order == Qt::DescendingOrder) std::swap(pLeft, pRight); switch(column) { case <API key>::Date: return pLeft->date.toTime_t() < pRight->date.toTime_t(); case <API key>::Label: return pLeft->recipient.label < pRight->recipient.label; case <API key>::Message: return pLeft->recipient.message < pRight->recipient.message; case <API key>::Amount: return pLeft->recipient.amount < pRight->recipient.amount; default: return pLeft->id < pRight->id; } }
public class UnsatLibrary03 { public static void main(final java.lang.String[] args) { String s = "one,two,three"; String[] strings = s.split(","); if (strings != null) assert (strings.length<0); } }
package reservationStations; import Instructions.Instruction; public class BEQRS extends ReservationStation { public BEQRS(int i) { // TODO Auto-generated constructor stub } @Override public boolean exec() { // TODO Auto-generated method stub return false; } @Override public short writeBack() { // TODO Auto-generated method stub return 0; } @Override public void loadInstruction(Instruction in, int indROB) { // TODO Auto-generated method stub } }
Rails4Example::Application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do
'use strict'; define('admin/plugins/anon', ['settings'], function(Settings) { var ACP = {}, banList = []; ACP.init = function() { Settings.load('anon', $('.anon-settings')); $('#save').on('click', function() { Settings.save('anon', $('.anon-settings'), function() { app.alert({ type: 'success', alert_id: 'anon-saved', title: 'Settings Saved', message: 'Please reload your NodeBB to apply these settings', clickfn: function() { socket.emit('admin.reload'); } }); }); }); $('#addBanList').on('click', function() { banList.signs.push($('#banSignField').val()) $('#banSignField').val(''); socket.emit('admin.settings.set', { hash: 'anon-banlist', values: banList }, function() { app.alert({ type: 'success', alert_id: 'anon-saved', title: 'Sign add to ban', message: 'Please reload your NodeBB to apply these settings', clickfn: function() { socket.emit('admin.reload'); } }); }); }); socket.emit('admin.settings.get', { hash: 'anon-banlist' }, function(err, values) { // Parse all values. If they are json, return json for (var key in values) { if (values.hasOwnProperty(key)) { try { values[key] = JSON.parse(values[key]); } catch (e) { // Leave the value as is } } } banList = values; if (banList.sign == null) { banList.signs = new Array(); } }); }; return ACP; });
import { declareRuntimeEnv } from '@resolve-js/scripts' const <API key> = { mode: 'development', runtime: { module: '@resolve-js/<API key>', options: { host: declareRuntimeEnv('HOST', 'localhost'), port: declareRuntimeEnv('PORT', '3000'), }, }, rootPath: '', staticPath: 'static', staticDir: 'static', distDir: 'dist', readModelConnectors: { default: { module: '@resolve-js/readmodel-lite', options: { databaseFile: 'data/<API key>.db', }, }, }, eventstoreAdapter: { module: '@resolve-js/eventstore-lite', options: { databaseFile: 'data/<API key>.db', secretsFile: 'data/<API key>.db', }, }, jwtCookie: { name: 'jwt', maxAge: 31536000000, }, } export default <API key>
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'RelativePath' => $vendorDir . '/grandt/relativepath/RelativePath.php', 'UUID' => $vendorDir . '/grandt/phpepub/src/lib.uuid.php', 'UUIDException' => $vendorDir . '/grandt/phpepub/src/lib.uuid.php', 'UUIDStorage' => $vendorDir . '/grandt/phpepub/src/lib.uuid.php', '<API key>' => $vendorDir . '/grandt/phpepub/src/lib.uuid.php', 'UUIDStorageStable' => $vendorDir . '/grandt/phpepub/src/lib.uuid.php', 'UUIDStorageVolatile' => $vendorDir . '/grandt/phpepub/src/lib.uuid.php', 'com\\grandt\\BinString' => $vendorDir . '/grandt/binstring/BinString.php', 'com\\grandt\\BinStringStatic' => $vendorDir . '/grandt/binstring/BinStringStatic.php', );
using <API key>; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; namespace Trax { class SearchResultsPanel : DockContent { private static Font _defaultFont = new Font("MS Reference Sans Serif", 8); private SearchResultsView RV; internal static Main Main; internal SearchResults Items { get { return RV.DataSource.Items; } } internal SearchResultsPanel() { Font = _defaultFont; DockPanel = Main.DockPanel; Text = Messages.SearchResults; RV = new SearchResultsView(); Controls.Add(RV); Show(DockPanel, DockState.DockBottomAutoHide); } internal void ReloadScheme() { RV.ReloadScheme(); } internal static void Reset() { if (Main.SearchResultsPanel != null && !Main.SearchResultsPanel.IsDisposed) Main.SearchResultsPanel.Items.Clear(); } internal new static void Show() { if (Main.SearchResultsPanel == null || Main.SearchResultsPanel.IsDisposed) Main.SearchResultsPanel = new SearchResultsPanel(); Main.SearchResultsPanel.VisibleState = DockState.DockBottom; Main.DockPanel.DockBottomPortion = Main.SearchResultsPanel.RV.Height; } internal static void Add(SearchResult result) { Show(); var p = Main.SearchResultsPanel; var v = p.RV; var e = Main.CurrentEditor; if (result.Replacement != null) p.Text = Messages.ReplaceResults; p.Items.Add(result); v.ClearSelection(); v.Rows[v.Rows.Count - 1].Selected = true; if (e != null) { if (result.Replacement == null) e.MarkSearchResult(result.Column - 1, result.Line - 1, result.Fragment.Length); else e.MarkReplaceResult(result.Column - 1, result.Line - 1, result.Replacement.Length); } } internal static void CloseIfEmpty() { if (Main.SearchResultsPanel != null && !Main.SearchResultsPanel.IsDisposed && Main.SearchResultsPanel.Items.Count < 1) Main.SearchResultsPanel.Close(); } } class SearchResultsView : DataGridView { internal new SearchResultsData DataSource { get { return base.DataSource as SearchResultsData; } set { base.DataSource = value; } } internal int MaxRowsVisible { get; set; } internal SearchResultsView() { DataSource = new SearchResultsData(); ReloadScheme(); AllowDrop = false; AllowUserToAddRows = false; <API key> = false; <API key> = false; <API key> = false; <API key> = true; RowHeadersVisible = true; <API key> = false; ReadOnly = true; Dock = DockStyle.Top; BorderStyle = BorderStyle.None; SelectionMode = <API key>.FullRowSelect; <API key> = <API key>.Single; <API key> = <API key>.Single; AutoSizeColumnsMode = <API key>.Fill; MaxRowsVisible = 10; } internal void ReloadScheme() { GridColor = EditorSyntax.Styles.ColorScheme.ServiceLine; BackgroundColor = EditorSyntax.Styles.ColorScheme.Background; ForeColor = EditorSyntax.Styles.ColorScheme.ProjectText; <API key>.BackColor = EditorSyntax.Styles.ColorScheme.Background; <API key>.ForeColor = EditorSyntax.Styles.ColorScheme.ProjectText; <API key>.SelectionBackColor = EditorSyntax.Styles.ColorScheme.ProjectSelection; <API key>.SelectionForeColor = EditorSyntax.Styles.ColorScheme.ProjectText; <API key>.BackColor = EditorSyntax.Styles.ColorScheme.Background; <API key>.ForeColor = EditorSyntax.Styles.ColorScheme.ProjectText; <API key>.SelectionBackColor = EditorSyntax.Styles.ColorScheme.ProjectSelection; <API key>.SelectionForeColor = EditorSyntax.Styles.ColorScheme.ProjectText; DefaultCellStyle.BackColor = EditorSyntax.Styles.ColorScheme.Background; DefaultCellStyle.ForeColor = EditorSyntax.Styles.ColorScheme.ProjectText; DefaultCellStyle.SelectionBackColor = EditorSyntax.Styles.ColorScheme.ProjectSelection; DefaultCellStyle.SelectionForeColor = EditorSyntax.Styles.ColorScheme.ProjectText; } protected override void OnParentChanged(EventArgs e) { Font = Parent.Font; <API key>.Font = new Font(Font, FontStyle.Bold); MinimumSize = new Size(MinimumSize.Width, ColumnHeadersHeight + 50); Height = MinimumSize.Height; } protected override void OnRowsAdded(<API key> e) { base.OnRowsAdded(e); if (Rows.Count > 0) { int height = 0; for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++) if (RowCount < MaxRowsVisible) height += Rows[i].Height; if (height > 0) Height += height; } } protected override void OnRowsRemoved(<API key> e) { base.OnRowsRemoved(e); if (Rows.Count < 1) Height = MinimumSize.Height; } protected override void OnCellDoubleClick(<API key> e) { if (e.RowIndex >= 0) { var item = DataSource.Items[e.RowIndex]; var file = ProjectFile.All.FirstOrDefault(i => i.Path == item.Path); if (file != null) { var editor = file.Editor; var place = item.Replacement == null ? editor.MarkSearchResult(item.Column - 1, item.Line - 1, item.Fragment.Length) : editor.MarkReplaceResult(item.Column - 1, item.Line - 1, item.Replacement.Length); editor.Selection = new Range(editor, place, place); editor.DoSelectionVisible(); editor.File.Container.Activate(); } } } } class SearchResultsData : DataTable { internal SearchResults Items { get; set; } internal SearchResultsData() { Columns.Add(Messages.PathHeader, typeof(String)); Columns.Add(Messages.FragmentHeader, typeof(String)); Columns.Add(Messages.FileHeader, typeof(String)); Columns.Add(Messages.LineHeader, typeof(Int32)); Columns.Add(Messages.ColumnHeader, typeof(Int32)); Items = new SearchResults(this); } } class SearchResults : List<SearchResult> { internal readonly SearchResultsData Data; internal SearchResults(SearchResultsData dt) { Data = dt; } internal new void Add(SearchResult r) { base.Add(r); Data.Rows.Add(new object[] { r.Path, r.Fragment, r.File, r.Line, r.Column }); } internal new void Clear() { base.Clear(); Data.Rows.Clear(); } } class SearchResult { public string Path; public string Fragment; public string Replacement; public string File; public int Line; public int Column; } }
var chai = require('chai'); var expect = chai.expect; var <API key> = require('../index.js'); var server; beforeEach(function(){ server = <API key>(); }); describe('<API key>', function(){ it('should return a function', function(){ expect(<API key>).to.be.a('function'); }); it('should return an object with a `listen` method', function(){ expect(server).to.be.an('object'); expect(server.listen).to.be.a('function'); }); });
export const <API key> = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M4 <API key>.25c1.1 0 2 .9 2 2s-.9 2-2 2H15v-2l-3 3 3 3v-2h2c2.21 0 4-1.79 4-4s-1.79-4-4-4zM4 5h16v2H4z"},"children":[]}]};
#!/usr/bin/env bash if [[ "$CI" != "true" || "$RUNNER_OS" == "macOS" ]]; then ava $@ else ava --match="!*legacy*" $@ fi
module Graphics.Urho3D.UI.Internal.Sprite( Sprite , spriteCntx , sharedSpritePtrCntx , SharedSprite ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import Graphics.Urho3D.Container.Ptr import qualified Data.Map as Map data Sprite spriteCntx :: C.Context spriteCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "Sprite", [t| Sprite |]) ] } sharedPtrImpl "Sprite"
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePlansTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('plans', function (Blueprint $table) { $table->increments('id'); // The type of plan, either PlanType::RECURRING (0) or PlanType::ONETIME (1) $table->string('type'); // Name of the plan $table->string('name'); // Price of the plan $table->decimal('price', 8, 2); // Store the amount of the charge, this helps if you are experimenting with pricing $table->decimal('capped_amount', 8, 2)->nullable(); // Terms for the usage charges $table->string('terms')->nullable(); // Nullable in case of 0 trial days $table->integer('trial_days')->nullable(); // Is a test plan or not $table->boolean('test')->default(false); // On-install $table->boolean('on_install')->default(false); // Provides created_at && updated_at columns $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('plans'); } }
require 'spec_helper' describe Predicate do describe "#initialize" do it "sets the state from the options" do p = Predicate.new({:entity => "server", :operand => "equals", :value => "foobar"}) p.entity.should == "server" p.operand.should == :equals p.value.should == "foobar" end end describe "#matches?" do before(:each) do @line = {:server => "server1", :duration => 345, :rpc => "N788XIO", :application => "sales"} end it "matches correctly using equals" do p = Predicate.new({:entity => "server", :operand => "equals", :value => "server1"}) p.matches?(@line).should be_true p = Predicate.new({:entity => "server", :operand => "equals", :value => "serv"}) p.matches?(@line).should be_false p = Predicate.new({:entity => "server", :operand => "equals", :value => "foobar"}) p.matches?(@line).should be_false end it "matches correctly using does_not_equal" do p = Predicate.new({:entity => "server", :operand => "does_not_equal", :value => "server1"}) p.matches?(@line).should be_false p = Predicate.new({:entity => "server", :operand => "does_not_equal", :value => "foobar"}) p.matches?(@line).should be_true p = Predicate.new({:entity => "server", :operand => "does_not_equal", :value => "serv"}) p.matches?(@line).should be_true end it "matches correctly using greater than" do p = Predicate.new({:entity => "duration", :operand => "greater_than", :value => "100"}) p.matches?(@line).should be_true p = Predicate.new({:entity => "duration", :operand => "greater_than", :value => "99999"}) p.matches?(@line).should be_false end it "matches correctly using less than" do p = Predicate.new({:entity => "duration", :operand => "less_than", :value => "100"}) p.matches?(@line).should be_false p = Predicate.new({:entity => "duration", :operand => "less_than", :value => "99999"}) p.matches?(@line).should be_true end it "matches correctly using like" do p = Predicate.new({ :entity => "server", :operand => "like", :value => "Serv" }) p.matches?(@line).should be_true end end end
// @flow import React from 'react'; import {connect} from 'react-redux'; import type {ContextRouter} from 'react-router'; import {withRouter} from 'react-router-dom'; import debounce from 'lodash.debounce'; import {enableFocusMode, addToast, confirmFocusMode} from '../actions'; import type {Action, Translation} from '../actions'; import { chapterCounts, locationToReference, chapterToLocation, <API key>, } from '../data/model'; import type {State} from '../reducer'; import Chapters from '../ui/chapters'; import ThatsNotInTheBible from '../ui/<API key>'; import ConfirmFocusMode from '../ui/confirm-focus-mode'; type StateProps = { +chapterCache: {[number]: string}, +enableFocusMode: boolean, +<API key>: boolean, +translation: Translation, }; const stateToProps = ({ chapters, preferences: { enableFocusMode, <API key>, translation, } }: State): StateProps => ({ chapterCache: chapters[translation], enableFocusMode, <API key>, translation, }); type DispatchProps = { +setFocusModeEnabled: boolean => any, +toast: string => any, }; const dispatchToProps = (dispatch: Action => any): DispatchProps => ({ setFocusModeEnabled: enabled => dispatch(enableFocusMode(enabled)), toast: text => dispatch(addToast(text)), confirmFocusMode: () => dispatch(confirmFocusMode()), }); const onScroll = debounce((history, location, el) => { const path = chapterToLocation(locationToReference(location)); return history.replace(`${path}?s=${el.scrollTop}`) }, 400); const getInitialScroll = () => { const url = new URL(window.location); if (!url.searchParams) return 0; const scroll = parseInt(url.searchParams.get('s'), 10); if (!Number.isNaN(scroll)) return scroll; const reference = locationToReference(window.location); if (reference.verse !== 1) return root => { const el = root.querySelector('#' + <API key>(reference)); return el? el.offsetTop : 0; }; else return 0; }; const ChaptersWithRouter = withRouter(({ chapterCache, location, history, setFocusModeEnabled, enableFocusMode, toast, <API key>, translation, confirmFocusMode, } : StateProps & DispatchProps & ContextRouter) => { const reference = locationToReference(location); return <div className='fit'> {chapterCounts[reference.book]? <Chapters reference={reference} chapterCache={chapterCache} onReferenceChange={reference => history.replace(`/${reference.book}+${reference.chapter}`)} onScroll={event => onScroll(history, location, event.currentTarget)} onClick={event => setFocusModeEnabled(!enableFocusMode)} getInitialScroll={getInitialScroll} toast={toast} translation={translation}/> : <ThatsNotInTheBible/>} {enableFocusMode && !<API key>? <ConfirmFocusMode confirmFocusMode={confirmFocusMode}/> : null} </div>; }); export default withRouter( connect(stateToProps, dispatchToProps)(ChaptersWithRouter));
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="layoutclass_pic"><div class="<API key>"><table class="ztable"><tr><th class="ztd1"><b>&nbsp;</b></th><td class="ztd2"></td></tr> <tr><th class="ztd1"><b>&nbsp;</b></th><td class="ztd2"> <font class="dianuan_mark"></font><font size=-2 color="#999900"><font class="dianyuanfont"><b><i>1></i></b></font></font><br><font size=4 color="#808080"></font><font size=4 color="#808080"></font></font> <br><font class="dianuan_mark2"></font><br></font> <div class="Rulediv"><font class="english_word">(1)</font> <font class="dianuan_mark"><font class="dianuan_mark"></font></font><font class="dianuan_mark"><font class="dianuan_mark"></font></font></font><font size=4 ></div><br><font class="dianuan_mark2"></font><br></font> <font class="dianuan_mark"><font class="dianuan_mark"></font></font><br></font> <font class="dianuan_mark"><font class="dianuan_mark"></font></font><br></font></td></tr> </td></tr></table></div> <!-- <API key> --><div class="<API key>"></div> <!-- <API key> --></div> <!-- layoutclass_pic --></td></tr></table>
layout: default billboard: /billboards/logo-colour.png <div class="main-post-list"> <ol class="post-list"> {% for post in paginator.posts %} {% assign authors = "" | split: ',' %} {% for item in post.author %} {% assign authors = authors | push: site.data.authors[item] %} {% endfor %} <li> <h2 class="<API key> post-title"><a href="{{ site.baseurl }}{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a></h2> {% if post.description %} <h3 class="<API key> post-subtitle">{{ post.description }}</h3> {% endif %} <p class="excerpt">{{ post.excerpt | remove: '<p>' | remove: '</p>' }}&hellip;</p> <div class="post-list__meta"><time datetime="{{ post.date | date: "%-d %b %Y" }}" class="<API key> date">{{ post.date | date: "%-d %b %Y" }}</time> &#8226; <span class="post-meta__tags">in {% for tag in post.tags %}{% if forloop.index != 1 %}, {% endif %}<a href="{{ site.baseurl }}/tags/#{{ tag }}">{{ tag }}</a>{% endfor %}</span> {% if authors %}<span class="post-meta__author author">by&nbsp;&nbsp;{% for item in authors %}{% if authors.size >1 %}{% if forloop.last == true %} and {% else %}{% if forloop.first == false %}, {% endif %}{% endif %}{% endif %}{% if item.image %}<img src="{{item.image}}" alt="profile image for {{item.name}}" class="avatar post-meta__avatar" /> {% endif %}<a href="{{ site.baseurl }}/authors/#{{ item.user }}" >{{item.name}}</a>{% endfor %}</span>{% endif %}</div> <hr class="post-list__divider"> </li> {% endfor %} </ol> <hr class="post-list__divider "> {% if paginator.previous_page or paginator.next_page %} {% include pagination.html %} {% endif %} </div>
if (!PhoneGap.hasResource("filetransfer")) { PhoneGap.addResource("filetransfer"); /** * FileTransfer uploads a file to a remote server. * @constructor */ FileTransfer = function() {}; /** * FileUploadResult * @constructor */ FileUploadResult = function() { this.bytesSent = 0; this.responseCode = null; this.response = null; }; /** * FileTransferError * @constructor */ FileTransferError = function() { this.code = null; }; FileTransferError.FILE_NOT_FOUND_ERR = 1; FileTransferError.INVALID_URL_ERR = 2; FileTransferError.CONNECTION_ERR = 3; /** * Given an absolute file path, uploads a file on the device to a remote server * using a multipart HTTP request. * @param filePath {String} Full path of the file on the device * @param server {String} URL of the server to receive the file * @param successCallback (Function} Callback to be invoked when upload has completed * @param errorCallback {Function} Callback to be invoked upon error * @param options {FileUploadOptions} Optional parameters such as file name and mimetype */ FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, debug) { // check for options var fileKey = null; var fileName = null; var mimeType = null; var params = null; if (options) { fileKey = options.fileKey; fileName = options.fileName; mimeType = options.mimeType; if (options.params) { params = options.params; } else { params = {}; } } PhoneGap.exec(successCallback, errorCallback, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, debug]); }; /** * Options to customize the HTTP request used to upload files. * @constructor * @param fileKey {String} Name of file request parameter. * @param fileName {String} Filename to be used by the server. Defaults to image.jpg. * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg. * @param params {Object} Object with key: value params to send to the server. */ FileUploadOptions = function(fileKey, fileName, mimeType, params) { this.fileKey = fileKey || null; this.fileName = fileName || null; this.mimeType = mimeType || null; this.params = params || null; }; };
/* In the CD+G system, 16 color graphics are displayed on a raster field which is 300 x 216 pixels in size. The middle 294 x 204 area is within the TV's "safe area", and that is where the graphics are displayed. The outer border is set to a solid color. The colors are stored in a 16 entry color lookup table. Each color in the table is drawn from an RGB space of 4096 (4 bits each for R,G and B) colors. Since we are using a 16 color table, each pixel can be stored in 4 bits, resulting in a total pixelmap size of 4 * 300 * 216 = 259200 bits = a little less than 32K. */ var CDG_COMMAND = 0x09 var <API key> = 1; var <API key> = 2; var CDG_INST_TILE_BLOCK = 6; var <API key> = 20; var <API key> = 24; var <API key> = 28; var <API key> = 30; var <API key> = 31; var <API key> = 38; var CDG_MASK = 0x3F var CDG_FULL_WIDTH = 300; var CDG_FULL_HEIGHT = 216; var CDG_DISPLAY_WIDTH = 288; var CDG_DISPLAY_HEIGHT = 192; var CDG_TILE_WIDTH = 6; var CDG_TILE_HEIGHT = 12; var CDG_TILE_ROWS = CDG_FULL_WIDTH / CDG_TILE_HEIGHT; var CDG_TILE_COLS = CDG_FULL_HEIGHT / CDG_TILE_WIDTH; var COLOUR_TABLE_SIZE = 16 function CdgCanvas(cdg, canvas) { this.cdg = cdg; this.canvas = canvas; this.ctx = canvas.getContext('2d'); this.ctx.<API key> = true; this.curPos = 0; this.colorMap = new Uint32Array(16); this.colorMap.fill(0xffffffff); // the surface as drawn using cdg is four bits per pixel, each being an index into a colormap // to make scrolling easier, we're going to waste the top four bits of each pixel. this.cdgSurface = new Uint8ClampedArray(CDG_FULL_WIDTH * CDG_FULL_HEIGHT); this.resetInvalidation(); this.borderColor = false; this.clearColor = false; this.hOffset = 0; this.vOffset = 0; } CdgCanvas.prototype = { start : function() { this.lastOffset = 0; this.startTime = Date.now(); this.curPos = 0; }, pause : function() { this.pauseTime = Date.now(0); }, resume : function() { var pausedTime = Date.now() - this.pauseTime; this.startTime += pausedTime; this.lastDraw += pausedTime; }, draw : function() { var update; // this.invalidateAll(); // always constrain to inside border var xAdjust = this.invalidateBorder ? 0 : 6; var yAdjust = this.invalidateBorder ? 0 : 12; // xAdjust -= this.hOffset // yAdjust -= this.vOffset var startX = Math.max(this.invalid.xStart, xAdjust); var startY = Math.max(this.invalid.yStart, yAdjust); var stopX = Math.min(this.invalid.xStop, CDG_FULL_WIDTH - xAdjust); var stopY = Math.min(this.invalid.yStop, CDG_FULL_HEIGHT - yAdjust); var width = stopX - startX; var height = stopY - startY; this.invalidateBorder = false; if (width <= 0 || height <= 0) return; update = new Uint8ClampedArray(width * height * 4); var idx = 0; for (var row = 0; row < height; row++) for (var col = 0; col < width; col++) { var pos = (startY + row) * CDG_FULL_WIDTH + (startX + col); var idx = (row * width + col) * 4; var color = this.colorMap[this.cdgSurface[pos]]; // var color = 0x77777777; update[idx] = (color >>> 24) & 0xff; update[idx + 1] = (color >>> 16) & 0xff; update[idx + 2] = (color >>> 8) & 0xff; update[idx + 3] = (color & 0xff); } var imageData = new ImageData(update, width, height); this.ctx.putImageData(imageData, startX - this.hOffset, startY - this.vOffset); // if we must draw the border, do that now // if (this.drawBorder || this.hOffset || this.vOffset) if (true) { hUpdate = new Uint8ClampedArray(CDG_FULL_WIDTH * CDG_TILE_HEIGHT * 4) vUpdate = new Uint8ClampedArray(CDG_FULL_HEIGHT * CDG_TILE_WIDTH * 4) var color = this.colorMap[this.borderColor]; for (var idx = 0; idx < hUpdate.length; idx += 4) { hUpdate[idx] = (color >>> 24) & 0xff; hUpdate[idx + 1] = (color >>> 16) & 0xff; hUpdate[idx + 2] = (color >>> 8) & 0xff; hUpdate[idx + 3] = (color & 0xff); } for (var idx = 0; idx < vUpdate.length; idx += 4) { vUpdate[idx] = (color >>> 24) & 0xff; vUpdate[idx + 1] = (color >>> 16) & 0xff; vUpdate[idx + 2] = (color >>> 8) & 0xff; vUpdate[idx + 3] = (color & 0xff); } var hImageData = new ImageData(hUpdate, CDG_FULL_WIDTH, CDG_TILE_HEIGHT); var vImageData = new ImageData(vUpdate, CDG_TILE_WIDTH, CDG_FULL_HEIGHT); this.ctx.putImageData(hImageData, 0, 0); this.ctx.putImageData(hImageData, 0, CDG_FULL_HEIGHT - CDG_TILE_HEIGHT); this.ctx.putImageData(vImageData, 0, 0); this.ctx.putImageData(hImageData, CDG_FULL_WIDTH - CDG_TILE_HEIGHT, 0); } }, invalidateAll : function(border) { this.invalidateRect(0, 0, CDG_FULL_WIDTH, CDG_FULL_HEIGHT); this.invalidateBorder = border; }, invalidateRect : function(xStart, yStart, xStop, yStop) { if (xStart < this.invalid.xStart) this.invalid.xStart = xStart; if (yStart < this.invalid.yStart) this.invalid.yStart = yStart; if (xStop > this.invalid.xStop) this.invalid.xStop = xStop; if (yStop > this.invalid.yStop) this.invalid.yStop = yStop; }, resetInvalidation : function() { this.invalid = { xStart: CDG_FULL_WIDTH, yStart: CDG_FULL_HEIGHT, xStop: 0, yStop: 0, }; }, xlatColor : function(index) { return this.colorMap(index); }, setTransparent : function(index) { this.colorMap[index] = 0; this.invalidateAll(true); }, setColors : function(offset, data) { function expand(bits) { return bits * 16 } for (var pos = 0; pos < 16; pos += 2) { var index = offset + pos / 2; var highByte = data[pos] & CDG_MASK; var lowByte = data[pos + 1] & CDG_MASK; var red4 = highByte >> 2; var green4 = ((highByte & 0x3) << 2) + (lowByte >> 4); var blue4 = lowByte & 0xf; var red = expand(red4); var green = expand(green4); var blue = expand(blue4); var rgba = (red << 24) + (green << 16) + (blue << 8) + (0xff); this.colorMap[index] = rgba; } this.invalidateAll(true); }, updateTile : function(data, xor) { var color0 = data[0] & 0x0f; var color1 = data[1] & 0x0f; var row = data[2] & 0x1f; var col = data[3] & 0x3f; var x = col * CDG_TILE_WIDTH; var y = row * CDG_TILE_HEIGHT; var tile = row * CDG_TILE_COLS + col; var pos = y * CDG_FULL_WIDTH + x; var pixels = data.slice(4); // run through each tile row. pos is the byte offset into the cdg surface // increment the pos by the width of the screen on each iteration for (var idx = 0; idx < 12; idx++, pos += CDG_FULL_WIDTH) { // unrole the inner loop var byte = pixels[idx]; var pixel = xor ? this.cdgSurface[pos] : 0; this.cdgSurface[pos] = pixel ^ (byte & 0x20 ? color1 : color0); pixel = xor ? this.cdgSurface[pos + 1] : 0; this.cdgSurface[pos + 1] = pixel ^ (byte & 0x10 ? color1 : color0); pixel = xor ? this.cdgSurface[pos + 2] : 0; this.cdgSurface[pos + 2] = pixel ^ (byte & 0x08 ? color1 : color0); pixel = xor ? this.cdgSurface[pos + 3] : 0; this.cdgSurface[pos + 3] = pixel ^ (byte & 0x04 ? color1 : color0); pixel = xor ? this.cdgSurface[pos + 4] : 0; this.cdgSurface[pos + 4] = pixel ^ (byte & 0x02 ? color1 : color0); pixel = xor ? this.cdgSurface[pos + 5] : 0; this.cdgSurface[pos + 5] = pixel ^ (byte & 0x01 ? color1 : color0); } this.invalidateRect(x, y, x + CDG_TILE_WIDTH, y + CDG_TILE_HEIGHT); }, clearAll : function(color) { if (this.clearColor === color) return; this.clearColor = color; this.borderColor = color; this.cdgSurface.fill(color); this.invalidateAll(true); this.drawBorder = true; }, clearBorder : function(color) { //! actually set the pixels this.borderColor = color; this.drawBorder = true; this.invalidateAll(true); }, vScroll : function(pixels, clear) { // Vertical scrolling is easiest, it is just a simple memory move. var length = CDG_FULL_WIDTH * Math.abs(pixels); var replace = new Uint8ClampedArray(length); var up = pixels < 0; var bottom = CDG_FULL_WIDTH * CDG_FULL_HEIGHT; var start = up ? 0 : bottom - length; var stop = start + length; // if we're rotating, grab the content, otherwise fill it if (clear === false) replace = this.cdgSurface.slice(start, stop); else replace.fill(clear); if (up) { this.cdgSurface.copyWithin(0, length); this.cdgSurface.set(replace, bottom - length); } else { this.cdgSurface.copyWithin(length, 0); this.cdgSurface.set(replace, 0, bottom - length); } }, hScroll : function(pixels, clear) { var length = Math.abs(pixels); var replace = new Uint8ClampedArray(length); var right = CDG_FULL_WIDTH; var left = pixels < 0; var start = left ? 0 : right - length var stop = start + length; // for horizontal scrolling we have to run a loop across all pixel rows. Much less fun. for (var row = 0, pos = 0; row < CDG_FULL_HEIGHT; row++, pos += CDG_FULL_WIDTH) { if (clear === false) replace = this.cdgSurface.slice(pos + start, pos + stop); else replace.fill(clear); if (left) { this.cdgSurface.copyWithin(pos + 0, pos + length, pos + right); this.cdgSurface.set(replace, pos + right - length); } else { this.cdgSurface.copyWithin(pos + length, pos, pos + right - length); this.cdgSurface.set(replace, pos, length); } } }, scroll : function(data, preset) { var color = data[0] & 0x0f; var hScroll = data[1] & 0x3f; var vScroll = data[2] & 0x3f; var hSCmd = (hScroll & 0x30) >> 4; var hOffset = hScroll & 0x07; var vSCmd = (vScroll & 0x30) >> 4; var vOffset = vScroll & 0x0f; var pixels; if (hSCmd !== 0) { var tiles = 0; if (hSCmd === 2) tiles = -1; else if (hSCmd === 1) tiles = 1; pixels = CDG_TILE_WIDTH * tiles; this.hScroll(pixels, preset ? color : false); } if (vSCmd !== 0) { var tiles = 0; if (vSCmd === 2) tiles = -1; else if (vSCmd === 1) tiles = 1; pixels = CDG_TILE_HEIGHT * tiles; this.vScroll(pixels, preset ? color : false); } if (this.hOffset != hOffset) { this.hOffset = hOffset; this.invalidateAll(true); this.scrolled = true; } if (this.vOffset != vOffset) { this.vOffset = vOffset; this.invalidateAll(true); this.scrolled = true; } }, executePacket : function(packet) { if (packet.command !== CDG_COMMAND) return; switch(packet.instruction) { case <API key>: this.clearAll(packet.data[0] & 0x0f); break; case <API key>: this.clearBorder(packet.data[0] & 0x0f); break; case CDG_INST_TILE_BLOCK: this.updateTile(packet.data, false); break; case <API key>: this.scroll(packet.data, true); break; case <API key>: this.scroll(packet.data, false); break; case <API key>: this.setTransparent(packet.data[0] & 0x0F); break; case <API key>: this.setColors(0, packet.data); break; case <API key>: this.setColors(8, packet.data); break; case <API key>: this.updateTile(packet.data, true); break; } if (packet.instruction !== <API key>) this.clearColor = false; }, updateSurface : function(timeOffset) { var total = Math.floor((timeOffset) * (300 / 1000)); var count = total - this.curPos; var packets = this.cdg.getPackets(this.curPos, count); if (packets.length === 0) return this.curPos <= this.cdg.length(); this.curPos = total; packets.each(function(packet) { this.executePacket(packet); }, this); this.draw(); return true; } }; module.exports = CdgCanvas;
package com.gl.docker.microservice.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageBuilder; import org.springframework.amqp.core.MessageProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.google.gson.GsonBuilder; import com.gl.docker.microservice.config.MicroserviceConfig; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; /** * @author sorabhkumar.sahu * */ @Validated @RestController @RequestMapping("/api/v2/Demo") @Api("Demo Controller for dockerization") public class DemoController { private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class); @Autowired private MicroserviceConfig config; /** * @param wfType * @param tenantId * @param projectId * @param jsonBody * @return */ @ApiOperation(value = "Mocked API for test", notes = "Mocked API") @RequestMapping(value = "/getMessage", method = RequestMethod.GET, produces = { MediaType.<API key> }) public ResponseEntity<Map<String, String>> getMessage(@RequestParam String message) { LOGGER.info("Controller processInit !"); Map<String, String> response = new HashMap<>(); response.put("response", "Hi this is mocked response for your message - " + message); return new ResponseEntity<>(response, HttpStatus.OK); } }
<?php namespace Covertechdesign\UserBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; class <API key> extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this-><API key>($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
<section class="content-header"> <h1>Sliders<small>Home page banner management</small></h1> <ol class="breadcrumb"> <li><a ui-sref="app.landing"><i class="fa fa-dashboard"></i> Home</a></li> <li><a ui-sref="app.slider">Slider Lists</a></li> <li class="active">Add Slider</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-sm-12 col-md-7"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Add Slider</h3> </div> <form enctype="multipart/form-data" class="form-horizontal" name="sliderForm" ng-submit="vm.save1(sliderForm.$valid, sliderForm)" novalidate> <div class="box-body"> <div ng-if="vm.alerts" class="alert alert-{{alert.type}}" ng-repeat="alert in vm.alerts"> <h4>{{alert.title}}</h4> <p>{{alert.msg}}</p> </div> <div class="form-group" ng-class="{ 'has-error': sliderForm.name.$invalid && ( vm.formSubmitted || sliderForm.name.$touched) }"> <label for="inputName" class="col-sm-2 control-label">Name</label> <div class="col-sm-10"> <input type="text" id="inputName" class="form-control" ng-model="vm.name" name="name" placeholder="Name" required> <p ng-show="sliderForm.name.$error.required && ( vm.formSubmitted || sliderForm.name.$touched)" class="help-block">Name is required.</p> </div> </div> <div class="form-group" ng-class="{ 'has-error': sliderForm.topic.$invalid && ( vm.formSubmitted || sliderForm.topic.$touched) }"> <label for="inputImage" class="col-sm-2 control-label">Image</label> <div class="col-sm-10"> <input type="file" id="inputImage" class="form-control" fileread="vm.topic" name="topic" placeholder="Image" required> <p ng-show="sliderForm.topic.$error.required && ( vm.formSubmitted || sliderForm.topic.$touched)" class="help-block">Image is required.</p> </div> </div> </div> <div class="box-footer"> <a ui-sref="app.slider" class="btn btn-default"><i class="fa <API key>"></i> Back</a> <button type="submit" class="btn btn-primary pull-right">Add New</button> </div> </form> </div> </div> </div> </section>
package com.south.openmrs.doctorsms; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Base64; import android.util.LruCache; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import java.security.SecureRandom; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.south.openmrs.doctorsms.NetworkService.NetworkBinder; public class ChatActivity extends AppCompatActivity { ArrayList<Item> postList; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private LruCache<String,Bitmap> mMemoryCache; private Context context; User mCurrentUser; ContactItem mRemoteContact; Intent serviceIntent; NetworkService mService; boolean mBound = false; GetMessagesTask getMsgTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.<API key>); getWindow().setSoftInputMode( WindowManager.LayoutParams.<API key>); SharedPreferences sharedPref = <API key>( getString(R.string.user_details_prefs), MODE_PRIVATE); String storedUserToken =sharedPref.getString(getString(R.string.stored_user_token),"0"); String storedUsername = sharedPref.getString(getString(R.string.stored_username),"0"); String userIdStr = sharedPref.getString(getString(R.string.stored_user_userid), "0"); String storedFirstName =sharedPref.getString(getString(R.string.<API key>), "0"); String storedLastname =sharedPref.getString(getString(R.string.<API key>), "0"); long userIdLong = Long.parseLong(userIdStr); mCurrentUser = new User(userIdLong,storedFirstName,storedLastname,storedUsername,storedUserToken); mRemoteContact = (ContactItem) getIntent().<API key>("ContactName"); postList = new ArrayList<Item>(); context =this; // get max available VM memory, exceeding this amount will throw // an OutOfMemory exception. Stored in kilobytes as LruCache takes an // int in its constructor final int maxMemory = (int) (Runtime.getRuntime().maxMemory()) / 1024; //use 1/8 of the available memory for this memory cache final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize){ @Override protected int sizeOf(String key, Bitmap bitmap){ // the cache size will be measured in kilobytes rather // than number of items return bitmap.getByteCount() / 1024; } }; ImageButton submitPostButton = (ImageButton) findViewById(R.id.chat_send_message); submitPostButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendMessage(); } }); init(null); serviceIntent = new Intent(this, NetworkService.class); serviceIntent.putExtra("senderid",mRemoteContact.getId()); startService(serviceIntent); bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE); Toolbar myToolbar = (Toolbar) findViewById(R.id.chat_toolbar); setSupportActionBar(myToolbar); } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.chat_menu, menu); return true; } @Override public boolean <API key>(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.<API key>: //showFriendDialog(); Toast.makeText(context,"Not implemented!",Toast.LENGTH_LONG).show(); return true; case R.id.chat_menu_logout: sendBroadcast(new Intent(NetworkService.LOG_OUT)); Intent intent = new Intent(this,LoginActivity.class); intent.setFlags(Intent.<API key>); startActivity(intent); return true; default: return super.<API key>(item); } } private void showFriendDialog(){ String myRsaPubKey = RSAKeyPair.getMyRSAPublicKey(context,mCurrentUser.getId(),mRemoteContact.getId()); String[] myDhKey = RSAKeyPair.getDHKey(context,mCurrentUser.getId(),mRemoteContact.getId()); String theirDHPubKey = RSAKeyPair.getDHPublicKey(context,mCurrentUser.getId(),mRemoteContact.getId()); String theirRSAPubKey = RSAKeyPair.getRSAPublicKey(context,mCurrentUser.getId(),mRemoteContact.getId()); byte[] mrsabytes = Base64.decode(myRsaPubKey,Base64.URL_SAFE); byte[] mdhbytes = Base64.decode(myDhKey[0],Base64.URL_SAFE); byte[] tdhkey = Base64.decode(theirDHPubKey,Base64.URL_SAFE); byte[] trsakey = Base64.decode(theirRSAPubKey,Base64.URL_SAFE); /* FriendInfoDialog(final Context context, ContactItem friend, User user, String friend_dhKey, String friend_rsaKey, String your_dhKey, String your_rsaKey){ super(context); */ FriendInfoDialog friendInfoDialog = new FriendInfoDialog(context, mRemoteContact, mCurrentUser, RSAKeyPair.fingerPrintFormat(tdhkey), RSAKeyPair.fingerPrintFormat(trsakey), RSAKeyPair.fingerPrintFormat(mrsabytes), RSAKeyPair.fingerPrintFormat(mdhbytes) ); friendInfoDialog.show(); } @Override protected void onPause() { Intent vIntent = new Intent(NetworkService.CHAT_VISIBILITY); vIntent.putExtra("sid",mRemoteContact.getId()); vIntent.putExtra("visibility",false); sendBroadcast(vIntent); this.unregisterReceiver(lreceiver); this.unregisterReceiver(lreceivers); unbindService(mConnection); super.onPause(); } private void init(View v) { mRecyclerView = (RecyclerView) findViewById(R.id.chat_recycler_view); //mRecyclerView.setHasFixedSize(true); // use a linear layout manager LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); linearLayoutManager.setStackFromEnd(true); //mLayoutManager = new LinearLayoutManager(context); mRecyclerView.setLayoutManager(linearLayoutManager); mAdapter = new MyAdapter(postList, context, mMemoryCache); mRecyclerView.setAdapter(mAdapter); getMsgTask = new GetMessagesTask(<API key>(),mRemoteContact.getId(),mCurrentUser.getId()){ @Override public void onPostExecute(Cursor result){ result.moveToPosition(-1); while(result.moveToNext()){ int sidPosition = result.<API key>(MessageBlockStore.FeedEntry.<API key>); int ridPosition = result.<API key>(MessageBlockStore.FeedEntry.COLUMN_NAME_REC); int timePosition = result.<API key>(MessageBlockStore.FeedEntry.<API key>); int msgPosition = result.<API key>(MessageBlockStore.FeedEntry.COLUMN_NAME_MESSAGE); String msg = result.getString(msgPosition); long sid = result.getLong(sidPosition); long rid = result.getLong(ridPosition); long time = result.getLong(timePosition); MessageBlock block = new MessageBlock(sid,rid,msg,time); MessageItem item = new MessageItem(mCurrentUser,mRemoteContact,block); postList.add(item); } mAdapter.<API key>(); mRecyclerView.scrollToPosition(postList.size()-1); } }; getMsgTask.execute(0L); } public void sendMessage() { //containerView // gets message from UI fields EditText editText = (EditText) findViewById(R.id.chat_edit_message); String message = editText.getText().toString(); // we create a new MessageItem // update the recycler view holding the messages etc.. sendMessageToScreen(message,editText); // And then <API key>(message); } @Override protected void onResume() { super.onResume(); //bindService(mConnection); registerReceiver(lreceiver, new IntentFilter(NetworkService.NEW_MESSAGE)); registerReceiver(lreceivers, new IntentFilter(NetworkService.NEW_MESSAGES)); Intent vIntent = new Intent(NetworkService.CHAT_VISIBILITY); vIntent.putExtra("sid",mRemoteContact.getId()); vIntent.putExtra("visibility",true); sendBroadcast(vIntent); } private void sendMessageToScreen(String message, EditText editText){ MessageBlock msgBlock = new MessageBlock(mCurrentUser.getId(),mRemoteContact.getId(),message, System.currentTimeMillis()); MessageItem post = new MessageItem(mCurrentUser,mRemoteContact,msgBlock); SharedPrefsHelper.<API key>(<API key>(),msgBlock); postList.add(post); mAdapter.<API key>(); mRecyclerView.scrollToPosition(postList.size()-1); editText.setText(""); } private void <API key>(MessageBlock msg){ long sid = msg.getSenderId(); if (sid == mRemoteContact.getId()){ MessageItem post = new MessageItem(mCurrentUser, mRemoteContact,msg); postList.add(post); mAdapter.<API key>(); mRecyclerView.scrollToPosition(postList.size()-1); } } private void <API key>(String message){ SharedPreferences sharedPref = <API key>( getString(R.string.user_details_prefs), MODE_PRIVATE); String serverUrl =sharedPref.getString(getString(R.string.stored_server_url), "http://localhost:8080"); String aes_key = RSAKeyPair.getAESKey(<API key>(),mCurrentUser.getId(), mRemoteContact.getId()); byte[] msgBytes = message.getBytes(); SecureRandom rand = new SecureRandom(); byte[] ivBytes = new byte[16]; rand.nextBytes(ivBytes); byte[] aesKeyBytes = Base64.decode(aes_key,Base64.URL_SAFE); String encMsg = "send error"; try { byte[] enc = RSAKeyPair.AESencrypt(message,aesKeyBytes,ivBytes); encMsg = Base64.encodeToString(enc,Base64.URL_SAFE); } catch (Exception e){ } String iv_str = Base64.encodeToString(ivBytes,Base64.URL_SAFE); List<NameValuePair> params = new LinkedList<NameValuePair>(); //example query: // sid=23948234& // rid=10920934& // msg=hello+world+lol& // auth=dontcare params.add(new NameValuePair("action","message")); params.add(new NameValuePair("sid",""+mCurrentUser.getId())); params.add(new NameValuePair("rid",""+mRemoteContact.getId())); params.add(new NameValuePair("msg",encMsg)); params.add(new NameValuePair("auth",mCurrentUser.getAuth())); params.add(new NameValuePair("iv",iv_str)); String urlResource = "/openmrsMessage/sendMessage"; HttpPost mPost = new HttpPost(this,serverUrl,urlResource){ @Override protected void onPostExecute(String response) { if (response != null) { Toast.makeText(parentContext,response,Toast.LENGTH_SHORT).show(); } } }; mPost.execute(params); } private BroadcastReceiver lreceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //System.out.println("Loginreciever caught "); Bundle bundle = intent.getExtras(); if (bundle != null) { //int subj = bundle.getInt(ActivityCodes.CODEPROTOCOL); MessageBlock msgBlock = (MessageBlock)bundle.getSerializable("message"); long sid = msgBlock.getSenderId(); //if (sid == mRemoteContact.getId()){ <API key>(msgBlock); }//bundle!=null } //overr. onReceive }; //new broadcast private BroadcastReceiver lreceivers = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //System.out.println("Loginreciever caught "); Bundle bundle = intent.getExtras(); if (bundle != null) { //int subj = bundle.getInt(ActivityCodes.CODEPROTOCOL); MessageStore msgStore = (MessageStore)bundle.getSerializable("messages"); //long sid = msgBlock.getSenderId(); //if (sid == mRemoteContact.getId()){ MessageBlock t = null; while( (t = msgStore.getAMessage() )!=null){ <API key>(t); } }//bundle!=null } //overr. onReceive }; //new broadcast /** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance NetworkBinder binder = (NetworkBinder) service; mService = binder.getService(); mBound = true; mService.connect(serviceIntent); } @Override public void <API key>(ComponentName arg0) { mBound = false; } }; }
<?php class Helpme extends Application { public function index() { $this->data['pagetitle'] = 'Help Wanted!'; $stuff = file_get_contents('../data/jobs.md'); $this->data['content'] = $this->parsedown->parse($stuff); $this->render(); } }
<?php namespace Iza\Moderare; use Countable; use JsonSerializable; //TODO add licence from laravel class MessageBag implements Countable, JsonSerializable { /** * All of the registered messages. * * @var array */ protected $messages = []; /** * Default format for message output. * * @var string */ protected $format = ':message'; /** * Create a new message bag instance. * * @param array $messages * @return void */ public function __construct(array $messages = []) { foreach ($messages as $key => $value) { $this->messages[$key] = (array)$value; } } /** * Get the keys present in the message bag. * * @return array */ public function keys() { return array_keys($this->messages); } /** * Add a message to the bag. * * @param string $key * @param string $message * @return $this */ public function add($key, $message) { if ($this->isUnique($key, $message)) { $this->messages[$key][] = $message; } return $this; } /** * Merge a new array of messages into the bag. * * @param array $messages * @return $this */ public function merge($messages) { $this->messages = <API key>($this->messages, $messages); return $this; } /** * Determine if a key and message combination already exists. * * @param string $key * @param string $message * @return bool */ protected function isUnique($key, $message) { $messages = (array)$this->messages; return !isset($messages[$key]) || !in_array($message, $messages[$key]); } /** * Determine if messages exist for a given key. * * @param string $key * @return bool */ public function has($key = null) { return $this->first($key) !== ''; } /** * Get the first message from the bag for a given key. * * @param string $key * @param string $format * @return string */ public function first($key = null, $format = null) { $messages = is_null($key) ? $this->all($format) : $this->get($key, $format); return count($messages) > 0 ? $messages[0] : ''; } /** * Get all of the messages from the bag for a given key. * * @param string $key * @param string $format * @return array */ public function get($key, $format = null) { // If the message exists in the container, we will transform it and return // the message. Otherwise, we'll return an empty array since the entire // methods is to return back an array of messages in the first place. if (array_key_exists($key, $this->messages)) { return $this->transform($this->messages[$key], $this->checkFormat($format), $key); } return []; } /** * Get all of the messages for every key in the bag. * * @param string $format * @return array */ public function all($format = null) { $format = $this->checkFormat($format); $all = []; foreach ($this->messages as $key => $messages) { $all = array_merge($all, $this->transform($messages, $format, $key)); } return $all; } /** * Format an array of messages. * * @param array $messages * @param string $format * @param string $messageKey * @return array */ protected function transform($messages, $format, $messageKey) { $messages = (array)$messages; // We will simply spin through the given messages and transform each one // replacing the :message place holder with the real message allowing // the messages to be easily formatted to each developer's desires. $replace = [':message', ':key']; foreach ($messages as &$message) { $message = str_replace($replace, [$message, $messageKey], $format); } return $messages; } /** * Get the appropriate format based on the given format. * * @param string $format * @return string */ protected function checkFormat($format) { return $format ?: $this->format; } /** * Get the raw messages in the container. * * @return array */ public function getMessages() { return $this->messages; } /** * Get the default message format. * * @return string */ public function getFormat() { return $this->format; } /** * Set the default message format. * * @param string $format * @return \Illuminate\Support\MessageBag */ public function setFormat($format = ':message') { $this->format = $format; return $this; } /** * Determine if the message bag has any messages. * * @return bool */ public function isEmpty() { return !$this->any(); } /** * Determine if the message bag has any messages. * * @return bool */ public function any() { return $this->count() > 0; } /** * Get the number of messages in the container. * * @return int */ public function count() { return count($this->messages, COUNT_RECURSIVE) - count($this->messages); } /** * Get the instance as an array. * * @return array */ public function toArray() { return $this->getMessages(); } /** * Convert the object into something JSON serializable. * * @return array */ public function jsonSerialize() { return $this->toArray(); } /** * Convert the object to its JSON representation. * * @param int $options * @return string */ public function toJson($options = 0) { return json_encode($this->toArray(), $options); } /** * Convert the message bag to its string representation. * * @return string */ public function __toString() { return $this->toJson(); } }
'use strict'; const Mongoose = require('mongoose'); const Schema = Mongoose.Schema; module.exports = function (N, collectionName) { let Ignore = new Schema({ // user who is ignoring messages from: Schema.Types.ObjectId, // user whose messages are ignored to: Schema.Types.ObjectId, // reason for ignore (optional) reason: String, // creation date ts: { type: Date, default: Date.now }, // expiration date expire: Date }, { versionKey: false }); // Indexes // check if a user ignores another user Ignore.index({ from: 1, to: 1 }); // clean up expired ignores Ignore.index({ expire: 1 }); N.wire.on('init:models', function emit_init_Ignore() { return N.wire.emit('init:models.' + collectionName, Ignore); }); N.wire.on('init:models.' + collectionName, function init_model_Ignore(schema) { N.models[collectionName] = Mongoose.model(collectionName, schema); }); };
title: IT Lesson 41 - A new term... layout: post author: brendan.frank permalink: /<API key>.../ source-id: <API key> published: true <table> <tr> <td>Title</td> <td>IT Lesson 41</td> <td>Date</td> <td>18/05/2017</td> </tr> </table> <table> <tr> <td>Starting point:</td> <td>19% completed</td> </tr> <tr> <td>Target for this lesson?</td> <td>Finish an additional 5%</td> </tr> <tr> <td>Did I reach my target? </td> <td>Yes, I finished up to 24%</td> </tr> </table> <table> <tr> <td>Lesson Review</td> </tr> <tr> <td>How did I learn? What strategies were effective? </td> </tr> <tr> <td>I learned by exploring what I could do but also trying to find the simplest ways to perform the action that I was instructed to do.</td> </tr> <tr> <td>What limited my learning? Which habits do I need to work on? </td> </tr> <tr> <td>Not much limited my learning as I 'put my head down' and focused on what I needed to do. Sometimes I asked my partner for help but he guided me towards finding out the answer to my problem instead of just telling me the answer to it.</td> </tr> <tr> <td>What will I change for next time? How will I improve my learning?</td> </tr> <tr> <td>Next time I will try to finish even more and try to retain the knowledge that I have learned!</td> </tr> </table>
Stats helper to show on screen framerate, memory occupation, ecc. Displayed infos are: Fps - DrawCalls - Total Memory (lua memory, texture memory) Stats = class(DisplayObjContainer) local extended_stats = false function Stats:init() DisplayObjContainer.init(self) local width = extended_stats and 320 or 300 local height = extended_stats and 40 or 20 local background = Quad(width,height) background:setColor(Color(0,0,0)) self:addChild(background) self.info_stats = TextField(width,height, "") self.info_stats:setAlignment(MOAITextBox.CENTER_JUSTIFY) self:addChild(self.info_stats) end Updates with the last frame informations function Stats:update() local fps = math.floor(MOAISim.getPerformance()) local usage = MOAISim.getMemoryUsage("M") --minus 1, the cost of drawing Stats object itself local drawcalls = MOAIRenderMgr.<API key>() - 1 if extended_stats then self.info_stats:setText(string.format("%d - %d - %.3f (%.3f, %.3f)\n%.3f, %.3f", fps, drawcalls, usage.total, usage.lua, usage.texture, usage._sys_rss, usage._sys_vs)) else self.info_stats:setText(string.format("%d - %d - %.3f (%.3f, %.3f)", fps, drawcalls, usage.total, usage.lua, usage.texture)) end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta content="Craig McClellan" name="author"> <title>Craig McClellan - T223427465937293313 </title> <link href="/assets/css/style.css" rel="stylesheet"> <link href="/assets/css/highlight.css" rel="stylesheet"> <link rel="stylesheet" href="/custom.css"> <link rel="shortcut icon" href="https://micro.blog/craigmcclellan/favicon.png" type="image/x-icon" /> <link rel="alternate" type="application/rss+xml" title="Craig McClellan" href="http://craigmcclellan.com/feed.xml" /> <link rel="alternate" type="application/json" title="Craig McClellan" href="http://craigmcclellan.com/feed.json" /> <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" /> <link rel="me" href="https://micro.blog/craigmcclellan" /> <link rel="me" href="https://twitter.com/craigmcclellan" /> <link rel="me" href="https://github.com/craigwmcclellan" /> <link rel="<API key> href="https://micro.blog/indieauth/auth" /> <link rel="token_endpoint" href="https://micro.blog/indieauth/token" /> <link rel="micropub" href="https://micro.blog/micropub" /> <link rel="webmention" href="https://micro.blog/webmention" /> <link rel="subscribe" href="https://micro.blog/users/follow" /> </head> <body> <nav class="main-nav"> <a class="normal" href="/"> <span class="arrow">←</span> Home</a> <a href="/archive/">Archive</a> <a href="/about/">About</a> <a href="/tools-of-choice/">Tools of Choice</a> <a class="cta" href="https://micro.blog/craigmcclellan" rel="me">Also on Micro.blog</a> </nav> <section id="wrapper"> <article class="h-entry post"> <header> <h2 class="headline"> <time class="dt-published" datetime="2012-07-12 09:43:53 -0500"> <a class="u-url dates" href="/2012/07/12/t223427465937293313.html">July 12, 2012</a> </time> </h2> </header> <section class="e-content post-body"> <p>“@thebwack: BTW, the plural of “y’all” is “all y’all”” Correct!</p> </section> </article> <section id="post-meta" class="clearfix"> <a href="/"> <img class="u-photo avatar" src="https://micro.blog/craigmcclellan/avatar.jpg"> <div> <span class="p-author h-card dark">Craig McClellan</span> <span><a href="https://micro.blog/craigmcclellan">@craigmcclellan</a></span> </div> </a> </section> </section> <footer id="footer"> <section id="wrapper"> <ul> <li><a href="/feed.xml">RSS</a></li> <li><a href="/feed.json">JSON Feed</a></li> <li><a href="https://micro.blog/craigmcclellan" rel="me">Micro.blog</a></li> <!-- <li><a class="u-email" href="mailto:" rel="me">Email</a></li> --> </ul> <form method="get" id="search" action="https://duckduckgo.com/"> <input type="hidden" name="sites" value="http://craigmcclellan.com"/> <input type="hidden" name="k8" value="#444444"/> <input type="hidden" name="k9" value="#ee4792"/> <input type="hidden" name="kt" value="h"/> <input class="field" type="text" name="q" maxlength="255" placeholder="To search, type and hit Enter&hellip;"/> <input type="submit" value="Search" style="display: none;" /> </form> </section> </footer> </body> </html>
#pragma once HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow); HRESULT InitDevice(); void CleanupDevice(); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void LoadContent(); void Update(float totalTime, float deltaTime); void Render(float totalTime, float deltaTime);
# <API key>: true RSpec.describe Svgeez::Commands::Watch, '.init_with_program' do let(:program) { Mercenary::Program.new(:svgeez) } let(:command) { described_class.init_with_program(program) } it 'sets a description' do expect(command.description).to eq('Watches a folder of SVG icons for changes') end it 'sets a syntax' do expect(command.syntax).to eq('svgeez watch [options]') end end
Copyright (c) G. Nicolas Arroyo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<!doctype html> <html lang="ru"> <head> <title>мойЧат</title> <meta charset="UTF-8"> <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script> <script defer src="app.js"></script> </head> <body> <div class='chat_main'></div> <script> 'use strict'; let elem = document.querySelector(".chat_main"); let CHAT_OPTIONS = { elem : elem } </script> </body> </html>
# Multiple constructors in Processing / Java # A class can have multiple constructors that assign the fields in different ways. # Sometimes it's beneficial to specify every aspect of an object's data by assigning # parameters to the fields, but other times it might be appropriate to define only # one or a few. # fjenett, 2010-03-13: # Ruby constructors are called "initialize" no matter what the name of the class is. # In Ruby you can not have multiple methods with the same name although they have different # parameters. In fact the last definition of a method will override all previous ones. # But there are two ways to define methods with variable parameters. One is to give the # parameters a default value, the second is to use the catch-all asterix: # def my_method1 ( a, b = "2" ) # can be called with one or two arguments # end # def my_method2 ( *args ) # can be called with any number of arguments, args is an array # end # Martin Prout, 2014-06-23: # even more flexibility can be had by passing a hash see inheritance_two @todo update for ruby-2.1+ def setup size 640, 360 background 204 smooth(8) no_loop sp1 = Spot.new sp2 = Spot.new width*0.5, height*0.5, 120 sp1.display sp2.display end def draw end # vvv CLASS SPOT class Spot attr_accessor :x, :y, :radius def initialize (x = 160, y = 180, r = 40) # can be called with 0 to 3 arguments @x, @y, @radius = x, y, r end def display ellipse @x, @y, @radius*2, @radius*2 end end # ^^^ CLASS SPOT
# <API key> * Works on linux, as master and slave. * Master, one process is listening on pipe and draws points. * Slave, many slave can be started at once, calculates points. ![example](https://cloud.githubusercontent.com/assets/6627307/24832557/<API key>.png)
<?php $file = "/home/pi/BlueTrack/my_macs.txt"; $f = file_get_contents($file); $my_macs = json_decode($f, true); $total = 0; foreach ($my_macs as $addr => $v) { $total++; unset($t); echo "$addr \tname: \e[0;35m" . str_pad(@$v['name'],32," ") . " \e[0mclock offset: " . str_pad(@$v['clock offset'],10," ") . " class: " . @$v['class'] . "\n"; echo "\t\t\tscanned: " . str_pad(@$v['scan_count'],29," ") . " inquired: " . @$v['inq_count'] . "\n"; if (strpos(strtolower(@$v['name']), 'conine') === false) { if (isset($v['scan_on'])) { foreach ($v['scan_on'] as $tm => $v) { @@$t[date("Y-m-d h:i a", $tm - 14400)]++; } } if (isset($v['inq_on'])) { foreach ($v['inq_on'] as $tm => $v) { @@$t[date("Y-m-d h:i a", $tm - 14400)]++; } } echo "\t\t\tseen on:\n"; if (isset($t)) { foreach ($t as $time => $cnt) { echo "\t\t\t\t$time\n"; } } } echo "\n"; } echo "Total Unique Devices: \e[1;33m $total \e[0m \n"; ?>
// class to create singing character // requires THREE.js // requires commands.js var Singer = {}; // constructor Singer.Character = function () { this.body; this.eyes; this.head; this.mouth; this.loaded = false; this.mouth_shapes = {}; this.talking_keys = ['ooo', 'aaa', 'mmm', 'eee']; this.scene_object = new THREE.Object3D(); this.character_root = new THREE.Object3D(); this.speech_bubbles_root = new THREE.Object3D(); this.character_head = new THREE.Object3D(); this.character_eyes = new THREE.Object3D(); this.character_mouth = new THREE.Object3D(); this.scene_object.add(this.character_root); this.scene_object.add(this.speech_bubbles_root); this.character_root.add(this.character_head); this.character_head.add(this.character_eyes); this.character_head.add(this.character_mouth); this.material_white = new THREE.MeshLambertMaterial(); this.material_black = new THREE.MeshBasicMaterial(); this.gaze_target = [0,0,0]; this.gaze_point = [0,0,0]; this.character_head.lookAt(new THREE.Vector3(this.gaze_point[0], this.gaze_point[1], this.gaze_point[2])); // notes // this.notes = []; // this.note_phase = 0 // for (var i = 0; i < 10; i++) // var note = new Singer.Note(); // this.notes.push(note); // this.speech_bubbles_root.add(note.scene_object); // demo keys this.demo_objects = { 'A' : new Singer.DemoBubble('A'), 'S' : new Singer.DemoBubble('S'), 'D' : new Singer.DemoBubble('D'), 'F' : new Singer.DemoBubble('F'), 'G' : new Singer.DemoBubble('G'), 'H' : new Singer.DemoBubble('H'), 'J' : new Singer.DemoBubble('J'), 'K' : new Singer.DemoBubble('K'), 'L' : new Singer.DemoBubble('L') } this.demo_objects_keys = Object.keys(this.demo_objects); for (var i = 0; i < this.demo_objects_keys.length; i++) { this.speech_bubbles_root.add(this.demo_objects[this.demo_objects_keys[i]].scene_object); } // position objects this.character_root.position.x = 130; this.character_root.position.y = -15; this.character_root.rotation.y = Utils.toRadians(-45); this.character_eyes.position.y = 60; this.speech_bubbles_root.position.x = 60; // character state this.blinking = 1; // 0=closed, 1=open } // load method Singer.Character.prototype.load = function (on_load_callback) { obj_url_array = [ 'obj/body.obj', 'obj/eyes.obj', 'obj/head.obj', 'obj/smile.obj', 'obj/ooo.obj', 'obj/aaa.obj', 'obj/mmm.obj', 'obj/eee.obj', ]; // on load var dummy_this = this; // hack to let you use this. inside a callback Utils.loadObjs(obj_url_array, function (obj_list) { dummy_this.body = obj_list[0]; dummy_this.eyes = obj_list[1]; dummy_this.head = obj_list[2]; dummy_this.mouth = obj_list[3]; dummy_this.mouth_shapes['smile'] = obj_list[3].geometry.vertices; dummy_this.mouth_shapes['ooo'] = obj_list[4].geometry.vertices; dummy_this.mouth_shapes['aaa'] = obj_list[5].geometry.vertices; dummy_this.mouth_shapes['mmm'] = obj_list[6].geometry.vertices; dummy_this.mouth_shapes['eee'] = obj_list[7].geometry.vertices; dummy_this.character_root.add(dummy_this.body); dummy_this.character_eyes.add(dummy_this.eyes); dummy_this.character_head.add(dummy_this.head); dummy_this.character_head.add(dummy_this.mouth); dummy_this.loaded = true; dummy_this.setup(); on_load_callback(); }.bind(dummy_this)); } // setup method - called after objs load Singer.Character.prototype.setup = function () { this.material_black.color = 0x000000; this.mouth.material = this.material_black; this.eyes.material = this.material_black; }; // sing/talk Singer.Character.prototype.sing = function (shape) { if (shape == undefined) { shape = this.randomMouthShape() } this.mouth.geometry.vertices = this.mouth_shapes[shape]; this.mouth.geometry.verticesNeedUpdate = true; if (this.note_phase == 9) {this.note_phase = 0;} else {this.note_phase ++;} this.notes[this.note_phase].reset(); } Singer.Character.prototype.talk = function (shape) { if (shape == undefined) { shape = this.randomMouthShape() } this.mouth.geometry.vertices = this.mouth_shapes[shape]; this.mouth.geometry.verticesNeedUpdate = true; } Singer.Character.prototype.randomMouthShape = function() { return this.talking_keys[Math.floor(Math.random()*this.talking_keys.length)]; } // demo Singer.Character.prototype.demoKey = function (key) { this.demo_objects[key].reset(); } // update method Singer.Character.prototype.update = function (tick) { // blinking if (Math.random() > 0.992) { this.blinking = 0.01; } if (this.blinking < 1) { this.blinking *= 2; this.character_eyes.scale.y = this.blinking; } // random gaze if (Math.random() > 0.99) { this.gaze_target = [Math.random() * 0.5, Math.random() * 0.5, 5]; if (Math.random() > 0.4) { this.blinking = 0.01; } } // head rotation this.gaze_point = [((this.gaze_point[0] * 5) + this.gaze_target[0]) / 6, ((this.gaze_point[1] * 5) + this.gaze_target[1]) / 6, ((this.gaze_point[2] * 5) + this.gaze_target[2]) / 6] this.character_head.lookAt(new THREE.Vector3(this.gaze_point[0], this.gaze_point[1], this.gaze_point[2])) // // notes // for (var i = 0; i < this.notes.length; i++) // this.notes[i].update(); for (var i = 0; i < this.demo_objects_keys.length; i++) { var key = this.demo_objects_keys[i]; this.demo_objects[key].updateWrapper(); } }; // SpeachBubble // class for notes and demo keys do derive from Singer.SpeachBubble = function () { this.scene_object = new THREE.Object3D(); this.scene_object.position.y = 200; // set nice and far out of view to start this.velocity = [0,0,0]; this.target_velocity = [0,0,0]; this.accelaration_factor = 0.06; } Singer.SpeachBubble.reset = function () { this.velocity = [ -2 - (Math.random() * 2), (Math.random() - 0.5) * 1, 0 ]; this.target_velocity = [ 0, 2 + (Math.random() * 1), 0 ]; this.scene_object.position.x = 0; this.scene_object.position.y = 0; this.scene_object.position.z = 0; this.scene_object.rotation.z += Utils.toRadians(Math.random() * -70); } Singer.SpeachBubble.updateWrapper = function () { // move for (var i = 0; i < 3; i++) { this.velocity[i] = (this.velocity[i] * (1-this.accelaration_factor)) + (this.target_velocity[i] * this.accelaration_factor); } this.scene_object.rotation.z = (this.scene_object.rotation.z * (1-this.accelaration_factor)); this.scene_object.position.add( new THREE.Vector3 ( this.velocity[0], this.velocity[1], this.velocity[2] )); this.update(); } // DemoBubble Singer.DemoBubble = function (letter){ Singer.SpeachBubble.call(this); this.char_object = new LineText.Character(letter, {color : 0xffdddd, cycle_color : true, sparkle : true, key_outline : true}); this.scene_object.scale.set(20,20,20); this.scene_object.add(this.char_object.scene_object); this.char_object.show(); } Singer.DemoBubble.prototype = Object.create(Singer.SpeachBubble); Singer.DemoBubble.prototype.constructor = Singer.DemoBubble; Singer.DemoBubble.prototype.update = function () { this.char_object.update(); }
<?php /* Safe sample input : get the field UserData from the variable $_POST sanitize : cast into int construction : concatenation */ $tainted = $_POST['UserData']; $tainted = (int) $tainted ; $query = "SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name, a.city, a.street & (' ' +a.housenum) AS address FROM Employees AS a WHERE a.supervisor=". $tainted . ""; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
import { <API key> } from '../models/index'; export interface <API key> { isDisabled: boolean; minDate: Date; maxDate: Date; hoveredYear: Date; displayMonths: number; yearIndex: number; } export declare function flagYearsCalendar(yearsCalendar: <API key>, options: <API key>): <API key>;
import os import abc untyped_list = [] def high_complexity (arg): """High cyclomatic complexity.""" if arg == 0: print(0) elif arg == 1: print(1) elif arg == 2: print(2) elif arg == 3: print(3) elif arg == 4: print(4) elif arg == 5: print(5) elif arg == 6: print(6) elif arg == 7: print(7) elif arg == 8: print(8) elif arg == 9: print(9) elif arg == 10: print(10) elif arg == 11: print(11) elif arg == 12: print(12) elif arg == 13: print(13) elif arg == 14: print(14) elif arg == 15: print(15) elif arg == 16: print(16) elif arg == 17: print(17) elif arg == 18: print(18) elif arg == 19: print(19)
<?php /** * Template Name: New Blog * * @package WordPress * @subpackage Twenty_Fourteen * @since Twenty Fourteen 1.0 */ get_header(); ?> <section id="innrbox"> <div class="row"> <div class="col-lg-12"> <h1 style="margin:10px 0px;"><?php the_title(); ?></h1> <ol class="breadcrumb"> <?php if (function_exists('bcn_display')) { bcn_display(); } ?> </ol> </div> </div> <div class="row"> <br/> <div class="col-lg-12"> <?php while (have_posts()): the_post(); the_content(); endwhile; ?> </div> </div> <div class="row"> <center> <span class="nav-previous"><?php previous_post_link('%link', '<span class="meta-nav">' . _x('&larr;', 'Previous post link', 'planningelegance') . '</span> %title'); ?></span> <span class="nav-next"><?php next_post_link('%link', '%title <span class="meta-nav">' . _x('&rarr;', 'Next post link', 'planningelegance') . '</span>'); ?></span> </center> </div> <div class="subscrbBX hide"><?php dynamic_sidebar('subscribenow'); ?></div> </section> <?php get_footer(); ?>
package org.kj6682.hop; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(SpringRunner.class) @ActiveProfiles({"postgresql", "create"}) public class HopEntityTest { public static final String ON_TITLE = "A reasonable title is necessary when creating a Hop"; public static final String ON_AUTHOR = "A Hop needs an author"; public static final String ON_TYPE = " strict type is necessary when creating a Hop"; public static final String ON_LOCATION = "A Hop is needless without a location"; @Rule public ExpectedException thrown = ExpectedException.none(); // @Autowired // private TestEntityManager entityManager; @Test public void <API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage(ON_TITLE); new Hop(null, "author", "type", "location"); } @Test public void <API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage(ON_TITLE); new Hop("", "author", "type", "location"); } @Test public void given<API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage(ON_AUTHOR); new Hop("title", null, "type", "location"); } @Test public void given<API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage(ON_AUTHOR); new Hop("title", "", "type", "location"); } @Test public void <API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage("A" + ON_TYPE); new Hop("title", "author", null, "location"); } @Test public void <API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage("A" + ON_TYPE); new Hop("title", "author", "", "location"); } @Test public void <API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage(ON_LOCATION); new Hop("title", "author", "type", null); } @Test public void <API key>() throws Exception { this.thrown.expect(<API key>.class); this.thrown.expectMessage(ON_LOCATION); new Hop("title", "author", "type", ""); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Extension; using Extension.Badge; using MongoDB.Bson; using SVNExtension.Model; namespace SVNExtension.Badges { public class <API key> : IBadge { public ObjectId id { get; private set; } public BadgeLevel Level { get; private set; } public string Content { get; private set; } public string IconPath { get; private set; } public string Name { get; private set; } public string ExtensionName { get; private set; } public bool Secret { get; private set; } public bool Gained { get; private set; } public <API key>() { ExtensionName = "SVN"; Level = BadgeLevel.corundum; Content = GetContent(); IconPath = ".\\res\\Badges\\SVN\\weekend_integration.png"; Name = "Continuous Integration!"; Secret = false; Gained = false; } public string GetContent() { var content = "Commit five days consecutives."; return content; } public void Compute(IUser user) { var infos = new DatabaseAccess.DatabaseManager() .GetDatabase() .GetCollection<SVNInfo>(typeof(SVNInfo).Name) .FindAll() .OrderBy(o => o.Date) .ToList(); var count = 0; DateTime initialTime = infos[0].Date.ToUniversalTime(); for (int i = 1; i < infos.Count; i++) { var ts = infos[i + 1].Date - initialTime; if (ts.Days >= 1 && ts.Days < 2) { count++; } else if (!(ts.Days < 1)) { count = 0; } else { continue; } initialTime = infos[i].Date; if (count >= 5) { Gained = true; break; } } } } }
# Jquery Gallery extension for Refinery CMS. This extension uses the jquery Gallery View plugin to render a set of images in refinerycms. This gallery works well with the <API key> extension, but it does not automatically display a gallery of page images. Installing this extension basically does nothing at all unless you load the _gallery.html.haml template. This template must be given a local "page" object, but actually this doesn't have to be a Refinery::Page, it could be anything that supports a method called "images" that returns an array of image objects which in turn can supply a url via "image.thumbnail("570x270#c").url". If you wish to do this with all pages, simply add a call to this _gallery partial in your _content_page partial: erb <%= render 'refinery/jquery_gallery/gallery', :page => @page %> ## Installation Simply install the gem. There is no generator or migrations. Add the javascript to your application.js javascript //= require <API key> You probably want to add a reference to the stylesheet "<API key>" in your application.css. ## How to build this extension as a gem gem build <API key>.gemspec gem push <API key>.gem ## Licence This code us available under the MIT licence. See attached licence file for full details. ## Credits Craig Ambrose http://github.com/craigambrose
/* n1 * Solutionoffer */ class Solution { public: int countDigitOne(int n) { } };
class Hadupils::SearchTest < Test::Unit::TestCase tempdir_context 'find_from_dir' do setup do @module = Hadupils::Search @search_name = mock().to_s end should 'return nil if requested directory cannot be found' do assert_equal nil, @module.find_from_dir(@search_name, @tempdir.path) end should 'should find the directory when it is in the start dir' do p = @tempdir.full_path('blah') Dir.mkdir p assert_equal p, @module.find_from_dir('blah', @tempdir.path) end should 'find the directory when it is in a sibling of the start dir' do target = @tempdir.full_path('target-dir') start = @tempdir.full_path('start-dir') [target, start].each {|d| Dir.mkdir(d) } assert_equal target, @module.find_from_dir('target-dir', start) end should 'find the directory when it is above the start dir' do d = @tempdir.full_path('flickityflu') Dir.mkdir(d) assert_equal @tempdir.path, @module.find_from_dir(File.basename(@tempdir.path), d) end end context 'find_from_pwd' do setup do @module = Hadupils::Search @pwd = ::Dir.pwd @target = mock() end should 'return the path found by find_from_dir for the pwd' do @module.expects(:find_from_dir).with(@target, @pwd).returns(result = mock()) assert_equal result, @module.find_from_pwd(@target) end should 'return nil when given that by find_from_dir for the pwd' do @module.expects(:find_from_dir).with(@target, @pwd).returns(nil) assert_equal nil, @module.find_from_pwd(@target) end end context 'user_config' do setup do @module = Hadupils::Search end should 'use ~/conf by default' do assert_equal ::File.expand_path(::File.join('~', 'conf')), @module.user_config end should 'be settable' do assert_equal true, @module.respond_to?(:user_config=) end end context 'hadoop_assets' do should 'search for directory specified by #hadoop_assets_name' do Hadupils::Search.expects(:hadoop_assets_name).with.returns(name = mock().to_s) Hadupils::Search.expects(:find_from_pwd).with(name).returns(dir = mock()) assert_equal dir, Hadupils::Search.hadoop_assets end end context 'hadoop_assets_name' do should 'default to "hadoop-ext"' do assert_equal 'hadoop-ext', Hadupils::Search.hadoop_assets_name end should 'be settable' do assert_respond_to Hadupils::Search, :hadoop_assets_name= end end context 'hive_extensions' do should 'search for a directory specified by #<API key>' do Hadupils::Search.expects(:<API key>).with.returns(name = mock.to_s) Hadupils::Search.expects(:find_from_pwd).with(name).returns(dir = mock) assert_equal dir, Hadupils::Search.hive_extensions end end context '<API key>' do should 'default to "hive-ext"' do assert_equal 'hive-ext', Hadupils::Search.<API key> end should 'be settable' do assert_respond_to Hadupils::Search, :<API key>= end end end
<?php namespace FSS\Controllers; /** * Generated by <API key> on 2017-12-31 at 20:36:32. */ class <API key> extends \PHPUnit\Framework\TestCase { /** * @var <API key> */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new <API key>; } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @covers FSS\Controllers\<API key>::read * @todo Implement testRead(). */ public function testRead() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers FSS\Controllers\<API key>::readAll * @todo Implement testReadAll(). */ public function testReadAll() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers FSS\Controllers\<API key>::readAllWithFilter * @todo Implement <API key>(). */ public function <API key>() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers FSS\Controllers\<API key>::create * @todo Implement testCreate(). */ public function testCreate() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers FSS\Controllers\<API key>::update * @todo Implement testUpdate(). */ public function testUpdate() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers FSS\Controllers\<API key>::delete * @todo Implement testDelete(). */ public function testDelete() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } }
import { GraphQLObjectType, GraphQLSchema, GraphQLString } from 'graphql'; import { WeavingConfig } from '../../../src/config/weaving-config'; export async function getConfig(): Promise<WeavingConfig> { const linkTargetType = new GraphQLObjectType({ name: 'OpNameObject', fields: { opName: { type: GraphQLString, resolve: (source, args, context, info) => info.operation.name ? info.operation.name.value : null }, } }); return { endpoints: [ { schema: new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { opName: { type: GraphQLString, resolve: (source, args, context, info) => info.operation.name ? info.operation.name.value : null }, linkTarget: { type: linkTargetType, args: { // just to please link module id: { type: GraphQLString } }, resolve: () => ({}) }, link: { type: GraphQLString, resolve: () => 'dummy' } } }) }), fieldMetadata: { 'Query.link': { link: { field: 'linkTarget', argument: 'id', batchMode: false } } } } ] }; }
@echo off REM standard mingw development environment! REM can be copied to any directory to start a console REM REM CHECK FOR MINGW INSTALLATION! REM set MINGW_APPSNAME=MinGW set MINGW_USERPATH=%APPDATA%\%MINGW_APPSNAME% set MINGW_PATHFILE=%MINGW_USERPATH%\mingw.path if exist "%MINGW_PATHFILE%" goto FIND_PATH echo Missing %MINGW_PATHFILE%! echo Aborting! pause goto END :FIND_PATH set /p mingw=<"%MINGW_PATHFILE%" set mingw=%mingw:~0,-1% if exist "%mingw%" goto MINGW_OK echo Cannot find MinGW folder! pause goto END REM REM SET MINGW ENVIRONMENT! REM :MINGW_OK set mingw_path=%mingw%\bin;%mingw%\mingw32\bin;%mingw%\tools set path=%mingw_path%;%path% REM REM CHECK GETPATH OPTION! REM if defined MINGWTERM_GETPATH goto END REM REM START MINGW CONSOLE! REM :START_CONSOLE start "MinGW Console" /max /normal cmd :END REM REM CLEANUP ENV VARIABLES! REM set MINGW_APPSNAME= set MINGW_USERPATH= set MINGW_PATHFILE=
import {IClone} from "../clone.interface"; export interface IClones { saveClone(clone: IClone); get(): IClone[]; }
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { increment, decrement } from '../../logic/actions/'; const About = ({ count, onIncrement, onDecrement }) => { return ( <div> Counter <div> <dl className="counter-display"> <dd>Count:</dd> <dt>{count}</dt> </dl> <button className="btn decrement" onClick={onDecrement}> &#8722; </button> <button className="btn increment" onClick={onIncrement}> & </button> </div> </div> ); }; export const mapStateToProps = (state) => { return { count: state.count, }; }; export const mapDispatchToProps = (dispatch) => { return { onIncrement: () => dispatch(increment()), onDecrement: () => dispatch(decrement()), }; }; About.propTypes = { count: PropTypes.number, onIncrement: PropTypes.func, onDecrement: PropTypes.func, }; export default connect( mapStateToProps, mapDispatchToProps )(About);
create or alter procedure scheduler.ExecuteTask @taskId int = null ,@identifier nvarchar(128) = null as begin set xact_abort on; set nocount on; if (@taskId is null and @identifier is null) or (@taskId is not null and @identifier is not null) begin ;throw 50000, 'Only one of @taskId or @identifier must be specified', 1; end if @taskId is null begin select @taskId = t.TaskId from scheduler.Task as t where t.Identifier = @identifier; end if not exists ( select 1 from scheduler.Task as t where t.TaskId = @taskId ) begin ;throw 50000, 'Specified Task does not exist', 1; end declare @executionId int ,@startDateTime datetime2 (3) = getutcdate() ,@monthOfYear tinyint ,@command nvarchar(max) ,@isEnabled bit ,@isNotifyOnFailure bit; set @monthOfYear = cast(month(@startDateTime) as tinyint) select @command = t.TSQLCommand ,@isEnabled = t.IsEnabled ,@isNotifyOnFailure = t.IsNotifyOnFailure ,@identifier = t.Identifier from scheduler.Task as t where t.TaskId = @taskId; /* Run the task only if it is enabled */ if @isEnabled = 0 begin return; end insert into scheduler.TaskExecution ( TaskId, StartDateTime ) values ( @taskId, @startDateTime ); select @executionId = scope_identity(); declare @errorNumber int ,@resultMessage nvarchar(max) ,@isError bit = 0 ,@id uniqueidentifier; select @id = i.Id from scheduler.GetInstanceId() as i; exec scheduler.SetContextInfo @instanceIdentifier = @id ,@taskId = @taskId ,@executionId = @executionId; begin try exec sp_executesql @command; end try begin catch set @isError = 1; set @errorNumber = error_number(); set @resultMessage = cast(@errorNumber as varchar(10)) + ' - ' + error_message(); if xact_state() in (-1,1) begin rollback transaction; end end catch update scheduler.TaskExecution set IsError = @isError ,ResultMessage = @resultMessage ,EndDateTime = getutcdate() where ExecutionId = @executionId and MonthOfYear = @monthOfYear; /* Throw here to allow agent to message the failure operator */ if @isError = 1 and @isNotifyOnFailure = 1 begin ;throw 50000, @resultMessage, 1; end end go
< .SYNOPSIS This is a Powershell script to bootstrap a Cake build. .DESCRIPTION This Powershell script will download NuGet if missing, restore NuGet tools (including Cake) and execute your Cake build script with the parameters you provide. .PARAMETER Script The build script to execute. .PARAMETER Target The build script target to run. .PARAMETER Configuration The build configuration to use. .PARAMETER Verbosity Specifies the amount of information to be displayed. .PARAMETER Experimental Tells Cake to use the latest Roslyn release. .PARAMETER WhatIf Performs a dry run of the build script. No tasks will be executed. .PARAMETER Mono Tells Cake to use the Mono scripting engine. .LINK http://cakebuild.net Param( [string]$Script = "build.cake", [string]$Target = "Default", [string]$Configuration = "Release", [ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")] [string]$Verbosity = "Verbose", [switch]$Experimental, [Alias("DryRun","Noop")] [switch]$WhatIf, [switch]$Mono, [switch]$<API key>, [switch]$Verbose ) Write-Host "Preparing to run build script..." # Should we show verbose messages? if($Verbose.IsPresent) { $VerbosePreference = "continue" } $TOOLS_DIR = Join-Path $PSScriptRoot "tools" $NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe" $CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe" $PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config" # Should we use mono? $UseMono = ""; if($Mono.IsPresent) { Write-Verbose -Message "Using the Mono based scripting engine." $UseMono = "-mono" } # Should we use the new Roslyn? $UseExperimental = ""; if($Experimental.IsPresent -and !($Mono.IsPresent)) { Write-Verbose -Message "Using experimental version of Roslyn." $UseExperimental = "-experimental" } # Is this a dry run? $UseDryRun = ""; if($WhatIf.IsPresent) { $UseDryRun = "-dryrun" } # Make sure tools folder exists if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) { Write-Verbose -Message "Creating tools directory..." New-Item -Path $TOOLS_DIR -Type directory | out-null } # Make sure that packages.config exist. if (!(Test-Path $PACKAGES_CONFIG)) { Write-Verbose -Message "Downloading packages.config..." try { Invoke-WebRequest -Uri http://cakebuild.net/bootstrapper/packages -OutFile $PACKAGES_CONFIG } catch { Throw "Could not download packages.config." } } # Try find NuGet.exe in path if not exists #if (!(Test-Path $NUGET_EXE)) { # Write-Verbose -Message "Trying to find nuget.exe in path..." # ($NUGET_EXE_IN_PATH = &where.exe nuget.exe) | out-null # if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH)) { # "Found $($NUGET_EXE_IN_PATH)." # $NUGET_EXE = $NUGET_EXE_IN_PATH # Try download NuGet.exe if not exists if (!(Test-Path $NUGET_EXE)) { Write-Verbose -Message "Downloading NuGet.exe..." try { Invoke-WebRequest -Uri https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile $NUGET_EXE } catch { Throw "Could not download NuGet.exe." } } # Save nuget.exe path to environment to be available to child processed $ENV:NUGET_EXE = $NUGET_EXE # Restore tools from NuGet? if(-Not $<API key>.IsPresent) { # Restore packages from NuGet. Push-Location Set-Location $TOOLS_DIR Write-Verbose -Message "Restoring tools from NuGet..." $NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`"" Write-Verbose -Message ($NuGetOutput | out-string) Pop-Location if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } # Make sure that Cake has been installed. if (!(Test-Path $CAKE_EXE)) { Throw "Could not find Cake.exe at $CAKE_EXE" } # Start Cake Write-Host "Running build script..." Invoke-Expression "$CAKE_EXE `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseMono $UseDryRun $UseExperimental" exit $LASTEXITCODE
<?php namespace Analogue\ORM\Relationships; use Analogue\ORM\EntityCollection; use Analogue\ORM\System\Mapper; abstract class HasOneOrMany extends Relationship { /** * The foreign key of the parent model. * * @var string */ protected $foreignKey; /** * The local key of the parent model. * * @var string */ protected $localKey; /** * Create a new has many relationship instance. * * @param Mapper $mapper * @param \Analogue\ORM\Mappable $parentEntity * @param string $foreignKey * @param string $localKey */ public function __construct(Mapper $mapper, $parentEntity, $foreignKey, $localKey) { $this->localKey = $localKey; $this->foreignKey = $foreignKey; parent::__construct($mapper, $parentEntity); } /** * @param \Analogue\ORM\Entity $entity */ public function attachOne($entity) { $wrapper = $this->factory->make($entity); // Ok, we need to guess the inverse of the relation from there. // Let's assume the inverse of the relation method is the name of // the entity. $wrapper->setEntityAttribute($this->getPlainForeignKey(), $this->getParentKey()); } /** * @param EntityCollection $entities */ public function attachMany(EntityCollection $entities) { foreach ($entities as $entity) { $this->attachOne($entity); } } /** * @param $entityHash */ protected function detachOne($entityHash) { $this->detachMany([$entityHash]); } /** * Attach ids that are passed as arguments, and detach any other. * * @param mixed $entities * * @throws \<API key> * * @return void */ public function sync(array $entities) { $this->detachExcept($entities); } /** * @param $entities * * @throws \<API key> */ protected function detachExcept($entities) { $query = $this->query->getQuery()->from($this->relatedMap->getTable()); if (count($entities) > 0) { $keys = $this->getKeys($entities); $query->whereNotIn($this->relatedMap->getKeyName(), $keys); } $parentKey = $this->parentMap->getKeyName(); $query->where($this->getPlainForeignKey(), '=', $this->parent->getEntityAttribute($parentKey)) ->update([$this->getPlainForeignKey() => null]); } /** * @param array $entityHashes */ public function detachMany(array $entityHashes) { $keys = []; foreach ($entityHashes as $hash) { $split = explode('.', $hash); $keys[] = $split[1]; } $query = $this->query->getQuery()->from($this->relatedMap->getTable()); $query->whereIn($this->relatedMap->getKeyName(), $keys) ->update([$this->getPlainForeignKey() => null]); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { if (static::$constraints) { $this->query->where($this->foreignKey, '=', $this->getParentKey()); } } /** * Set the constraints for an eager load of the relation. * * @param array $results * * @return void */ public function addEagerConstraints(array $results) { $this->query->whereIn($this->foreignKey, $this->getKeysFromResults($results, $this->localKey)); } /** * Match the eagerly loaded relationship to the current result set. * * @param array $results * @param string $relation * * @return array */ public function matchOne(array $results, $relation) { return $this->matchOneOrMany($results, $relation, 'one'); } /** * Match the eagerly loaded results to their many parents. * * @param array $results * @param string $relation * * @return array */ public function matchMany(array $results, $relation) { return $this->matchOneOrMany($results, $relation, 'many'); } /** * Match the eagerly loaded results to their many parents. * * @param array $results * @param string $relation * @param string $type * * @return array */ protected function matchOneOrMany(array $results, $relation, $type) { $entities = $this->getEager(); $dictionary = $this->buildDictionary($entities); $cache = $this->parentMapper->getEntityCache(); $host = $this; // Once we have the dictionary we can simply spin through the parent models to // link them up with their children using the keyed dictionary to make the // matching very convenient and easy work. Then we'll just return them. return array_map(function ($result) use ($dictionary, $cache, $type, $relation, $host) { $key = $result[$host->localKey]; if (isset($dictionary[$key])) { $value = $host->getRelationValue($dictionary, $key, $type); $result[$relation] = $value; // TODO : Refactor This $cache-><API key>($key, $relation, $value, $this); } else { $result[$relation] = $type === 'many' ? $this->relatedMap->newCollection() : null; } return $result; }, $results); } /** * Get the value of a relationship by one or many type. * * @param array $dictionary * @param string $key * @param string $type * * @return mixed */ protected function getRelationValue(array $dictionary, $key, $type) { $value = $dictionary[$key]; return $type == 'one' ? reset($value) : $this->relatedMap->newCollection($value); } /** * Build model dictionary keyed by the relation's foreign key. * * @param EntityCollection $results * * @return array */ protected function buildDictionary(EntityCollection $results) { $dictionary = []; $foreign = $this->getPlainForeignKey(); // First we will create a dictionary of models keyed by the foreign key of the // relationship as this will allow us to quickly access all of the related // models without having to do nested looping which will be quite slow. foreach ($results as $result) { $dictionary[$result->{$foreign}][] = $result; } return $dictionary; } /** * Get the key for comparing against the parent key in "has" query. * * @return string */ public function getHasCompareKey() { return $this->getForeignKey(); } /** * Get the foreign key for the relationship. * * @return string */ public function getForeignKey() { return $this->foreignKey; } /** * Get the plain foreign key. * * @return string */ public function getPlainForeignKey() { $segments = explode('.', $this->getForeignKey()); return $segments[count($segments) - 1]; } /** * Get the key value of the parent's local key. * * @return mixed */ public function getParentKey() { return $this->parent->getEntityAttribute($this->localKey); } /** * Get the fully qualified parent key name. * * @return string */ public function <API key>() { return $this->parentMap->getTable().'.'.$this->localKey; } /** * Get the foreign key as value pair for this relation. * * @return array */ public function <API key>() { return [$this->getPlainForeignKey() => $this->getParentKey()]; } }
'use strict'; //Start by defining the main module and adding the module dependencies angular.module(<API key>.<API key>, <API key>.<API key>); // Setting HTML5 Location Mode angular.module(<API key>.<API key>).config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix('!'); } ]); //Then define the init function for starting up the application angular.element(document).ready(function() { //Fixing facebook bug with redirect if (window.location.hash === '#_=_') window.location.hash = '#!'; window.navigator.userLanguage = window.navigator.language = 'es-AR'; //Then init the app angular.bootstrap(document, [<API key>.<API key>]); });
using Ninefold.Compute.Messages; namespace Ninefold.Compute { public interface IComputeClient { <API key> ListTemplates(<API key> request); <API key> ListAccounts(ListAccountsRequest request); <API key> <API key>(<API key> request); <API key> ListVirtualMachines(<API key> request); <API key> <API key>(<API key> request); ListIsosResponse ListIsos(ListIsosRequest request); <API key> ListIsoPermissions(<API key> request); ListVolumesResponse ListVolumes(ListVolumesRequest request); <API key> ListSnapshots(<API key> <API key>); <API key> <API key>(<API key> request); <API key> ListAsyncJobs(<API key> request); ListEventsResponse ListEvents(ListEventsRequest request); } }
"""Utils for time travel testings.""" def _t(rel=0.0): """Return an absolute time from the relative time given. The minimal allowed time in windows is 86400 seconds, for some reason. In stead of doing the arithmetic in the tests themselves, this function should be used. The value `86400` is exported in `time_travel.MIN_START_TIME`, but I shant use it for it is forbidden to test the code using the code that is being tested. """ return 86400.0 + rel
var server = http.createServer(function(req, res) { fs.readFile('./index.html', 'utf-8', function(error, content) { res.writeHead(200, {"Content-Type": "text/html"}); res.end(content); }); }); // Chargement de socket.io var io = require('socket.io').listen(server); // Quand un client se connecte, on le note dans la console io.sockets.on('connection', function (socket) { socket.on('new_profil', function(pseudo) { socket.pseudo = pseudo; socket.messages = []; //Todo save message in MongoDB }); socket.emit('message', 'Vous êtes bien connecté !'); //Receive all msg form all client socket.broadcast.emit('message', 'Un autre client vient de se connecter !'); socket.on('message', function (data) { if(data.message) { socket.messages.push(data.message); console.log(socket.pseudo + ' me parle ! Il me dit : ' + data.message); }else{ Console.log("There is problem:", data); } }); //envoit un message d'un client socket.on('send', function (data) { io.sockets.emit('message', data.message); }); }); server.listen(3000);
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [3.2.0] - 2021-10-18 Added - Add shell option to processes Changed - Maintenance updates ## [3.1.0] - 2020-08-24 Added - `.updateSpinnerText()` method Changed - Maintenance updates ## [3.0.4] - 2020-03-30 Changed - Maintenance updates Fixed - Allow `null` for `status.tracking` in `.printGitStatus()` ## [3.0.3] - 2020-03-15 Changed - Maintenance updates Fixed - Added support for RegExp on `process.runAsync` `ignoreError` option ## [3.0.2] - 2020-01-31 Fixed - Correct definition for `StatusResult` parameter in `.printGitStatus()` ## [3.0.1] - 2020-01-29 Changed - Maintenance updates Removed - Validation on logo length ## [3.0.0] - 2020-01-21 Added - API documentation - Arguments validation for all methods - Add options to `run` methods to specify a current working directory and environment variables - `.language` property - `.basicColor` property - `.spinnerType` property - `.colorizeText()` method - `.colorizeBackground()` method - `.confirmation()` method - `.stopSpinner()` method - `.confirmationBox()` method - `.process.parseOptions()` method Changed - Complete code refactor and standardization - Colors are now defined by Chalk keyword or hex string - All methods outputing are now chainable - Renamed `.defaults` to `.theme` with renamed and new values - Renamed `.setDefaults()` to `.setTheme()` with renamed and new options - Renamed `.printStatus()` to `.printGitStatus()` - Renamed `.run()` to `.process.run()` - Renamed `.runPromise()` to `.process.runAsync()` - Renamed `.runAndRead()` to `.process.runAndRead()` - Renamed `.runAndReadLines()` to `.process.runAndReadLines()` - Renamed `.runAndGet()` to `.process.runAndGet()` - Renamed `.runAndEcho()` to `.process.runAndEcho()` - Renamed `.runTask()` to `.process.runTask()` - Renamed `.printState()` option `msg` to `message` - Grouped `.box()` optional arguments under one argument with properties `colorizer`, `padding`, `extraPadding` - `.warning()` does not add newline by default anymore - `.startSpinner()` does not return `ora` instance anymore - Maintenance updates Removed - `.chalk` property - `.scripts` property - `.setDefault()` method - `.setLang()` method - `.setScriptsFiles()` method - `.cleanUp()` method - `.println()` method - `.trans()` method - `.addTrans()` method - `.startTimer()` method - `.isTimerStarted()` method - `.stopTimer()` method - `.runScript()` method ## [2.1.1] - 2019-08-29 Fixed - Added `borderColor` option to `.setDefaults()` ## [2.1.0] - 2019-08-29 Added - `.defaults` property - `.scripts` property - `.setLang()` method - `.trans()` method - `.addTrans()` method - `.cleanUp()` method - `.startTimer()` method - `.isTimerStarted()` method - `.stopTimer()` method - `.box()` method - `.borderedBox()` method - `.runAndReadLines()` method - Added JSDoc comments Changed - Renamed `.setDefault()` to `.setDefaults()` - Maintenance updates ## [2.0.0] - 2019-03-12 Added - Expose class definition Changed - Maintenance updates ## [1.2.1] - 2019-02-22 Fixed - Removed test in `.titleBox()` ## [1.2.0] - 2019-02-22 Changed - Changed color specifications - Maintenance updates Fixed - Finally fixed logo spacing ## [1.1.1] - 2019-02-05 Fixed - Corrected variable emoji width ## [1.1.0] - 2019-01-28 Changed - Support boxes with a width larger than 80 characters ## [1.0.2] - 2019-01-25 Fixed - Correction to box with emoji ## [1.0.1] - 2019-01-25 Fixed - Update `@absolunet/terminal-pad` to correct box with emoji ## [1.0.0] - 2019-01-17 Changed - Refactor for standardization - Maintenance updates ## [0.5.0] - 2018-05-02 Added - Duration on `.completionBox()` Changed - Maintenance updates ## [0.4.4] - 2017-09-27 Changed - More documentation ## [0.4.3] - 2017-09-27 Added - Added documentation Changed - Maintenance updates ## [0.4.2] - 2017-05-26 Added - Added a `silent` option in `.runPromise()` ## [0.4.1] - 2017-05-14 Changed - Better management of errors vs warnings in `.runPromise()` ## [0.4.0] - 2017-05-09 Added - Support ignore custom error messages in `.runPromise()` ## [0.3.1] - 2017-05-04 Fixed - Glitch with error output in `.runPromise()` ## [0.3.0] - 2017-05-04 Changed - Better handling of `.runPromise()` errors ## [0.2.0] - 2017-04-23 Added - `.startSpinner()` method ## [0.1.0] - 2017-04-18 Added - `.exit()` method - `.runPromise()` method ## [0.0.5] - 2017-04-06 Added - `.infoBox()` method ## [0.0.4] - 2017-03-28 Changed - Cleanup output in `.echoIndent()` ## [0.0.3] - 2017-03-28 Added - `.echoIndent()` method - `.println()` method - `.spacer()` method - `.printState()` method ## [0.0.2] - 2017-03-26 Added - Initial [Unreleased]: https://github.com/absolunet/node-terminal/compare/3.2.0...HEAD [3.2.0]: https://github.com/absolunet/node-terminal/compare/3.1.0...3.2.0 [3.1.0]: https://github.com/absolunet/node-terminal/compare/3.0.4...3.1.0 [3.0.4]: https://github.com/absolunet/node-terminal/compare/3.0.3...3.0.4 [3.0.3]: https://github.com/absolunet/node-terminal/compare/3.0.2...3.0.3 [3.0.2]: https://github.com/absolunet/node-terminal/compare/3.0.1...3.0.2 [3.0.1]: https://github.com/absolunet/node-terminal/compare/3.0.0...3.0.1 [3.0.0]: https://github.com/absolunet/node-terminal/compare/2.1.1...3.0.0 [2.1.1]: https://github.com/absolunet/node-terminal/compare/2.1.0...2.1.1 [2.1.0]: https://github.com/absolunet/node-terminal/compare/2.0.0...2.1.0 [2.0.0]: https://github.com/absolunet/node-terminal/compare/1.2.1...2.0.0 [1.2.1]: https://github.com/absolunet/node-terminal/compare/1.2.0...1.2.1 [1.2.0]: https://github.com/absolunet/node-terminal/compare/1.1.1...1.2.0 [1.1.1]: https://github.com/absolunet/node-terminal/compare/1.1.0...1.1.1 [1.1.0]: https://github.com/absolunet/node-terminal/compare/1.0.2...1.1.0 [1.0.2]: https://github.com/absolunet/node-terminal/compare/1.0.1...1.0.2 [1.0.1]: https://github.com/absolunet/node-terminal/compare/1.0.0...1.0.1 [1.0.0]: https://github.com/absolunet/node-terminal/compare/0.5.0...1.0.0 [0.5.0]: https://github.com/absolunet/node-terminal/compare/0.4.4...0.5.0 [0.4.4]: https://github.com/absolunet/node-terminal/compare/0.4.3...0.4.4 [0.4.3]: https://github.com/absolunet/node-terminal/compare/0.4.2...0.4.3 [0.4.2]: https://github.com/absolunet/node-terminal/compare/0.4.1...0.4.2 [0.4.1]: https://github.com/absolunet/node-terminal/compare/0.4.0...0.4.1 [0.4.0]: https://github.com/absolunet/node-terminal/compare/0.3.1...0.4.0 [0.3.1]: https://github.com/absolunet/node-terminal/compare/0.3.0...0.3.1 [0.3.0]: https://github.com/absolunet/node-terminal/compare/0.2.0...0.3.0 [0.2.0]: https://github.com/absolunet/node-terminal/compare/0.1.0...0.2.0 [0.1.0]: https://github.com/absolunet/node-terminal/compare/0.0.5...0.1.0 [0.0.5]: https://github.com/absolunet/node-terminal/compare/0.0.4...0.0.5 [0.0.4]: https://github.com/absolunet/node-terminal/compare/0.0.3...0.0.4 [0.0.3]: https://github.com/absolunet/node-terminal/compare/0.0.2...0.0.3 [0.0.2]: https://github.com/absolunet/node-terminal/releases/tag/0.0.2
module.exports = require('../dist/Collapse');
'use strict' let console = require('./console') let color = require('./color') let errors = require('./errors') class Spinner { constructor (options) { this.options = Object.assign({ text: '' }, options) this.ansi = require('ansi-escapes') let spinners = require('./spinners.json') this.color = this.options.color || 'heroku' this.spinner = process.platform === 'win32' ? spinners.line : (this.options.spinner ? spinners[this.options.spinner] : spinners.dots2) this.text = this.options.text this.interval = this.options.interval || this.spinner.interval || 100 this.id = null this.frameIndex = 0 this.stream = this.options.stream || process.stderr this.enabled = !console.mocking() && (this.stream && this.stream.isTTY) && !process.env.CI this.warnings = [] } start () { if (this.id) return if (!this.enabled) { console.writeError(this.text) return } this.stream.write(this.ansi.cursorLeft) this.stream.write(this.ansi.eraseLine) this.stream.write(this.ansi.cursorHide) this._render() this.id = setInterval(this._spin.bind(this), this.interval) process.on('SIGWINCH', this._sigwinch = this._render.bind(this)) } stop (status) { if (status && !this.enabled) console.error(` ${status}`) if (!this.enabled) return if (status) this._status = status process.removeListener('SIGWINCH', this._sigwinch) clearInterval(this.id) this.id = null this.enabled = false this.frameIndex = 0 this._render() this.stream.write(this.ansi.cursorShow) } warn (msg) { if (!this.enabled) { console.writeError(color.yellow(' !') + '\n' + errors.renderWarning(msg) + '\n' + this.text) } else { this.warnings.push(msg) this._render() } } get status () { return this._status } set status (status) { this._status = status if (this.enabled) this._render() else console.writeError(` ${this.status}\n${this.text}`) } clear () { if (!this._output) return this.stream.write(this.ansi.cursorUp(this._lines)) this.stream.write(this.ansi.eraseDown) } _render () { if (this._output) this.clear() this._output = `${this.text}${this.enabled ? ' ' + this._frame() : ''} ${this.status ? this.status : ''}\n` + this.warnings.map(w => errors.renderWarning(w) + '\n').join('') this.stream.write(this._output) } get _lines () { return color.stripColor(this._output) .split('\n') .map(l => Math.ceil(l.length / this._width)) .reduce((c, i) => c + i, 0) } get _width () { return errors.errtermwidth() } _spin () { this.stream.write(this.ansi.cursorUp(this._lines)) let x = color.stripColor(this.text).length + 1 let y = Math.floor(x / this._width) x = x - y * this._width this.stream.write(this.ansi.cursorMove(x, y)) this.stream.write(this._frame()) this.stream.write(this.ansi.cursorDown(this._lines - y)) this.stream.write(this.ansi.cursorLeft) this.stream.write(this.ansi.eraseLine) } _frame () { var frames = this.spinner.frames var frame = frames[this.frameIndex] if (this.color) frame = color[this.color](frame) this.frameIndex = ++this.frameIndex % frames.length return frame } } module.exports = Spinner
title: Extracting Contacts from Gmail date: 2016-11-01 12:00:00 Z layout: post published: false <script src="https://gist.github.com/joeyvmason/<API key>.js"></script>
// UIViewController+AlertVc.h // ShreddedBread /** * <API key> * * */ #import <UIKit/UIKit.h> @interface UIViewController (AlertVc) - (void)<API key>:(nullable NSString *)title message:(nullable NSString *)message preferredStyle:(<API key>)preferredStyle alertActionName:(nullable NSString *)alertActionName alertActionOne:(nullable void (^)())alertActionOne alertBackAfter:(nullable void (^)())alertBackAction; - (void)<API key>:(nullable NSString *)str time:(float)time; - (void)<API key>:(nullable NSString *)title message:(nullable NSString *)message preferredStyle:(<API key>)preferredStyle alertActionName:(nullable NSString *)alertActionName; @end
import sbt._ object Dependencies { object Version { val akka = "2.6.6" val akkaHttp = "10.1.12" val circe = "0.13.0" val slf4j = "1.7.30" val logback = "1.2.3" } val akkaStream = "com.typesafe.akka" %% "akka-stream" % Version.akka val akkaHttp = "com.typesafe.akka" %% "akka-http" % Version.akkaHttp val akkaHttpCirce = "de.heikoseeberger" %% "akka-http-circe" % "1.32.0" val circeCore = "io.circe" %% "circe-core" % Version.circe val circeGeneric = "io.circe" %% "circe-generic" % Version.circe val circeParser = "io.circe" %% "circe-parser" % Version.circe val slf4jApi = "org.slf4j" % "slf4j-api" % Version.slf4j val logbackCore = "ch.qos.logback" % "logback-core" % Version.logback val logbackClassic = "ch.qos.logback" % "logback-classic" % Version.logback val serverDeps = Seq( akkaStream, akkaHttp, akkaHttpCirce, circeCore, circeGeneric, circeParser, slf4jApi, logbackCore, logbackClassic ) val rootDeps = Seq( ) }