answer
stringlengths
15
1.25M
from ev import Command, CmdSet from src.commands.default.muxcommand import MuxCommand class CmdAttack(Command): """ Begin to fight a target, typically an npc enemy. Usage: attack target-name """ key = 'attack' aliases = ['kill'] help_category = "Combat" locks = "cmd:all()" def parse(self): self.what = self.args.strip() def func(self): caller = self.caller mob = caller.search(self.what, global_search=False) if mob is None: return caller.begin_combat(mob) class CmdTalk(Command): """ Attempt to talk to the given object, typically an npc who is able to respond to you. Will return gracefully if the particular object does not support having a conversation with the character. Usage: talk to <npc|object name> <whatever yer message is> NOTE: Just because you can talk to an npc does not mean that they care about or know about what you are discussing with them. Typically the control words will be very easy to spot. """ key = 'talk' aliases = ['talk to', 't'] help_category = 'general' locks = "cmd:all()" def parse(self): if len(self.args) < 1: print "usage: talk to <npc> <message>" return args = self.args.split() self.npc = args[0] args.remove(self.npc) self.message = ' '.join(args) def func(self): if self.caller.db.in_combat: self.caller.msg("{RCan't talk to people while in combat!") return if len(self.args) < 1: self.caller.msg("usage: talk to <npc> <message>") return npc = self.caller.search(self.npc, global_search=False) if hasattr(npc, "combatant"): self.caller.msg("You can't talk to that, are you mad?") else: if npc is not None: self.caller.msg("{mYou tell %s: %s{n" % (npc.name, self.message)) npc.dictate_action(self.caller, self.message) else: self.caller.msg("I don not see anyone around by that name.") return class CmdDisplaySheet(Command): """ Display your character sheet. Usage: stats """ key = 'stats' aliases = ['points', 'sheet'] help_category = "General" locks = "cmd:all()" def func(self): caller = self.caller caller.<API key>() class CmdLoot(Command): """ Pass a corpse name to this command to loot the corpse. Usage: loot <corpse> """ key = 'loot' help_category = "General" locks = "cmd:all()" def parse(self): self.what = self.args.strip() def func(self): obj = self.caller.search(self.what, global_search=False) if obj is None: return if obj.db.corpse: if len(obj.contents) == 0: self.caller.msg("That corpse is empty.") obj.db.destroy_me = True return for i in obj.contents: if i.db.attributes['lootable']: i.move_to(self.caller, quiet=True) self.caller.msg("{CYou have looted a: %s{n" % i.name) obj.db.destroy_me = True else: self.caller.msg("{RThat is not a corpse.{n") class CmdEquip(Command): key = 'equip' help_category = "General" locks = "cmd:all()" def parse(self): self.what = self.args.strip() def func(self): e = self.caller.db.equipment obj = self.caller.search(self.what, global_search=False) print e print obj oa = obj.db.attributes if obj is None: return e['%s' % oa['item_slot']] = obj self.caller.msg("{CYou have equipped: %s as your weapon.{n") class CmdLook(MuxCommand): """ look at location or object Usage: look look <obj> look *<player> Observes your location or objects in your vicinity. """ key = "look" aliases = ["l", "ls"] locks = "cmd:all()" arg_regex = r"\s.*?|$" def func(self): """ Handle the looking. """ caller = self.caller args = self.args if args: # Use search to handle duplicate/nonexistant results. if self.caller.location.db.decor_objects is not None and len(self.caller.location.db.decor_objects) > 0: for k in self.caller.location.db.decor_objects: print k if k.lower() == args.lower(): caller.msg("%s" % self.caller.location.db.decor_objects[k]) return looking_at_obj = caller.search(args, use_nicks=True) if not looking_at_obj: return else: looking_at_obj = caller.location if not looking_at_obj: caller.msg("You have no location to look at!") return if not hasattr(looking_at_obj, 'return_appearance'): # this is likely due to us having a player instead looking_at_obj = looking_at_obj.character if not looking_at_obj.access(caller, "view"): caller.msg("Could not find '%s'." % args) return # get object's appearance caller.msg(looking_at_obj.return_appearance(caller)) # the object's at_desc() method. looking_at_obj.at_desc(looker=caller) class CmdEquip(Command): """ This attempts to equip items on the character. If no arguements are given, then it picks the first item for each slot it finds and equips those items in their respective slots. usage: equip <item to equip> aliases: wield, equip item, e """ key = 'equip' aliases = ['equip item', 'wield', 'e'] help_category = "General" locks = "cmd:all()" def parse(self): if len(self.args) < 1: self.what = None else: self.what = self.args.strip() def func(self): if self.caller.db.in_combat: self.caller.msg("{RCan't equip while in combat!") if len(self.args) < 1: self.caller.msg("What did you want to equip? equip <item to equip>") return if self.what is not None: obj = self.caller.search(self.what, global_search=False) if not obj: self.caller.msg("Are you sure you are carrying the item you are trying to equip?") else: self.caller.equip_item(ite=obj, slot=obj.db.attributes['item_slot']) obj.on_equip() else: self.caller.equip_item(ite=None,slot=None) class CharacterCmdSet(CmdSet): key = "<API key>" def at_cmdset_creation(self): self.add(CmdAttack()) self.add(CmdLoot()) self.add(CmdDisplaySheet()) self.add(CmdEquip()) self.add(CmdTalk()) self.add(CmdLook()) self.add(CmdEquip())
package de.plushnikov.utilityclass; import lombok.experimental.UtilityClass; @UtilityClass public class Permission { public String <API key> = "arena.admin"; }
// Use of this source code is governed by a BSD-style package template import ( "bytes" "encoding/json" "fmt" "reflect" "strings" "unicode/utf8" ) // nextJSCtx returns the context that determines whether a slash after the // given run of tokens starts a regular expression instead of a division // operator: / or /=. // This assumes that the token run does not include any string tokens, comment // tokens, regular expression literal tokens, or division operators. // This fails on some valid but nonsensical JavaScript programs like // "x = ++/foo/i" which is quite different than "x++/foo/i", but is not known to // fail on any known useful programs. It is based on the draft // JavaScript 2.0 lexical grammar and requires one token of lookbehind: func nextJSCtx(s []byte, preceding jsCtx) jsCtx { s = bytes.TrimRight(s, "\t\n\f\r \u2028\u2029") if len(s) == 0 { return preceding } // All cases below are in the single-byte UTF-8 group. switch c, n := s[len(s)-1], len(s); c { case '+', '-': // ++ and -- are not regexp preceders, but + and - are whether // they are used as infix or prefix operators. start := n - 1 // Count the number of adjacent dashes or pluses. for start > 0 && s[start-1] == c { start } if (n-start)&1 == 1 { // same as "-- -". return jsCtxRegexp } return jsCtxDivOp case '.': // Handle "42." if n != 1 && '0' <= s[n-2] && s[n-2] <= '9' { return jsCtxDivOp } return jsCtxRegexp // Suffixes for all punctuators from section 7.7 of the language spec // that only end binary operators not handled above. case ',', '<', '>', '=', '*', '%', '&', '|', '^', '?': return jsCtxRegexp // Suffixes for all punctuators from section 7.7 of the language spec // that are prefix operators not handled above. case '!', '~': return jsCtxRegexp // Matches all the punctuators from section 7.7 of the language spec // that are open brackets not handled above. case '(', '[': return jsCtxRegexp // Matches all the punctuators from section 7.7 of the language spec // that precede expression starts. case ':', ';', '{': return jsCtxRegexp // CAVEAT: the close punctuators ('}', ']', ')') precede div ops and // are handled in the default except for '}' which can precede a // division op as in // ({ valueOf: function () { return 42 } } / 2 // which is valid, but, in practice, developers don't divide object // literals, so our heuristic works well for code like // function () { ... } /foo/.test(x) && sideEffect(); // The ')' punctuator can precede a regular expression as in // if (b) /foo/.test(x) && ... // but this is much less likely than // (a + b) / c case '}': return jsCtxRegexp default: // Look for an IdentifierName and see if it is a keyword that // can precede a regular expression. j := n for j > 0 && isJSIdentPart(rune(s[j-1])) { j } if <API key>[string(s[j:])] { return jsCtxRegexp } } // Otherwise is a punctuator not listed above, or // a string which precedes a div op, or an identifier // which precedes a div op. return jsCtxDivOp } // <API key> is a set of reserved JS keywords that can precede a // regular expression in JS source. var <API key> = map[string]bool{ "break": true, "case": true, "continue": true, "delete": true, "do": true, "else": true, "finally": true, "in": true, "instanceof": true, "return": true, "throw": true, "try": true, "typeof": true, "void": true, } var jsonMarshalType = reflect.TypeOf((*json.Marshaler)(nil)).Elem() // <API key> returns the value, after dereferencing as many times // as necessary to reach the base type (or nil) or an implementation of json.Marshal. func <API key>(a interface{}) interface{} { v := reflect.ValueOf(a) for !v.Type().Implements(jsonMarshalType) && v.Kind() == reflect.Ptr && !v.IsNil() { v = v.Elem() } return v.Interface() } // jsValEscaper escapes its inputs to a JS Expression (section 11.14) that has // neither side-effects nor free variables outside (NaN, Infinity). func jsValEscaper(args ...interface{}) string { var a interface{} if len(args) == 1 { a = <API key>(args[0]) switch t := a.(type) { case JS: return string(t) case JSStr: // TODO: normalize quotes. return `"` + string(t) + `"` case json.Marshaler: // Do not treat as a Stringer. case fmt.Stringer: a = t.String() } } else { for i, arg := range args { args[i] = <API key>(arg) } a = fmt.Sprint(args...) } // TODO: detect cycles before calling Marshal which loops infinitely on // cyclic data. This may be an unacceptable DoS risk. b, err := json.Marshal(a) if err != nil { // Put a space before comment so that if it is flush against // a division operator it is not turned into a line comment: // turning into // x//* error marshalling y: // second line of error message */null return fmt.Sprintf(" null ", strings.Replace(err.Error(), "*/", "* /", -1)) } // TODO: maybe post-process output to prevent it from containing // "", "<![CDATA[", "]]>", or "</script" // in case custom marshallers produce output containing those. // TODO: Maybe abbreviate \u00ab to \xab to produce more compact output. if len(b) == 0 { // In, `x=y/{{.}}*z` a json.Marshaler that produces "" should
#ifndef PNGTEST1_READER_H #define PNGTEST1_READER_H extern int TestReader(); #endif /* PNGTEST1_READER_H */
import { ConfigPlugin, WarningAggregator, <API key> } from '@expo/config-plugins'; import { ExpoConfig } from '@expo/config-types'; export type IosProps = { appleTeamId?: string; <API key>?: 'Development' | 'Production'; }; export const <API key>: ConfigPlugin<IosProps> = ( config, { appleTeamId, <API key> } ) => { return <API key>(config, (config) => { if (appleTeamId) { config.modResults = <API key>( config, { appleTeamId, <API key> }, config.modResults ); } else { WarningAggregator.addWarningIOS( '<API key>', 'Cannot configure iOS entitlements because neither the appleTeamId property, nor the environment variable EXPO_APPLE_TEAM_ID were defined.' ); } return config; }); }; export function <API key>( config: Pick<ExpoConfig, 'ios'>, { appleTeamId, <API key> }: IosProps, { 'com.apple.developer.<API key>': _env, ...entitlements }: Record<string, any> ): Record<string, any> { if (config.ios?.usesIcloudStorage) { entitlements['com.apple.developer.<API key>'] = <API key>; entitlements['com.apple.developer.<API key>'] = [ 'iCloud.' + config.ios.bundleIdentifier, ]; entitlements['com.apple.developer.<API key>'] = [ 'iCloud.' + config.ios.bundleIdentifier, ]; entitlements['com.apple.developer.<API key>'] = appleTeamId + '.' + config.ios.bundleIdentifier; entitlements['com.apple.developer.icloud-services'] = ['CloudDocuments']; } return entitlements; }
<!-- This comment will put IE 6, 7 and 8 in quirks mode --> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>wdt.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="$relpath/search.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <table width="100%"> <tr> <td bgcolor="black" width="1"><a href="http: <td bgcolor="red"><img src="titagline.gif" /></td> </tr> </table> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">MSP430 Driver Library &#160;<span id="projectnumber">1.90.00.65</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.5 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="<API key>.html">cygdrive</a></li><li class="navelem"><a class="el" href="<API key>.html">c</a></li><li class="navelem"><a class="el" href="<API key>.html">msp430-driverlib</a></li><li class="navelem"><a class="el" href="<API key>.html">driverlib</a></li><li class="navelem"><a class="el" href="<API key>.html">MSP430i2xx</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#define-members">Macros</a> &#124; <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">wdt.h File Reference</div> </div> </div><!--header <div class="contents"> <div class="textblock"><code>#include &quot;<a class="el" href="<API key>.html">inc/hw_memmap.h</a>&quot;</code><br/> </div> <p><a href="wdt_8h_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="define-members"></a> Macros</h2></td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="wdt_8h.html#<API key>"><API key></a>&#160;&#160;&#160;(0x00)</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="wdt_8h.html#<API key>"><API key></a>&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTSSEL</a>)</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="wdt_8h.html#<API key>"><API key></a>&#160;&#160;&#160;(0x00)</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="wdt_8h.html#<API key>"><API key></a>&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTIS0</a>)</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="wdt_8h.html#<API key>"><API key></a>&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTIS1</a>)</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="wdt_8h.html#<API key>">WDT_CLOCKDIVIDER_64</a>&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTIS0</a> | <a class="el" href="<API key>.html#<API key>">WDTIS1</a>)</td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__wdt__api.html#<API key>">WDT_hold</a> (uint16_t baseAddress)</td></tr> <tr class="memdesc:<API key>"><td class="mdescLeft">&#160;</td><td class="mdescRight">Holds the Watchdog Timer. <a href="group__wdt__api.html#<API key>">More...</a><br/></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__wdt__api.html#<API key>">WDT_start</a> (uint16_t baseAddress)</td></tr> <tr class="memdesc:<API key>"><td class="mdescLeft">&#160;</td><td class="mdescRight">Starts the Watchdog Timer. <a href="group__wdt__api.html#<API key>">More...</a><br/></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__wdt__api.html#<API key>">WDT_resetTimer</a> (uint16_t baseAddress)</td></tr> <tr class="memdesc:<API key>"><td class="mdescLeft">&#160;</td><td class="mdescRight">Resets the timer counter of the Watchdog Timer. <a href="group__wdt__api.html#<API key>">More...</a><br/></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__wdt__api.html#<API key>"><API key></a> (uint16_t baseAddress, uint8_t clockSelect, uint8_t clockDivider)</td></tr> <tr class="memdesc:<API key>"><td class="mdescLeft">&#160;</td><td class="mdescRight">Sets the clock source for the Watchdog Timer in watchdog mode. <a href="group__wdt__api.html#<API key>">More...</a><br/></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__wdt__api.html#<API key>"><API key></a> (uint16_t baseAddress, uint8_t clockSelect, uint8_t clockDivider)</td></tr> <tr class="memdesc:<API key>"><td class="mdescLeft">&#160;</td><td class="mdescRight">Sets the clock source for the Watchdog Timer in timer interval mode. <a href="group__wdt__api.html#<API key>">More...</a><br/></td></tr> <tr class="separator:<API key>"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Macro Definition Documentation</h2> <a class="anchor" id="<API key>"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define <API key>&#160;&#160;&#160;(0x00)</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="<API key>"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define <API key>&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTSSEL</a>)</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="<API key>"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define <API key>&#160;&#160;&#160;(0x00)</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="<API key>"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define <API key>&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTIS0</a>)</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="<API key>"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define <API key>&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTIS1</a>)</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="<API key>"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define WDT_CLOCKDIVIDER_64&#160;&#160;&#160;(<a class="el" href="<API key>.html#<API key>">WDTIS0</a> | <a class="el" href="<API key>.html#<API key>">WDTIS1</a>)</td> </tr> </table> </div><div class="memdoc"> </div> </div> </div><!-- contents --> <hr size="1" /><small> Copyright 2014, Texas Instruments Incorporated</small> </body> </html>
package versioned.host.exp.exponent.modules.api.components; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.yqritc.scalablevideoview.ScalableType; import versioned.host.exp.exponent.modules.api.components.VideoView.Events; import javax.annotation.Nullable; import java.util.Map; public class VideoViewManager extends SimpleViewManager<VideoView> { public static final String REACT_CLASS = "ExponentVideo"; public static final String PROP_SRC = "src"; public static final String PROP_SRC_URI = "uri"; public static final String PROP_SRC_TYPE = "type"; public static final String PROP_SRC_IS_NETWORK = "isNetwork"; public static final String PROP_SRC_IS_ASSET = "isAsset"; public static final String PROP_RESIZE_MODE = "resizeMode"; public static final String PROP_REPEAT = "repeat"; public static final String PROP_PAUSED = "paused"; public static final String PROP_MUTED = "muted"; public static final String PROP_VOLUME = "volume"; public static final String PROP_SEEK = "seek"; public static final String PROP_RATE = "rate"; @Override public String getName() { return REACT_CLASS; } @Override protected VideoView createViewInstance(ThemedReactContext themedReactContext) { return new VideoView(themedReactContext); } @Override @Nullable public Map <API key>() { MapBuilder.Builder builder = MapBuilder.builder(); for (Events event : Events.values()) { builder.put(event.toString(), MapBuilder.of("registrationName", event.toString())); } return builder.build(); } @Override @Nullable public Map <API key>() { return MapBuilder.of( "ScaleNone", Integer.toString(ScalableType.LEFT_TOP.ordinal()), "ScaleToFill", Integer.toString(ScalableType.FIT_XY.ordinal()), "ScaleAspectFit", Integer.toString(ScalableType.FIT_CENTER.ordinal()), "ScaleAspectFill", Integer.toString(ScalableType.CENTER_CROP.ordinal()) ); } @ReactProp(name = PROP_SRC) public void setSrc(final VideoView videoView, @Nullable ReadableMap src) { videoView.setSrc( src.getString(PROP_SRC_URI), src.getString(PROP_SRC_TYPE), src.getBoolean(PROP_SRC_IS_NETWORK), src.getBoolean(PROP_SRC_IS_ASSET) ); } @ReactProp(name = PROP_RESIZE_MODE) public void setResizeMode(final VideoView videoView, final String <API key>) { videoView.<API key>(ScalableType.values()[Integer.parseInt(<API key>)]); } @ReactProp(name = PROP_REPEAT, defaultBoolean = false) public void setRepeat(final VideoView videoView, final boolean repeat) { videoView.setRepeatModifier(repeat); } @ReactProp(name = PROP_PAUSED, defaultBoolean = false) public void setPaused(final VideoView videoView, final boolean paused) { videoView.setPausedModifier(paused); } @ReactProp(name = PROP_MUTED, defaultBoolean = false) public void setMuted(final VideoView videoView, final boolean muted) { videoView.setMutedModifier(muted); } @ReactProp(name = PROP_VOLUME, defaultFloat = 1.0f) public void setVolume(final VideoView videoView, final float volume) { videoView.setVolumeModifier(volume); } @ReactProp(name = PROP_SEEK) public void setSeek(final VideoView videoView, final float seek) { videoView.seekTo(Math.round(seek * 1000.0f)); } @ReactProp(name = PROP_RATE) public void setRate(final VideoView videoView, final float rate) { videoView.setRateModifier(rate); } }
<?php namespace NpPage\Config\Loader; /** * Description of ConfigLoader * * @author tomoaki */ interface <API key> { public function __construct(array $config = null); public function load($name); }
from jinja2 import escape from flask.globals import _request_ctx_stack from flask import json from wtforms import widgets from mytrade.utils import _, get_url class Select2Widget(widgets.Select): def __call__(self, field, **kwargs): kwargs.setdefault('data-role', u'select2') allow_blank = getattr(field, 'allow_blank', False) if allow_blank and not self.multiple: kwargs['data-allow-blank'] = u'1' return super(Select2Widget, self).__call__(field, **kwargs) class Select2TagsWidget(widgets.TextInput): def __call__(self, field, **kwargs): kwargs.setdefault('data-role', u'select2') kwargs.setdefault('data-tags', u'1') return super(Select2TagsWidget, self).__call__(field, **kwargs) class DatePickerWidget(widgets.TextInput): """ Date picker widget. You must include <API key>.js and form-x.x.x.js for styling to work. """ def __call__(self, field, **kwargs): kwargs.setdefault('data-role', u'datepicker') kwargs.setdefault('data-date-format', u'YYYY-MM-DD') self.date_format = kwargs['data-date-format'] return super(DatePickerWidget, self).__call__(field, **kwargs) class <API key>(widgets.TextInput): """ Datetime picker widget. You must include <API key>.js and form-x.x.x.js for styling to work. """ def __call__(self, field, **kwargs): kwargs.setdefault('data-role', u'datetimepicker') kwargs.setdefault('data-date-format', u'YYYY-MM-DD HH:mm:ss') return super(<API key>, self).__call__(field, **kwargs) class TimePickerWidget(widgets.TextInput): """ Date picker widget. You must include <API key>.js and form-x.x.x.js for styling to work. """ def __call__(self, field, **kwargs): kwargs.setdefault('data-role', u'timepicker') kwargs.setdefault('data-date-format', u'HH:mm:ss') return super(TimePickerWidget, self).__call__(field, **kwargs) class <API key>(object): """ WTForms widget that renders Jinja2 template """ def __init__(self, template): """ Constructor :param template: Template path """ self.template = template def __call__(self, field, **kwargs): ctx = _request_ctx_stack.top jinja_env = ctx.app.jinja_env kwargs.update({ 'field': field, '_gettext': _, '_ngettext': _, }) template = jinja_env.get_template(self.template) return template.render(kwargs) class <API key>(<API key>): def __init__(self): super(<API key>, self).__init__('widgets/inline_field_list.html') class InlineFormWidget(<API key>): def __init__(self): super(InlineFormWidget, self).__init__('widgets/inline_form.html') def __call__(self, field, **kwargs): kwargs.setdefault('form_opts', getattr(field, 'form_opts', None)) return super(InlineFormWidget, self).__call__(field, **kwargs) class AjaxSelect2Widget(object): def __init__(self, multiple=False): self.multiple = multiple def __call__(self, field, **kwargs): kwargs.setdefault('data-role', 'select2-ajax') kwargs.setdefault('data-url', get_url('.ajax_lookup', name=field.loader.name)) allow_blank = getattr(field, 'allow_blank', False) if allow_blank and not self.multiple: kwargs['data-allow-blank'] = u'1' kwargs.setdefault('id', field.id) kwargs.setdefault('type', 'hidden') if self.multiple: result = [] ids = [] for value in field.data: data = field.loader.format(value) result.append(data) ids.append(data[0]) separator = getattr(field, 'separator', ',') kwargs['value'] = separator.join(ids) kwargs['data-json'] = json.dumps(result) kwargs['data-multiple'] = u'1' else: data = field.loader.format(field.data) if data: kwargs['value'] = data[0] kwargs['data-json'] = json.dumps(data) placeholder = _(field.loader.options.get('placeholder', 'Please select model')) kwargs.setdefault('data-placeholder', placeholder) return widgets.HTMLString('<input %s>' % widgets.html_params(name=field.name, **kwargs)) class XEditableWidget(object): """ WTForms widget that provides in-line editing for the list view. Determines how to display the x-editable/ajax form based on the field inside of the FieldList (StringField, IntegerField, etc). """ def __call__(self, field, **kwargs): kwargs.setdefault('data-value', kwargs.pop('value', '')) kwargs.setdefault('data-role', 'x-editable') kwargs.setdefault('data-url', './ajax/update/') kwargs.setdefault('id', field.id) kwargs.setdefault('name', field.name) kwargs.setdefault('href', ' if not kwargs.get('pk'): raise Exception('pk required') kwargs['data-pk'] = str(kwargs.pop("pk")) kwargs['data-csrf'] = kwargs.pop("csrf", "") # subfield is the first entry (subfield) from FieldList (field) subfield = field.entries[0] kwargs = self.get_kwargs(subfield, kwargs) return widgets.HTMLString( '<a %s>%s</a>' % (widgets.html_params(**kwargs), escape(kwargs['data-value'])) ) def get_kwargs(self, subfield, kwargs): """ Return extra kwargs based on the subfield type. """ if subfield.type == 'StringField': kwargs['data-type'] = 'text' elif subfield.type == 'TextAreaField': kwargs['data-type'] = 'textarea' kwargs['data-rows'] = '5' elif subfield.type == 'BooleanField': kwargs['data-type'] = 'select' # data-source = dropdown options kwargs['data-source'] = {'': 'False', '1': 'True'} kwargs['data-role'] = 'x-editable-boolean' elif subfield.type == 'Select2Field': kwargs['data-type'] = 'select' choices = [{'value': x, 'text': y} for x, y in subfield.choices] # prepend a blank field to choices if allow_blank = True if getattr(subfield, 'allow_blank', False): choices.insert(0, {'value': '__None', 'text': ''}) # json.dumps fixes issue with unicode strings not loading correctly kwargs['data-source'] = json.dumps(choices) elif subfield.type == 'DateField': kwargs['data-type'] = 'combodate' kwargs['data-format'] = 'YYYY-MM-DD' kwargs['data-template'] = 'YYYY-MM-DD' elif subfield.type == 'DateTimeField': kwargs['data-type'] = 'combodate' kwargs['data-format'] = 'YYYY-MM-DD HH:mm:ss' kwargs['data-template'] = 'YYYY-MM-DD HH:mm:ss' # <API key> uses 1 minute increments kwargs['data-role'] = '<API key>' elif subfield.type == 'TimeField': kwargs['data-type'] = 'combodate' kwargs['data-format'] = 'HH:mm:ss' kwargs['data-template'] = 'HH:mm:ss' kwargs['data-role'] = '<API key>' elif subfield.type == 'IntegerField': kwargs['data-type'] = 'number' elif subfield.type in ['FloatField', 'DecimalField']: kwargs['data-type'] = 'number' kwargs['data-step'] = 'any' elif subfield.type in ['QuerySelectField', 'ModelSelectField']: # QuerySelectField and ModelSelectField are for relations kwargs['data-type'] = 'select' choices = [] for choice in subfield: try: choices.append({'value': str(choice._value()), 'text': str(choice.label.text)}) except TypeError: # unable to display text value choices.append({'value': str(choice._value()), 'text': ''}) # blank field is already included if allow_blank kwargs['data-source'] = json.dumps(choices) else: raise Exception('Unsupported field type: %s' % (type(subfield),)) return kwargs
<?php namespace frontend\controllers; use common\models\Product; class ProductController extends \frontend\controllers\FrontendController { public function actionView($slug) { $productModel = new Product(); $productData = $productModel->findOne(['slug' => $slug]); $relatedProduct = $productModel->find()->where([ 'category_id' => $productData->category_id, ])->andWhere(['<>', 'id', $productData->id]) ->limit(9) ->orderBy(['id' => SORT_ASC]) ->all(); return $this->render('view', [ 'node' => $productData, 'relateNodes' => $relatedProduct, ]); } }
package gov.hhs.fha.nhinc.patientdiscovery.entity.deferred.response; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.orchestration.Orchestratable; import gov.hhs.fha.nhinc.orchestration.<API key>; import gov.hhs.fha.nhinc.patientdiscovery.<API key>; import gov.hhs.fha.nhinc.patientdiscovery.<API key>; import gov.hhs.fha.nhinc.patientdiscovery.nhin.deferred.response.proxy.<API key>; import gov.hhs.fha.nhinc.patientdiscovery.nhin.deferred.response.proxy.<API key>; import gov.hhs.fha.nhinc.properties.<API key>; import gov.hhs.fha.nhinc.properties.PropertyAccessor; import org.apache.log4j.Logger; import org.hl7.v3.MCCIIN000002UV01; import org.hl7.v3.PRPAIN201306UV02; /** * @author akong * */ public class <API key> implements <API key> { private static final Logger LOG = Logger.getLogger(<API key>.class); @Override public void execute(Orchestratable message) { if (message instanceof <API key>) { execute((<API key>) message); } else { LOG.error("Not an <API key>."); } } public void execute(<API key> message) { LOG.debug("Begin <API key>.process"); if (message == null) { LOG.debug("<API key> was null"); return; } if (message instanceof <API key>) { boolean auditNhin = isAuditEnabled(NhincConstants.<API key>, NhincConstants.NHIN_AUDIT_PROPERTY); if (auditNhin) { auditRequestToNhin(message.getRequest(), message.getAssertion()); } <API key> <API key> = new <API key>() .<API key>(); MCCIIN000002UV01 response = <API key>.<API key>(message.getRequest(), message.getAssertion(), message.getTarget()); message.setResponse(response); if (auditNhin) { <API key>(message.getResponse(), message.getAssertion()); } } else { LOG.error( "<API key> received a message " + "which was not of type <API key>."); } LOG.debug("End <API key>.process"); } private void auditRequestToNhin(PRPAIN201306UV02 request, AssertionType assertion) { <API key> auditLog = new <API key>(); auditLog.<API key>(request, assertion, NhincConstants.<API key>); } private void <API key>(MCCIIN000002UV01 resp, AssertionType assertion) { <API key> auditLog = new <API key>(); auditLog.auditAck(resp, assertion, NhincConstants.<API key>, NhincConstants.<API key>); } /** * Retrieves flag for audit enabling. If true, audit is enabled. * * @param <API key> * Properties File * @param <API key> * Property Name * @return Property Value */ protected boolean isAuditEnabled(String <API key>, String <API key>) { boolean propertyValue = false; try { PropertyAccessor propertyAccessor = PropertyAccessor.getInstance(); propertyValue = propertyAccessor.getPropertyBoolean( <API key>, <API key>); } catch (<API key> ex) { LOG.error(ex.getMessage()); } return propertyValue; } }
#!/usr/bin/env bash set -u #Detect undefined variable set -o pipefail #Return return code in pipeline fails # IFS=$'\n\t' #used in loop, Internal Field Separator #Target: Automatically Install & Update Tor Browser On GNU/Linux #Writer: MaxdSre #Update Time: # - Feb 16, 2017 11:43 +0800 # - May 16, 2017 17:20 Tue -0400 # - June 07, 2017 17:23 Wed +0800 # - July 25, 2017 09:42 Tue +0800 mktemp_format=${mktemp_format:-'TBTemp_XXXXXX'} # trap '' HUP #overlook SIGHUP when internet interrupted or terminal shell closed # trap '' INT #overlook SIGINT when enter Ctrl+C, QUIT is triggered by Ctrl+\ trap funcTrapINTQUIT INT QUIT funcTrapINTQUIT(){ rm -rf /tmp/"${mktemp_format%%_*}"* 2>/dev/null printf "Detect $(tput setaf 1)%s$(tput sgr0) or $(tput setaf 1)%s$(tput sgr0), begin to exit shell\n" "CTRL+C" "CTRL+\\" exit } umask 022 # temporarily change umask value to 022 # term_cols=$(tput cols) # term_lines=$(tput lines) readonly c_bold="$(tput bold)" readonly c_normal="$(tput sgr0)" # c_normal='\e[0m' # black 0, red 1, green 2, yellow 3, blue 4, magenta 5, cyan 6, gray 7 readonly c_red="${c_bold}$(tput setaf 1)" # c_red='\e[31;1m' readonly c_blue="$(tput setaf 4)" # c_blue='\e[34m' readonly official_site='https: readonly download_page="${official_site}/download/download.html" # Download Page readonly <API key>='https://dist.torproject.org' readonly download_version="linux64" # linux64 readonly download_language='en-US' # en-US, zh-TW readonly key_server='pgp.mit.edu' # pgp.mit.edu pool.sks-keyservers.net readonly gnupg_key='0x4E2C6E8793298290' software_fullname=${software_fullname:-'Tor Browser'} application_name=${application_name:-'TorBrowser'} bak_suffix=${bak_suffix:-'_bak'} # suffix word for file backup readonly temp_save_path='/tmp' # Save Path Of Downloaded Packages installation_dir="/opt/${application_name}" # Decompression & Installation Path Of Package readonly pixmaps_png_path="/usr/share/pixmaps/${application_name}.png" readonly <API key>="/usr/share/applications/${application_name}.desktop" is_existed=${is_existed:-0} # Default value is 0 check if system has installed Mozilla Thunderbird version_check=${version_check:-0} is_uninstall=${is_uninstall:-0} proxy_server=${proxy_server:-} funcHelpInfo(){ cat <<EOF ${c_blue}Usage: script [options] ... script | sudo bash -s -- [options] ... Installing / Updating Tor Browser On GNU/Linux! This script requires superuser privileges (eg. root, su). [available option] -h --help, show help info -c --check, check current stable release version -p [protocol:]ip:port --proxy host (http|https|socks4|socks5), default protocol is http -u --uninstall, uninstall software installed ${c_normal} EOF } while getopts "hcup:" option "$@"; do case "$option" in c ) version_check=1 ;; u ) is_uninstall=1 ;; p ) proxy_server="$OPTARG" ;; h|\? ) funcHelpInfo && exit ;; esac done start_time=$(date +'%s') # Start Time Of Operation funcExitStatement(){ local str="$*" [[ -n "$str" ]] && printf "%s\n" "$str" rm -rf /tmp/"${mktemp_format%%_*}"* 2>/dev/null exit } <API key>(){ # $? -- 0 is find, 1 is not find local name="$1" if [[ -n "$name" ]]; then local executing_path=${executing_path:-} executing_path=$(which "$name" 2> /dev/null || command -v "$name" 2> /dev/null) [[ -n "${executing_path}" ]] && return 0 || return 1 else return 1 fi } <API key>(){ # 1 - Check root or sudo privilege [[ "$UID" -ne 0 ]] && funcExitStatement "${c_red}Sorry${c_normal}: this script requires superuser privileges (eg. root, su)." # 2 - OS support check [[ -s /etc/os-release || -s /etc/SuSE-release || -s /etc/redhat-release || (-s /etc/debian_version && -s /etc/issue.net) ]] || funcExitStatement "${c_red}Sorry${c_normal}: this script doesn't support your system!" # 3 - bash version check ${BASH_VERSINFO[@]} ${BASH_VERSION} # bash --version | sed -r -n '1s@[^[:digit:]]*([[:digit:].]*).*@\1@p' [[ "${BASH_VERSINFO[0]}" -lt 4 ]] && funcExitStatement "${c_red}Sorry${c_normal}: this script need BASH version 4+, your current version is ${c_blue}${BASH_VERSION%%-*}${c_normal}." # CentOS/Fedora/Debian/Ubuntu: gnupg2, OpenSUSE: gpg2 if <API key> 'gpg2'; then gpg_tool='gpg2' elif <API key> 'gpg'; then gpg_tool='gpg' else funcExitStatement "${c_red}Error${c_normal}, no ${c_blue}gpg${c_normal} or ${c_blue}gpg2${c_normal} command found to verify GnuPG digit signature!" fi if [[ -s /etc/debian_version ]]; then <API key> 'dirmngr' || funcExitStatement "${c_red}Error${c_normal}, No ${c_blue}dirmngr${c_normal} command found" fi # CentOS/Fedora/OpenSUSE: xz Debian/Ubuntu: xz-utils <API key> 'xz' || funcExitStatement "${c_red}Error${c_normal}, No ${c_blue}xz${c_normal} command found, please install it (CentOS/OpenSUSE: xz Debian/Ubuntu: xz-utils)!" <API key> 'tar' || funcExitStatement "${c_red}Error${c_normal}, No ${c_blue}tar${c_normal} command found to decompress .tar.xz file!" # 4 - current login user detection #$USER exist && $SUDO_USER not exist, then use $USER [[ -n "${USER:-}" && -z "${SUDO_USER:-}" ]] && login_user="$USER" || login_user="$SUDO_USER" } <API key>(){ local l_item1="${1:-0}" # old val local l_item2="${2:-0}" # new val local l_operator=${3:-'<'} local l_output=${l_output:-0} if [[ -n "${l_item1}" && -n "${l_item2}" ]]; then local l_arr1=( $(echo "${l_item1}" | sed -r 's@\.@ @g') ) local l_arr2=( $(echo "${l_item2}" | sed -r 's@\.@ @g') ) local l_arr1_len=${l_arr1_len:-"${#l_arr1[@]}"} local l_arr2_len=${l_arr2_len:-"${#l_arr2[@]}"} local l_max_len=${l_max_len:-"${l_arr1_len}"} [[ "${l_arr1_len}" -lt "${l_arr2_len}" ]] && l_max_len="${l_arr2_len}" for (( i = 0; i < "${l_max_len}"; i++ )); do [[ "${l_arr1_len}" -lt $(( i+1 )) ]] && l_arr1[$i]=0 [[ "${l_arr2_len}" -lt $(( i+1 )) ]] && l_arr2[$i]=0 if [[ "${l_arr1[i]}" -lt "${l_arr2[i]}" ]]; then case "${l_operator}" in '>' ) l_output=0 ;; '<'|* ) l_output=1 ;; esac break elif [[ "${l_arr1[i]}" -gt "${l_arr2[i]}" ]]; then case "${l_operator}" in '>' ) l_output=1 ;; '<'|* ) l_output=0 ;; esac break else continue fi done fi echo "${l_output}" } <API key>(){ # CentOS: iproute Debian/OpenSUSE: iproute2 local gateway_ip=${gateway_ip:-} if <API key> 'ip'; then gateway_ip=$(ip route | awk 'match($1,/^default/){print $3}') elif <API key> 'netstat'; then gateway_ip=$(netstat -rn | awk 'match($1,/^Destination/){getline;print $2;exit}') else funcExitStatement "${c_red}Error${c_normal}: No ${c_blue}ip${c_normal} or ${c_blue}netstat${c_normal} command found, please install it!" fi ! ping -q -w 1 -c 1 "$gateway_ip" &> /dev/null && funcExitStatement "${c_red}Error${c_normal}: No internet connection detected, disable ICMP? please check it!" # Check Internet Connection } <API key>(){ local proxy_pattern="^((http|https|socks4|socks5):)?([0-9]{1,3}.){3}[0-9]{1,3}:[0-9]{1,5}$" proxy_server=${proxy_server:-} if [[ -n "${proxy_server}" ]]; then if [[ "${proxy_server}" =~ $proxy_pattern ]]; then local proxy_proto_pattern="^((http|https|socks4|socks5):)" if [[ "${proxy_server}" =~ $proxy_proto_pattern ]]; then local p_proto="${proxy_server%%:*}" local p_host="${proxy_server else local p_proto='http' local p_host="${proxy_server}" fi else funcExitStatement "${c_red}Error${c_normal}: please specify right proxy host addr like ${c_blue}[protocol:]ip:port${c_normal}!" fi fi local retry_times=${retry_times:-5} local retry_delay_time=${retry_delay_time:-1} local <API key>=${<API key>:-2} local referrer_page=${referrer_page:-'https://duckduckgo.com/?q=github'} # local user_agent=${user_agent:-'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6.4) AppleWebKit/537.29.20 (KHTML, like Gecko) Chrome/60.0.3030.92 Safari/537.29.20'} if <API key> 'curl'; then download_tool="curl -fsL --retry ${retry_times} --retry-delay ${retry_delay_time} --connect-timeout ${<API key>} --no-keepalive --referer ${referrer_page}" # curl -s URL -o /PATH/FILE -fsSL # --user-agent ${user_agent} if [[ -n "${proxy_server}" ]]; then local curl_version_no=${curl_version_no:-} curl_version_no=$(curl --version | sed -r -n '1s@.* ([[:digit:].]*) .*@\1@p') case "$p_proto" in http ) export http_proxy="${p_host}" ;; https ) export HTTPS_PROXY="${p_host}" ;; socks4 ) if [[ $(<API key> "${curl_version_no}" '7.21.7' '>') -eq 1 ]]; then download_tool="${download_tool} -x ${p_proto}a://${p_host}" else download_tool="${download_tool} --socks4a ${p_host}" fi ;; socks5 ) if [[ $(<API key> "${curl_version_no}" '7.21.7' '>') -eq 1 ]]; then download_tool="${download_tool} -x ${p_proto}h://${p_host}" else download_tool="${download_tool} --socks5-hostname ${p_host}" fi ;; * ) export http_proxy="${p_host}" ;; esac fi elif <API key> 'wget'; then download_tool="wget -qO- --tries=${retry_times} --waitretry=${retry_delay_time} --connect-timeout ${<API key>} --no-http-keep-alive --referer=${referrer_page}" # wget -q URL -O /PATH/FILE # --user-agent=${user_agent} # local version_no=$(wget --version | sed -r -n '1s@.* ([[:digit:].]*) .*@\1@p') if [[ -n "$proxy_server" ]]; then if [[ "$p_proto" == 'https' ]]; then export https_proxy="${p_host}" else export http_proxy="${p_host}" fi fi else funcExitStatement "${c_red}Error${c_normal}: can't find command ${c_blue}curl${c_normal} or ${c_blue}wget${c_normal}!" fi } <API key>(){ local l_item1="${1:-0}" # old val local l_item2="${2:-0}" # new val local l_operator=${3:-'<'} local l_output=${l_output:-0} if [[ -n "${l_item1}" && -n "${l_item2}" ]]; then local l_arr1=( $(echo "${l_item1}" | sed -r 's@\.@ @g') ) local l_arr2=( $(echo "${l_item2}" | sed -r 's@\.@ @g') ) local l_arr1_len=${l_arr1_len:-"${#l_arr1[@]}"} local l_arr2_len=${l_arr2_len:-"${#l_arr2[@]}"} local l_max_len=${l_max_len:-"${l_arr1_len}"} [[ "${l_arr1_len}" -lt "${l_arr2_len}" ]] && l_max_len="${l_arr2_len}" for (( i = 0; i < "${l_max_len}"; i++ )); do [[ "${l_arr1_len}" -lt $(( i+1 )) ]] && l_arr1[$i]=0 [[ "${l_arr2_len}" -lt $(( i+1 )) ]] && l_arr2[$i]=0 if [[ "${l_arr1[i]}" -lt "${l_arr2[i]}" ]]; then case "${l_operator}" in '>' ) l_output=0 ;; '<'|* ) l_output=1 ;; esac break elif [[ "${l_arr1[i]}" -gt "${l_arr2[i]}" ]]; then case "${l_operator}" in '>' ) l_output=1 ;; '<'|* ) l_output=0 ;; esac break else continue fi done fi echo "${l_output}" } <API key>(){ if [[ -f "${installation_dir}/start-tor-browser.desktop" ]]; then is_existed=1 <API key>=$(sed -n -r '1,/^$/s@^Tor Browser (.*) --.*@\1@p' "${installation_dir}/Browser/TorBrowser/Docs/ChangeLog.txt") fi } <API key>(){ download_page_html=$(mktemp -t "${mktemp_format}") $download_tool "${download_page}" > "${download_page_html}" [[ -s "${download_page_html}" ]] || funcExitStatement "${c_red}Sorry${c_normal}: fail to download html info from page ${c_blue}${download_page}${c_normal}!" # release version & release date <API key>=$(sed -r -n '/Linux, BSD/{s@^.*Version[[:space:]]*([^[:space:]]+)[[:space:]]*\(([^\)]+)\).*$@\1 \2@g;p}' "${download_page_html}") # 7.0.11|2017-12-09 if [[ -n "${<API key>}" ]]; then <API key>="${<API key>%% *}" release_date_online="${<API key> else funcExitStatement "${c_red}Sorry${c_normal}: fail to extract latest release version and release date!" fi # pack file & sign file <API key>=$(sed -r -n '/linux64-/{s@^.*href="\.+/dist/([^"]+)">.*$@\1@g;p}' "${download_page_html}" | sed ':a;N;$!ba;s@\n@ @g;') # torbrowser/7.0.11/<API key>.0.11_en-US.tar.xz|torbrowser/7.0.11/<API key>.0.11_en-US.tar.xz.asc if [[ -n "${<API key>}" ]]; then pack_download_link="${<API key>}/${<API key>%% *}" # actual package file download link pack_name=${pack_download_link##*/} # package name <API key>="${<API key>}/${<API key>##* }" # actual GnuPG file download link sign_file_name=${<API key>##*/} # signature file else funcExitStatement "${c_red}Sorry${c_normal}: fail to extract release version and date!" fi if [[ "${version_check}" -eq 1 ]]; then if [[ "${is_existed}" -eq 1 ]]; then funcExitStatement "Local existed version is ${c_red}${<API key>}${c_normal}, Latest version online is ${c_red}${<API key>}${c_normal} (${c_blue}${release_date_online}${c_normal})!" else funcExitStatement "Latest version online (${c_red}${<API key>}${c_normal}), Release date ($c_red${release_date_online}$c_normal)!" fi fi if [[ "${is_existed}" -eq 1 ]]; then if [[ "${<API key>}" == "${<API key>}" ]]; then funcExitStatement "Latest version (${c_red}${<API key>}${c_normal}) has been existed in your system!" elif [[ $(<API key> "${<API key>}" "${<API key>}" '<') -eq 1 ]]; then printf "Existed version local (${c_red}%s${c_normal}) < Latest version online (${c_red}%s${c_normal})!\n" "${<API key>}" "${<API key>}" fi else printf "No %s find in your system!\n" "${software_fullname}" fi } <API key>(){ [[ "${is_existed}" -eq 1 ]] || funcExitStatement "${c_blue}Note${c_normal}: no ${software_fullname} is found in your system!" [[ -f "${pixmaps_png_path}" ]] && rm -f "${pixmaps_png_path}" [[ -f "${<API key>}" ]] && rm -f "${<API key>}" [[ -d "${installation_dir}" ]] && rm -rf "${installation_dir}" [[ -d "${installation_dir}${bak_suffix}" ]] && rm -rf "${installation_dir}${bak_suffix}" [[ -d "${installation_dir}" ]] || funcExitStatement "${software_fullname} (v ${c_red}${<API key>}${c_normal}) is successfully removed from your system!" } <API key>(){ printf "Begin to download latest version ${c_red}%s${c_normal}, just be patient!\n" "${<API key>}" # Download the latest version while two versions compared different pack_save_path="${temp_save_path}/${pack_name}" sign_file_save_path="${temp_save_path}/${sign_file_name}" [[ -f "${pack_save_path}" ]] && rm -f "${pack_save_path}" [[ -f "${sign_file_save_path}" ]] && rm -f "${sign_file_save_path}" $download_tool "${pack_download_link}" > "${pack_save_path}" # download pack suffix with .tar.xz $download_tool "${<API key>}" > "${sign_file_save_path}" # download GnuPG singature file suffix with .tar.xz.asc # - Verify Signature $gpg_tool --list-key "${gnupg_key}" &> /dev/null # Check GnuPG key if installed or not, it not, install it if [[ $? -gt 0 ]]; then $gpg_tool --keyserver "${key_server}" --recv-keys "${gnupg_key}" &> /dev/null fi temp_signinfo_file=$(mktemp -t "${mktemp_format}") $gpg_tool --verify "${sign_file_save_path}" "${pack_save_path}" 2> "${temp_signinfo_file}" local verify_result=${verify_result:-} verify_result=$(sed -n '/Good signature /p' "${temp_signinfo_file}") [[ -f "${temp_signinfo_file}" ]] && rm -f "${temp_signinfo_file}" if [[ "${verify_result}" == '' ]]; then [[ -f "${pack_save_path}" ]] && rm -f "${pack_save_path}" [[ -f "${sign_file_save_path}" ]] && rm -f "${sign_file_save_path}" funcExitStatement "${c_red}Sorry${c_normal}: package GnuPG signature verified faily, please try it later again!" else printf "GnuPG signature verified info:\n${c_blue}%s${c_normal}\n" "$verify_result" fi # - Decompress local <API key>="${installation_dir}${bak_suffix}" [[ -d "${<API key>}" ]] && rm -rf "${<API key>}" [[ -d "${installation_dir}" ]] && mv "${installation_dir}" "${<API key>}" # Backup Installation Directory [[ -d "${installation_dir}" ]] || mkdir -p "${installation_dir}" # Create Installation Directory tar xf "${pack_save_path}" -C "${installation_dir}" --strip-components=1 # Decompress To Target Directory chown -R "${login_user}" "${installation_dir}" local <API key>=${<API key>:-} local version_file="${installation_dir}/Browser/TorBrowser/Docs/ChangeLog.txt" [[ -s "${version_file}" ]] && <API key>=$(sed -n -r '1,/^$/s@^Tor Browser[[:space:]]*([[:digit:].]+)[[:space:]]*.*@\1@gp' "${version_file}") # Just Installed Version In System [[ -f "${pack_save_path}" ]] && rm -f "${pack_save_path}" [[ -f "${sign_file_save_path}" ]] && rm -f "${sign_file_save_path}" if [[ "${<API key>}" != "${<API key>}" ]]; then [[ -d "${installation_dir}" ]] && rm -rf "${installation_dir}" if [[ "${is_existed}" -eq 1 ]]; then mv "${<API key>}" "${installation_dir}" funcExitStatement "${c_red}Sorry${c_normal}: ${c_blue}update${c_normal} operation is faily. ${software_fullname} has been rolled back to the former version!" else funcExitStatement "${c_red}Sorry${c_normal}: ${c_blue}install${c_normal} operation is faily!" fi else [[ -f "${pixmaps_png_path}" ]] && rm -f "${pixmaps_png_path}" [[ -f "${<API key>}" ]] && rm -f "${<API key>}" [[ -d "${<API key>}" ]] && rm -rf "${<API key>}" fi } <API key>(){ tee "${<API key>}" &> /dev/null <<-'EOF' [Desktop Entry] Encoding=UTF-8 Name=Tor Browser GenericName[en]=Web Browser Comment=Tor Browser is +1 for privacy and -1 for mass surveillance Type=Application Categories=Network;WebBrowser;Security; Exec=sh -c 'installation_dir/Browser/start-tor-browser --detach' dummy %k <API key>=installation_dir/Browser/start-tor-browser --detach Icon=application_name.png Terminal=false StartupWMClass=Tor Browser MimeType=text/html;text/xml;application/xhtml+xml;application/vnd.mozilla.xul+xml;text/mml; EOF sed -i -r 's@application_name@'"$application_name"'@g' "${<API key>}" sed -i -r 's@installation_dir@'"$installation_dir"'@g' "${<API key>}" } <API key>(){ if [[ -d '/usr/share/applications' ]]; then [[ -f "${installation_dir}/Browser/browser/chrome/icons/default/default48.png" ]] && ln -sf "${installation_dir}/Browser/browser/chrome/icons/default/default48.png" "${pixmaps_png_path}" <API key> fi if [[ "$is_existed" -eq 1 ]]; then printf "%s was updated to version ${c_red}%s${c_normal} successfully!\n" "${software_fullname}" "${<API key>}" else printf "Installing %s version ${c_red}%s${c_normal} successfully!\n" "${software_fullname}" "${<API key>}" fi } <API key>(){ finish_time=$(date +'%s') # End Time Of Operation total_time_cost=$((<API key>)) # Total Time Of Operation funcExitStatement "Total time cost is ${c_red}${total_time_cost}${c_normal} seconds!" } <API key> <API key> <API key> <API key> if [[ "${is_uninstall}" -eq 1 ]]; then <API key> else <API key> <API key> <API key> <API key> fi # trap "commands" EXIT # execute command when exit from shell funcTrapEXIT(){ rm -rf /tmp/"${mktemp_format%%_*}"* 2>/dev/null unset software_fullname unset application_name unset bak_suffix unset installation_dir unset is_existed unset version_check unset is_uninstall unset proxy_server unset start_time unset finish_time unset total_time_cost } trap funcTrapEXIT EXIT # Script End
package com.psddev.dari.db; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.psddev.dari.util.Settings; public interface Recordable { /** * Returns the state {@linkplain State#linkObject linked} to this * instance. */ public State getState(); /** * Sets the state {@linkplain State#linkObject linked} to this * instance. This method must also {@linkplain State#unlinkObject * unlink} the state previously set. */ public void setState(State state); /** * Returns an instance of the given {@code modificationClass} linked * to this object. */ public <T> T as(Class<T> modificationClass); /** * Specifies whether the target type is abstract and can't be used * to create a concrete instance. */ @Documented @ObjectType.<API key>(AbstractProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Abstract { boolean value() default true; } /** * Specifies the JavaBeans property name that can be used to access an * instance of the target type as a modification. * * <p>For example, given the following modification:</p> * * <blockquote><pre><code data-type="java"> *{@literal @}Modification.BeanProperty("css") *class CustomCss extends Modification&lt;Object&gt; { * public String getBodyClass() { * return getOriginalObject().getClass().getName().replace('.', '_'); * } *} * </code></pre></blockquote> * * * <p>The following becomes valid and will invoke the {@code getBodyClass} * above, even if the {@code content} object doesn't define a * {@code getCss} method.</p> * * <blockquote><pre><code data-type="jsp"> *${content.css.bodyClass} * </code></pre></blockquote> */ @Documented @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface BeanProperty { String value(); } @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface <API key> { } @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface BootstrapPackages { String[] value(); Class<?>[] depends() default { }; } @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface <API key> { Class<?>[] groups(); String uniqueKey(); } /** Specifies the maximum number of items allowed in the target field. */ @Documented @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface CollectionMaximum { int value(); } /** Specifies the minimum number of items required in the target field. */ @Documented @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface CollectionMinimum { int value(); } /** * Specifies whether the target field is always denormalized within * another instance. */ @Documented @Inherited @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE }) public @interface Denormalized { boolean value() default true; String[] fields() default { }; } /** Specifies the target's display name. */ @Documented @ObjectField.<API key>(<API key>.class) @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE, ElementType.METHOD }) public @interface DisplayName { String value(); } /** * Specifies whether the target data is always embedded within * another instance. */ @Documented @Inherited @ObjectField.<API key>(EmbeddedProcessor.class) @ObjectType.<API key>(EmbeddedProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE, ElementType.METHOD }) public @interface Embedded { boolean value() default true; } /** * Specifies the prefix for the internal names of all fields in the * target type. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface <API key> { String value(); } @Documented @Inherited @ObjectField.<API key>(GroupsProcessor.class) @ObjectType.<API key>(GroupsProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE }) public @interface Groups { String[] value(); } /** Specifies whether the target field is ignored. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface Ignored { boolean value() default true; } /** Specifies whether the target field value is indexed. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface Indexed { String[] extraFields() default { }; boolean unique() default false; boolean caseSensitive() default false; boolean visibility() default false; /** @deprecated Use {@link #unique} instead. */ @Deprecated boolean isUnique() default false; } /** Specifies the target's internal name. */ @Documented @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.TYPE, ElementType.METHOD }) public @interface InternalName { String value(); } /** * Specifies the name of the field in the junction query that should be * used to populate the target field. */ @Documented @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface JunctionField { String value(); } /** * Specifies the name of the position field in the junction query that * should be used to order the collection in the target field. */ @Documented @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface <API key> { String value(); } /** * Specifies the field names that are used to retrieve the * labels of the objects represented by the target type. */ @Documented @Inherited @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface LabelFields { String[] value(); } /** * Specifies either the maximum numeric value or string length of the * target field. */ @Documented @ObjectField.<API key>(MaximumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Maximum { double value(); } /** Specifies the field the metric is recorded in. */ @Documented @Retention(RetentionPolicy.RUNTIME) @ObjectField.<API key>(<API key>.class) @Target(ElementType.FIELD) public @interface MetricValue { Class<? extends MetricInterval> interval() default MetricInterval.Hourly.class; String intervalSetting() default ""; } /** * Specifies either the minimum numeric value or string length of the * target field. */ @Documented @ObjectField.<API key>(MinimumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Minimum { double value(); } /** * Specifies the field name used to retrieve the previews of the * objects represented by the target type. */ @Documented @Inherited @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface PreviewField { String value(); } /** * Specifies that the values in the target collection field should * remain raw (not reference resolved). */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) @ObjectField.<API key>(RawProcessor.class) @interface Raw { boolean value() default true; } /** Specifies how the method index should be updated. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) @ObjectField.<API key>(<API key>.class) public @interface Recalculate { public Class<? extends RecalculationDelay> delay() default RecalculationDelay.Hour.class; public String metric() default ""; public boolean immediate() default false; } /** * Specifies the regular expression pattern that the target field value * must match. */ @Documented @ObjectField.<API key>(RegexProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Regex { String value(); } /** Specifies whether the target field value is required. */ @Documented @ObjectField.<API key>(RequiredProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Required { boolean value() default true; } /** Specifies the source database class for the target type. */ @Documented @Inherited @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SourceDatabaseClass { Class<? extends Database> value(); } /** Specifies the source database name for the target type. */ @Documented @Inherited @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SourceDatabaseName { String value(); } /** * Specifies the step between the minimum and the maximum that the * target field must match. */ @Documented @ObjectField.<API key>(StepProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Step { double value(); } /** * Specifies the processor class(es) to run after the type is initialized. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface <API key> { Class<? extends ObjectType.PostProcessor>[] value(); } /** Specifies the valid types for the target field value. */ @Documented @ObjectField.<API key>(TypesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Types { Class<?>[] value(); } /** Specifies the valid values for the target field value. */ @Documented @ObjectField.<API key>(ValuesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface Values { String[] value(); } @Documented @Inherited @ObjectField.<API key>(WhereProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Where { String value(); } /** @deprecated Use {@link Denormalized} instead. */ @Deprecated @Documented @Inherited @ObjectType.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DenormalizedFields { String[] value(); } /** @deprecated Use {@link CollectionMaximum} instead. */ @Deprecated @Documented @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface <API key> { int value(); } /** @deprecated Use {@link CollectionMinimum} instead. */ @Deprecated @Documented @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface <API key> { int value(); } /** @deprecated Use {@link DisplayName} instead. */ @Deprecated @Documented @ObjectField.<API key>(<API key>.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldDisplayName { String value(); } /** @deprecated Use {@link Embedded} instead. */ @Deprecated @Documented @ObjectField.<API key>(EmbeddedProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldEmbedded { boolean value() default true; } /** @deprecated Use {@link Modification} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldGlobal { } /** @deprecated Use {@link Ignored} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldIgnored { } /** @deprecated Use {@link Indexed} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldIndexed { String[] extraFields() default { }; boolean isUnique() default false; } /** @deprecated Use {@link InternalName} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface FieldInternalName { String value(); } /** @deprecated Use {@link FieldTypes} instead. */ @Deprecated @Documented @ObjectField.<API key>(TypesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldItemTypes { Class<?>[] value(); } /** @deprecated Use {@link Maximum} instead. */ @Deprecated @Documented @ObjectField.<API key>(MaximumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldMaximum { double value(); } /** @deprecated Use {@link Minimum} instead. */ @Deprecated @Documented @ObjectField.<API key>(MinimumProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldMinimum { double value(); } /** @deprecated Use {@link Regex} instead. */ @Deprecated @Documented @ObjectField.<API key>(RegexProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldPattern { String value(); } /** @deprecated Use {@link Required} instead. */ @Deprecated @Documented @ObjectField.<API key>(RequiredProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldRequired { boolean value() default true; } /** @deprecated Use {@link Step} instead. */ @Deprecated @Documented @ObjectField.<API key>(StepProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldStep { double value(); } /** @deprecated Use {@link Types} instead. */ @Deprecated @Documented @ObjectField.<API key>(TypesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldTypes { Class<?>[] value(); } /** @deprecated Use {@link FieldIndexed} with {@code isUnique} instead. */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldUnique { } /** @deprecated Use {@link Values} instead. */ @Deprecated @Documented @ObjectField.<API key>(ValuesProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldValues { String[] value(); } } class AbstractProcessor implements ObjectType.AnnotationProcessor<Recordable.Abstract> { @Override public void process(ObjectType type, Recordable.Abstract annotation) { type.setAbstract(annotation.value()); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.BeanProperty> { @Override public void process(ObjectType type, Recordable.BeanProperty annotation) { if (type.getGroups().contains(Modification.class.getName())) { type.setJavaBeanProperty(annotation.value()); } } } class <API key> implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { if (field.<API key>()) { field.<API key>(annotation instanceof Recordable.<API key> ? ((Recordable.<API key>) annotation).value() : ((Recordable.CollectionMaximum) annotation).value()); } else { throw new <API key>(String.format( "[%s] annotation cannot be applied to a non-collection field!", annotation.getClass().getName())); } } } class <API key> implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { if (field.<API key>()) { field.<API key>(annotation instanceof Recordable.<API key> ? ((Recordable.<API key>) annotation).value() : ((Recordable.CollectionMinimum) annotation).value()); } else { throw new <API key>(String.format( "[%s] annotation cannot be applied to a non-collection field!", annotation.getClass().getName())); } } } class <API key> implements ObjectField.AnnotationProcessor<Recordable.Denormalized>, ObjectType.AnnotationProcessor<Recordable.Denormalized> { @Override public void process(ObjectType type, ObjectField field, Recordable.Denormalized annotation) { field.setDenormalized(annotation.value()); Collections.addAll(field.<API key>(), annotation.fields()); } @Override public void process(ObjectType type, Recordable.Denormalized annotation) { type.setDenormalized(annotation.value()); Collections.addAll(type.<API key>(), annotation.fields()); } } class <API key> implements ObjectType.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, Annotation annotation) { type.setDenormalized(true); Collections.addAll(type.<API key>(), ((Recordable.DenormalizedFields) annotation).value()); } } class <API key> implements ObjectField.AnnotationProcessor<Annotation>, ObjectType.AnnotationProcessor<Recordable.DisplayName> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setDisplayName(annotation instanceof Recordable.FieldDisplayName ? ((Recordable.FieldDisplayName) annotation).value() : ((Recordable.DisplayName) annotation).value()); } @Override public void process(ObjectType type, Recordable.DisplayName annotation) { Class<?> objectClass = type.getObjectClass(); if (objectClass != null) { Recordable.DisplayName displayName = objectClass.getAnnotation(Recordable.DisplayName.class); // Only sets the display name if the annotation came from the type being modified. if (displayName != null && displayName.value() != null && displayName.value().equals(annotation.value())) { type.setDisplayName(annotation.value()); } } } } class EmbeddedProcessor implements ObjectField.AnnotationProcessor<Annotation>, ObjectType.AnnotationProcessor<Recordable.Embedded> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setEmbedded(annotation instanceof Recordable.FieldEmbedded ? ((Recordable.FieldEmbedded) annotation).value() : ((Recordable.Embedded) annotation).value()); } @Override public void process(ObjectType type, Recordable.Embedded annotation) { type.setEmbedded(annotation.value()); } } class GroupsProcessor implements ObjectField.AnnotationProcessor<Recordable.Groups>, ObjectType.AnnotationProcessor<Recordable.Groups> { @Override public void process(ObjectType type, ObjectField field, Recordable.Groups annotation) { Collections.addAll(field.getGroups(), annotation.value()); } @Override public void process(ObjectType type, Recordable.Groups annotation) { Collections.addAll(type.getGroups(), annotation.value()); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.InternalName> { @Override public void process(ObjectType type, Recordable.InternalName annotation) { type.setInternalName(annotation.value()); } } class RawProcessor implements ObjectField.AnnotationProcessor<Recordable.Raw> { @Override public void process(ObjectType type, ObjectField field, Recordable.Raw annotation) { field.setRaw(annotation.value()); } } class <API key> implements ObjectField.AnnotationProcessor<Recordable.Recalculate> { @Override public void process(ObjectType type, ObjectField field, Recordable.Recalculate annotation) { if (field instanceof ObjectMethod) { <API key> fieldData = ((ObjectMethod) field).as(<API key>.class); fieldData.setDelayClass(annotation.delay()); fieldData.setImmediate(annotation.immediate()); if (annotation.metric() != null && !"".equals(annotation.metric())) { fieldData.setMetricFieldName(annotation.metric()); } else if (annotation.immediate()) { throw new <API key>("immediate = true requires a metric!"); } } } } class <API key> implements ObjectField.AnnotationProcessor<Recordable.JunctionField> { @Override public void process(ObjectType type, ObjectField field, Recordable.JunctionField annotation) { field.setJunctionField(annotation.value()); } } class <API key> implements ObjectField.AnnotationProcessor<Recordable.<API key>> { @Override public void process(ObjectType type, ObjectField field, Recordable.<API key> annotation) { field.<API key>(annotation.value()); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.LabelFields> { @Override public void process(ObjectType type, Recordable.LabelFields annotation) { List<String> labelFields = type.getLabelFields(); for (String field : annotation.value()) { if (!labelFields.contains(field)) { labelFields.add(field); } } } } class MaximumProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setMaximum(annotation instanceof Recordable.FieldMaximum ? ((Recordable.FieldMaximum) annotation).value() : ((Recordable.Maximum) annotation).value()); } } class <API key> implements ObjectField.AnnotationProcessor<Recordable.MetricValue> { @Override public void process(ObjectType type, ObjectField field, Recordable.MetricValue annotation) { SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class); MetricAccess.FieldData metricFieldData = field.as(MetricAccess.FieldData.class); fieldData.setIndexTable(MetricAccess.METRIC_TABLE); fieldData.<API key>(MetricAccess.METRIC_DATA_FIELD); fieldData.<API key>(false); fieldData.setIndexTableSource(true); fieldData.<API key>(true); metricFieldData.<API key>(annotation.interval()); if (!"".equals(annotation.intervalSetting())) { String settingValue = Settings.getOrDefault(String.class, annotation.intervalSetting(), null); if (settingValue != null) { metricFieldData.<API key>(settingValue); } } metricFieldData.setMetricValue(true); } } class MinimumProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setMinimum(annotation instanceof Recordable.FieldMinimum ? ((Recordable.FieldMinimum) annotation).value() : ((Recordable.Minimum) annotation).value()); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.PreviewField> { @Override public void process(ObjectType type, Recordable.PreviewField annotation) { type.setPreviewField(annotation.value()); } } class RegexProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setPattern(annotation instanceof Recordable.FieldPattern ? ((Recordable.FieldPattern) annotation).value() : ((Recordable.Regex) annotation).value()); } } class RequiredProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setRequired(annotation instanceof Recordable.FieldRequired ? ((Recordable.FieldRequired) annotation).value() : ((Recordable.Required) annotation).value()); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.SourceDatabaseClass> { @Override public void process(ObjectType type, Recordable.SourceDatabaseClass annotation) { type.<API key>(annotation.value().getName()); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.SourceDatabaseName> { @Override public void process(ObjectType type, Recordable.SourceDatabaseName annotation) { type.<API key>(annotation.value()); } } class StepProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { field.setStep(annotation instanceof Recordable.FieldStep ? ((Recordable.FieldStep) annotation).value() : ((Recordable.Step) annotation).value()); } } class TypesProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { Set<ObjectType> types = new LinkedHashSet<ObjectType>(); DatabaseEnvironment environment = field.getParent().getEnvironment(); for (Class<?> typeClass : annotation instanceof Recordable.FieldTypes ? ((Recordable.FieldTypes) annotation).value() : annotation instanceof Recordable.FieldItemTypes ? ((Recordable.FieldItemTypes) annotation).value() : ((Recordable.Types) annotation).value()) { types.add(environment.getTypeByClass(typeClass)); } field.setTypes(types); } } class ValuesProcessor implements ObjectField.AnnotationProcessor<Annotation> { @Override @SuppressWarnings({ "all", "deprecation" }) public void process(ObjectType type, ObjectField field, Annotation annotation) { Set<ObjectField.Value> values = new LinkedHashSet<ObjectField.Value>(); for (String valueValue : annotation instanceof Recordable.FieldValues ? ((Recordable.FieldValues) annotation).value() : ((Recordable.Values) annotation).value()) { ObjectField.Value value = new ObjectField.Value(); value.setValue(valueValue); values.add(value); } field.setValues(values); } } class WhereProcessor implements ObjectField.AnnotationProcessor<Recordable.Where> { @Override public void process(ObjectType type, ObjectField field, Recordable.Where annotation) { field.setPredicate(annotation.value()); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.BootstrapPackages> { @Override public void process(ObjectType type, Recordable.BootstrapPackages annotation) { Set<String> packageNames = new LinkedHashSet<String>(); for (String packageName : annotation.value()) { packageNames.add(packageName); for (Class<?> dependency : annotation.depends()) { ObjectType dependentType = type.getEnvironment().getTypeByClass(dependency); if (dependentType != null) { dependentType.as(BootstrapPackage.TypeData.class).getPackageNames().add(packageName); } } } type.as(BootstrapPackage.TypeData.class).setPackageNames(packageNames); } } class <API key> implements ObjectType.AnnotationProcessor<Recordable.<API key>> { @Override public void process(ObjectType type, Recordable.<API key> annotation) { Set<String> typeMappableGroups = new LinkedHashSet<String>(); for (Class<?> group : annotation.groups()) { typeMappableGroups.add(group.getName()); } type.as(BootstrapPackage.TypeData.class).<API key>(typeMappableGroups); type.as(BootstrapPackage.TypeData.class).<API key>(annotation.uniqueKey()); } } class <API key> implements ObjectField.AnnotationProcessor<Recordable.<API key>> { @Override public void process(ObjectType type, ObjectField field, Recordable.<API key> annotation) { type.as(BootstrapPackage.TypeData.class).<API key>().add(field.getInternalName()); } }
// Use of this source code is governed by a BSD-style // Bridge package to expose http internals to tests in the http_test // package. package http import ( "net" "net/url" "time" ) func NewLoggingConn(baseName string, c net.Conn) net.Conn { return newLoggingConn(baseName, c) } var ExportAppendTime = appendTime func (t *Transport) <API key>() int { t.reqMu.Lock() defer t.reqMu.Unlock() return len(t.reqCanceler) } func (t *Transport) <API key>() (keys []string) { keys = make([]string, 0) t.idleMu.Lock() defer t.idleMu.Unlock() if t.idleConn == nil { return } for key := range t.idleConn { keys = append(keys, key.String()) } return } func (t *Transport) <API key>(cacheKey string) int { t.idleMu.Lock() defer t.idleMu.Unlock() if t.idleConn == nil { return 0 } for k, conns := range t.idleConn { if k.String() == cacheKey { return len(conns) } } return 0 } func (t *Transport) <API key>() int { t.idleMu.Lock() defer t.idleMu.Unlock() return len(t.idleConnCh) } func (t *Transport) IsIdleForTesting() bool { t.idleMu.Lock() defer t.idleMu.Unlock() return t.wantIdle } func (t *Transport) <API key>() { t.getIdleConnCh(connectMethod{nil, "http", "example.com"}) } func (t *Transport) PutIdleTestConn() bool { c, _ := net.Pipe() return t.putIdleConn(&persistConn{ t: t, conn: c, // dummy closech: make(chan struct{}), // so it can be closed cacheKey: connectMethodKey{"", "http", "example.com"}, }) } func <API key>(f func()) { <API key> = f } func <API key>(handler Handler, ch <-chan time.Time) Handler { f := func() <-chan time.Time { return ch } return &timeoutHandler{handler, f, ""} } func <API key>() { httpProxyEnv.reset() httpsProxyEnv.reset() noProxyEnv.reset() } var DefaultUserAgent = defaultUserAgent func ExportRefererForURL(lastReq, newReq *url.URL) string { return refererForURL(lastReq, newReq) } // SetPendingDialHooks sets the hooks that run before and after handling // pending dials. func SetPendingDialHooks(before, after func()) { prePendingDial, postPendingDial = before, after } var ExportServerNewConn = (*Server).newConn var <API key> = (*conn).closeWriteAndWait
/** * @file vcs_defs.h * Defines and definitions within the vcs package */ #ifndef VCS_DEFS_H #define VCS_DEFS_H namespace Cantera { /*! * ERROR CODES */ #define VCS_SUCCESS 0 #define VCS_NOMEMORY 1 #define <API key> -1 #define <API key> -2 #define VCS_PUB_BAD -3 #define <API key> -4 #define VCS_FAILED_LOOKUP -5 #define VCS_MP_FAIL -6 /*! * @name Type of the underlying equilibrium solve * @{ */ //! Current, it is always done holding T and P constant. #define VCS_PROBTYPE_TP 0 /*! * @name Sizes of Phases and Cutoff Mole Numbers * * All size parameters are listed here * @{ */ //! Cutoff relative mole fraction value, below which species are deleted from //! the equilibrium problem. #ifndef <API key> #define <API key> 1.0e-64 #endif //! Cutoff relative mole number value, below which species are deleted from the //! equilibrium problem. #ifndef <API key> #define <API key> 1.0e-140 #endif //! Relative value of multiphase species mole number for a multiphase species //! which is small. #ifndef <API key> #define <API key> 1.0e-25 #endif //! Cutoff relative moles below which a phase is deleted //! from the equilibrium problem. #ifndef <API key> #define <API key> 1.0e-13 #endif //! Relative mole number of species in a phase that is created We want this to //! be comfortably larger than the <API key> value so that the //! phase can have a chance to survive. #ifndef <API key> #define <API key> 1.0e-11 #endif //! Cutoff moles below which a phase or species which comprises the bulk of an //! element's total concentration is deleted. #ifndef <API key> #define <API key> 1.0e-280 #endif //! Maximum steps in the inner loop #ifndef VCS_MAXSTEPS #define VCS_MAXSTEPS 50000 #endif /*! * @name State of Dimensional Units for Gibbs free energies * @{ */ //! nondimensional #define <API key> 1 //! dimensioned #define VCS_DIMENSIONAL_G 0 //! @name Species Categories used during the iteration /*! * These defines are valid values for spStatus() */ //! Species is a component which can never be nonzero because of a //! stoichiometric constraint /*! * An example of this would be a species that contains Ni. But, * the amount of Ni elements is exactly zero. */ #define <API key> 3 //! Species is a component which can be nonzero #define <API key> 2 //! Species is a major species /*! * A major species is either a species in a multicomponent phase with * significant concentration or it's a Stoich Phase */ #define VCS_SPECIES_MAJOR 1 //! Species is a major species /*! * A major species is either a species in a multicomponent phase with * significant concentration or it's a Stoich Phase */ #define VCS_SPECIES_MINOR 0 //! Species lies in a multicomponent phase, with a small phase concentration /*! * The species lies in a multicomponent phase that exists. It concentration is * currently very low, necessitating a different method of calculation. */ #define VCS_SPECIES_SMALLMS -1 //! Species lies in a multicomponent phase with concentration zero /*! * The species lies in a multicomponent phase which currently doesn't exist. * It concentration is currently zero. */ #define <API key> -2 //! Species is a SS phase, that is currently zeroed out. /*! * The species lies in a single-species phase which is currently zeroed out. */ #define <API key> -3 //! Species has such a small mole fraction it is deleted even though its //! phase may possibly exist. /*! * The species is believed to have such a small mole fraction that it best to * throw the calculation of it out. It will be added back in at the end of the * calculation. */ #define VCS_SPECIES_DELETED -4 //! Species refers to an electron in the metal. /*! * The unknown is equal to the electric potential of the phase in which it * exists. */ #define <API key> -5 //! Species lies in a multicomponent phase that is zeroed atm /*! * The species lies in a multicomponent phase that is currently deleted and will * stay deleted due to a choice from a higher level. These species will formally * always have zero mole numbers in the solution vector. */ #define <API key> -6 //! Species lies in a multicomponent phase that is active, but species //! concentration is zero /*! * The species lies in a multicomponent phase which currently does exist. It * concentration is currently identically zero, though the phase exists. Note, * this is a temporary condition that exists at the start of an equilibrium * problem. The species is soon "birthed" or "deleted". */ #define <API key> -7 //! Species lies in a multicomponent phase that is active, //! but species concentration is zero due to stoich constraint /*! * The species lies in a multicomponent phase which currently does exist. Its * concentration is currently identically zero, though the phase exists. This is * a permanent condition due to stoich constraints. * * An example of this would be a species that contains Ni. But, the amount of Ni * elements in the current problem statement is exactly zero. */ #define <API key> -8 //! @name Phase Categories used during the iteration /*! * These defines are valid values for the phase existence flag */ //! Always exists because it contains inerts which can't exist in any other phase #define <API key> 3 //! Phase is a normal phase that currently exists #define VCS_PHASE_EXIST_YES 2 //! Phase is a normal phase that exists in a small concentration /*! * Concentration is so small that it must be calculated using an alternate * method */ #define <API key> 1 //! Phase doesn't currently exist in the mixture #define VCS_PHASE_EXIST_NO 0 //! Phase currently is zeroed due to a programmatic issue /*! * We zero phases because we want to follow phase stability boundaries. */ #define <API key> -6 #define VCS_UNITS_KCALMOL -1 #define VCS_UNITS_UNITLESS 0 #define VCS_UNITS_KJMOL 1 #define VCS_UNITS_KELVIN 2 #define VCS_UNITS_MKS 3 /*! * @name Types of Element Constraint Equations * * There may be several different types of element constraints handled by the * equilibrium program. These defines are used to assign each constraint to one * category. * @{ */ //! An element constraint that is current turned off #define <API key> -1 //! Normal element constraint consisting of positive coefficients for the //! formula matrix. /*! * All species have positive coefficients within the formula matrix. With this * constraint, we may employ various strategies to handle small values of the * element number successfully. */ #define <API key> 0 //! This refers to conservation of electrons /*! * Electrons may have positive or negative values in the Formula matrix. */ #define <API key> 1 //! This refers to a charge neutrality of a single phase /*! * Charge neutrality may have positive or negative values in the Formula matrix. */ #define <API key> 2 //! Constraint associated with maintaining a fixed lattice stoichiometry in the //! solids /*! * The constraint may have positive or negative values. The lattice 0 species * will have negative values while higher lattices will have positive values */ #define <API key> 3 //! Constraint associated with maintaining frozen kinetic equilibria in //! some functional groups within molecules /*! * We seek here to say that some functional groups or ionic states should be * treated as if they are separate elements given the time scale of the problem. * This will be abs positive constraint. We have not implemented any examples * yet. A requirement will be that we must be able to add and subtract these * constraints. */ #define <API key> 4 //! Constraint associated with the maintenance of a surface phase /*! * We don't have any examples of this yet either. However, surfaces only exist * because they are interfaces between bulk layers. If we want to treat surfaces * within thermodynamic systems we must come up with a way to constrain their * total number. */ #define <API key> 5 //! Other constraint equations /*! * currently there are none */ #define <API key> 6 /*! * @name Types of Species Unknowns in the problem * @{ */ //! Unknown refers to mole number of a single species #define <API key> 0 //! Unknown refers to the voltage level of a phase /*! * Typically, these species are electrons in metals. There is an infinite supply * of them. However, their electrical potential is sometimes allowed to vary, * for example if the open circuit voltage is sought after. */ #define <API key> -5 /*! * @name Types of State Calculations within VCS. These values determine where * the results are stored within the VCS_SOLVE object. * @{ */ //! State Calculation is currently in an unknown state #define <API key> -1 //! State Calculation based on the old or base mole numbers #define VCS_STATECALC_OLD 0 //! State Calculation based on the new or tentative mole numbers #define VCS_STATECALC_NEW 1 //! State Calculation based on tentative mole numbers for a phase which is //! currently zeroed, but is being evaluated for whether it should pop back into //! existence #define <API key> 2 //! State Calculation based on a temporary set of mole numbers #define VCS_STATECALC_TMP 3 } // namespace alias for backward compatibility namespace VCSnonideal = Cantera; #endif
// SeqAn - The Library for Sequence Analysis // modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. #include <seqan/align.h> #include <seqan/align_extend.h> #include <seqan/align_parallel.h> #include <seqan/align_profile.h> #include <seqan/align_split.h> #include <seqan/alignment_free.h> #include <seqan/arg_parse.h> #include <seqan/bam_io.h> #include <seqan/basic.h> #include <seqan/bed_io.h> #include <seqan/consensus.h> #include <seqan/file.h> #include <seqan/find.h> #include <seqan/gff_io.h> #include <seqan/graph_algorithms.h> #include <seqan/graph_align.h> #include <seqan/graph_msa.h> #include <seqan/graph_types.h> #include <seqan/index.h> #include <seqan/journaled_set.h> #include <seqan/map.h> #include <seqan/math.h> #include <seqan/modifier.h> #include <seqan/parallel.h> #include <seqan/parse_lm.h> #include <seqan/pipe.h> #include <seqan/platform.h> #include <seqan/random.h> #include <seqan/realign.h> #include <seqan/reduced_aminoacid.h> #include <seqan/roi_io.h> #include <seqan/score.h> #include <seqan/seeds.h> #include <seqan/seq_io.h> #include <seqan/sequence.h> #include <seqan/sequence_journaled.h> #include <seqan/simple_intervals_io.h> #include <seqan/statistics.h> #include <seqan/store.h> #include <seqan/stream.h> #include <seqan/system.h> #include <seqan/translation.h> #include <seqan/ucsc_io.h> #include <seqan/vcf_io.h> #include <seqan/version.h> // This test simply checks whether all functions are inline or templates. <API key>(<API key>) { } SEQAN_END_TESTSUITE
define([ "firebug/lib/object", "firebug/lib/trace", "firebug/lib/locale", "firebug/lib/domplate" ], function(Obj, FBTrace, Locale, Domplate) { // Custom Panel Implementation var panelName = "Canary"; Firebug.MyPanel = function MyPanel() {}; Firebug.MyPanel.prototype = Obj.extend(Firebug.Panel, { name: panelName, title: "Canary", // Initialization initialize: function() { Firebug.Panel.initialize.apply(this, arguments); if (FBTrace.DBG_FIRECANARY) FBTrace.sysout("fireCanary; MyPanel.initialize"); // TODO: Panel initialization (there is one panel instance per browser tab) var jsd = Components.classes["@mozilla.org/js/jsd/debugger-service;1"].getService(Components.interfaces.jsdIDebuggerService); // jsd.on(); // enables the service till firefox 3.6, for 4.x use asyncOn // if (jsd.isOn) alert(42); // disables the service this.refresh(); jsd.scriptHook = { onScriptCreated: function(script) { if (FBTrace.DBG_FIRECANARY) FBTrace.sysout("fireCanary; MyPanel.onScriptCreated", this.panelNode); Firebug.MyPanel.prototype.RowTemplate.log("Script create: " + script, this.panelNode) }, onScriptDestroyed: function(script){Firebug.MyPanel.prototype.RowTemplate.log("Script create: " + script, this.panelNode)} }; }, destroy: function(state) { if (FBTrace.DBG_FIRECANARY) FBTrace.sysout("fireCanary; MyPanel.destroy"); Firebug.Panel.destroy.apply(this, arguments); }, show: function(state) { Firebug.Panel.show.apply(this, arguments); if (FBTrace.DBG_FIRECANARY) FBTrace.sysout("fireCanary; MyPanel.show"); }, refresh: function() { // Render panel content. The HTML result of the template corresponds to: //this.panelNode.innerHTML = "<span>" + Locale.$STR("hellobootamd.panel.label") + "</span>"; this.MyTemplate.render(this.panelNode); // this.RowTemplate.log("testfunction", this.panelNode) // TODO: Render panel content } }); // Panel UI (Domplate) // Register locales before the following template definition. Firebug.<API key>("chrome://firecanary/locale/firecanary.properties"); /** * Domplate template used to render panel's content. Note that the template uses * localized strings and so, Firebug.<API key> for the appropriate * locale file must be already executed at this moment. */ with (Domplate) { Firebug.MyPanel.prototype.MyTemplate = domplate( { tag: DIV({onclick: "$onClick"}, SPAN( Locale.$STR("firecanary.panel.label") )), render: function(parentNode) { this.tag.replace({}, parentNode); }, onClick: function(event) { alert(42); } })} with (Domplate){ Firebug.MyPanel.prototype.RowTemplate = domplate( { tag: DIV( SPAN("$date"),SPAN(" - "),SPAN("$functionName") ), log: function(funcName, parentNode) { var args = { date: (new Date()).toGMTString(), functionName: "aaaa" }; this.tag.append(args, parentNode, this); } }) } // Registration Firebug.registerPanel(Firebug.MyPanel); Firebug.registerStylesheet("chrome://firecanary/skin/firecanary.css"); if (FBTrace.DBG_FIRECANARY) FBTrace.sysout("fireCanary; myPanel.js, stylesheet registered"); return Firebug.MyPanel; });
/** * @file * This file includes definitions for Thread child table. */ #include "child_table.hpp" #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator-getters.hpp" namespace ot { #if OPENTHREAD_FTD ChildTable::Iterator::Iterator(Instance &aInstance, Child::StateFilter aFilter) : InstanceLocator(aInstance) , mFilter(aFilter) , mStart(nullptr) , mChild(nullptr) { Reset(); } ChildTable::Iterator::Iterator(Instance &aInstance, Child::StateFilter aFilter, Child *aStartingChild) : InstanceLocator(aInstance) , mFilter(aFilter) , mStart(aStartingChild) , mChild(nullptr) { Reset(); } void ChildTable::Iterator::Reset(void) { if (mStart == nullptr) { mStart = &Get<ChildTable>().mChildren[0]; } mChild = mStart; if (!mChild->MatchesFilter(mFilter)) { Advance(); } } void ChildTable::Iterator::Advance(void) { ChildTable &childTable = Get<ChildTable>(); Child * listStart = &childTable.mChildren[0]; Child * listEnd = &childTable.mChildren[childTable.mMaxChildrenAllowed]; VerifyOrExit(mChild != nullptr, OT_NOOP); do { mChild++; if (mChild >= listEnd) { mChild = listStart; } VerifyOrExit(mChild != mStart, mChild = nullptr); } while (!mChild->MatchesFilter(mFilter)); exit: return; } ChildTable::ChildTable(Instance &aInstance) : InstanceLocator(aInstance) , mMaxChildrenAllowed(kMaxChildren) { for (Child *child = &mChildren[0]; child < OT_ARRAY_END(mChildren); child++) { child->Init(aInstance); child->Clear(); } } void ChildTable::Clear(void) { for (Child *child = &mChildren[0]; child < OT_ARRAY_END(mChildren); child++) { child->Clear(); } } Child *ChildTable::GetChildAtIndex(uint16_t aChildIndex) { Child *child = nullptr; VerifyOrExit(aChildIndex < mMaxChildrenAllowed, OT_NOOP); child = &mChildren[aChildIndex]; exit: return child; } Child *ChildTable::GetNewChild(void) { Child *child = mChildren; for (uint16_t num = mMaxChildrenAllowed; num != 0; num--, child++) { if (child->IsStateInvalid()) { child->Clear(); ExitNow(); } } child = nullptr; exit: return child; } Child *ChildTable::FindChild(uint16_t aRloc16, Child::StateFilter aFilter) { Child *child = mChildren; for (uint16_t num = mMaxChildrenAllowed; num != 0; num--, child++) { if (child->MatchesFilter(aFilter) && (child->GetRloc16() == aRloc16)) { ExitNow(); } } child = nullptr; exit: return child; } Child *ChildTable::FindChild(const Mac::ExtAddress &aAddress, Child::StateFilter aFilter) { Child *child = mChildren; for (uint16_t num = mMaxChildrenAllowed; num != 0; num--, child++) { if (child->MatchesFilter(aFilter) && (child->GetExtAddress() == aAddress)) { ExitNow(); } } child = nullptr; exit: return child; } Child *ChildTable::FindChild(const Mac::Address &aAddress, Child::StateFilter aFilter) { Child *child = nullptr; switch (aAddress.GetType()) { case Mac::Address::kTypeShort: child = FindChild(aAddress.GetShort(), aFilter); break; case Mac::Address::kTypeExtended: child = FindChild(aAddress.GetExtended(), aFilter); break; default: break; } return child; } bool ChildTable::HasChildren(Child::StateFilter aFilter) const { bool rval = false; const Child *child = mChildren; for (uint16_t num = mMaxChildrenAllowed; num != 0; num--, child++) { if (child->MatchesFilter(aFilter)) { ExitNow(rval = true); } } exit: return rval; } uint16_t ChildTable::GetNumChildren(Child::StateFilter aFilter) const { uint16_t numChildren = 0; const Child *child = mChildren; for (uint16_t num = mMaxChildrenAllowed; num != 0; num--, child++) { if (child->MatchesFilter(aFilter)) { numChildren++; } } return numChildren; } otError ChildTable::<API key>(uint16_t aMaxChildren) { otError error = OT_ERROR_NONE; VerifyOrExit(aMaxChildren > 0 && aMaxChildren <= kMaxChildren, error = <API key>); VerifyOrExit(!HasChildren(Child::<API key>), error = <API key>); mMaxChildrenAllowed = aMaxChildren; exit: return error; } #endif // OPENTHREAD_FTD } // namespace ot
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>noHitCounter</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css"> </head> <body> <nav class="level"> <div class="level-left"> <a href="/" class="level-item subtitle" style="padding: 15px;"> noHitCounter </a> </div> <div class="level-right"> </div> </nav> <section class="section"> <div class="container" id="app"> <h1 class="subtitle">Global hot key</h1> <div class="field"> <label class="label">Increment current split</label> <div class="control"> <input class="input" type="text" v-model="hotkeys.inc"/> </div> </div> <div class="field"> <label class="label">Move back one split</label> <div class="control"> <input class="input" type="text" v-model="hotkeys.up"/> </div> </div> <div class="field"> <label class="label">Move down one split</label> <div class="control"> <input class="input" type="text" v-model="hotkeys.down"/> </div> </div> <div class="control"> <button class="button is-primary" v-on:click=" save()">Save</button> </div> </div> </section> <script src="https://unpkg.com/vue"></script> <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.4"></script> <script src="settings.js"></script> </body> </html>
package com.vmware.vim25; @SuppressWarnings("all") public class <API key> extends <API key> { public <API key>[] failoverHosts; public <API key>[] getFailoverHosts() { return this.failoverHosts; } public void setFailoverHosts(<API key>[] failoverHosts) { this.failoverHosts=failoverHosts; } }
{% load i18n %} {% if items %} {% if is_searching %} <h2> {% blocktrans count counter=items.paginator.count %} There is one match {% plural %} There are {{ counter }} matches {% endblocktrans %} </h2> {% endif %} {% include "wagtailpolls/list.html" %} {% include "wagtailadmin/shared/pagination_nav.html" with items=items is_searching=is_searching linkurl=<API key> %} {% else %} {% if is_searching %} <p>{% blocktrans %}Sorry, no snippets match "<em>{{ query_string }}</em>"{% endblocktrans %}</p> {% else %} {% url 'wagtailsnippets:add' content_type.app_label content_type.model as <API key> %} <p class="no-results-message">{% blocktrans %}No {{ <API key> }} have been created. Why not <a href="{{ <API key> }}">add one</a>?{% endblocktrans %}</p> {% endif %} {% endif %}
package org.sirix.cache; import org.sirix.index.redblacktree.RBNode; import org.sirix.page.PageReference; import org.sirix.page.RevisionRootPage; import org.sirix.page.interfaces.Page; public interface BufferManager extends AutoCloseable { Cache<PageReference, Page> getRecordPageCache(); Cache<PageReference, Page> getPageCache(); Cache<Integer, RevisionRootPage> <API key>(); Cache<RBIndexKey, RBNode<?, ?>> getIndexCache(); }
#include <stdio.h> #define DELAY 40000 #define CLEAR1 "      " #define ROCKET1 " /\\  ||  ||  ||   " #define ROCKET2 " _.  / |  / /  / /  /   " #define ROCKET3 " ._  | \\  \\ \\  \\ \\  \\   " #define GROUND " #define FLAG "|***====|***====|=======||||" #define POSXY "[%i;%iH" #define CLRSCR "" #define HOME "" int main(void); int move_rocket(void); /* moves rocket into sky */ int move_rocket(void) { /* declares local vars */ int i,x,y; /* moves rocket */ for (i = 0; i < 21; i ++) { /* rocket that shoots to right */ if (i > 11) { printf("[%i;%iH", 21-((i-11)*2), 34+(2*(i-11))); printf(ROCKET2); }; /* rochet that shoots to left */ if ( i > 6) { printf("[%i;%iH", 21-i+6, 30-i+6); printf(ROCKET3); }; /* rocket center top */ printf("[%i;30H", 21-i); printf(ROCKET1); /* rocket slow right */ printf("[%i;34H", 21-(i/2)); printf(ROCKET1); /* rocket fast left */ if (i > 12) { printf("[%i;26H", 20-((i-12)*2)); printf(ROCKET1); }; /* ground level */ printf(GROUND); /* controls rate similiar to frame rate */ usleep(DELAY); //sleep(1); }; }; int main(void) { printf(CLRSCR); printf(POSXY, 15, 3); printf(FLAG); move_rocket(); printf(HOME); printf("\n"); return(0); }
/* <API key>: BSD-3-Clause */ #include <stdlib.h> #include "files.h" #include "log.h" #include "tpm2_cc_util.h" #include "tpm2_policy.h" #include "tpm2_tool.h" typedef struct <API key> <API key>; struct <API key> { const char *session_path; TPM2_CC command_code; const char *<API key>; tpm2_session *session; }; static <API key> ctx; static bool on_option(char key, char *value) { switch (key) { case 'S': ctx.session_path = value; break; case 'L': ctx.<API key> = value; break; } return true; } static bool <API key>(void) { if (!ctx.session_path) { LOG_ERR("Must specify -S session file."); return false; } return true; } static bool on_arg(int argc, char **argv) { if (argc > 1) { LOG_ERR("Specify only the TPM2 command code."); return false; } if (!argc) { LOG_ERR("TPM2 command code must be specified."); return false; } bool result = <API key>(argv[0], &ctx.command_code); if (!result) { return false; } return true; } static bool tpm2_tool_onstart(tpm2_options **opts) { static struct option topts[] = { { "session", required_argument, NULL, 'S' }, { "policy", required_argument, NULL, 'L' }, }; *opts = tpm2_options_new("S:L:", ARRAY_LEN(topts), topts, on_option, on_arg, 0); return *opts != NULL; } static tool_rc tpm2_tool_onrun(ESYS_CONTEXT *ectx, tpm2_option_flags flags) { UNUSED(flags); bool retval = <API key>(); if (!retval) { return <API key>; } tool_rc rc = <API key>(ectx, ctx.session_path, false, &ctx.session); if (rc != tool_rc_success) { return rc; } rc = <API key>(ectx, ctx.session, ctx.command_code); if (rc != tool_rc_success) { LOG_ERR("Could not build TPM policy_command_code"); return rc; } return <API key>(ectx, ctx.session, ctx.<API key>); } static tool_rc tpm2_tool_onstop(ESYS_CONTEXT *ectx) { UNUSED(ectx); return tpm2_session_close(&ctx.session); } // Register this tool with tpm2_tool.c TPM2_TOOL_REGISTER("policycommandcode", tpm2_tool_onstart, tpm2_tool_onrun, tpm2_tool_onstop, NULL)
<div class="col-sm-4 col-lg-3"> <ul class="nav nav-pills nav-stacked nav-email"> <li class="active"> <a href="#"> <i class="glyphicon glyphicon-inbox"></i> Branch </a> </li> <li> <a href="<?php echo Yii::app()->createUrl("<API key>?pId=" . $pId); ?>"> <i class="glyphicon glyphicon-th-list"></i> View All Questions </a> </li> </ul> </div><!-- col-sm-3 --> <div class="col-sm-8 col-lg-8"> <div class="block-web"> <div class="pull-right"> <div class="btn-group"> <a href="<?php echo Yii::app()->createUrl("<API key>/update/" . $model->id . "?pId=" . $pId); ?>" title="" data-toggle="tooltip" type="button" class="btn btn-white tooltips" data-original-title="Edit"><i class="glyphicon glyphicon-pencil"></i></a> <a href="#" onclick="delete_data('Are you sure you want to DELETE this Field?', '<?php echo Yii::app()->createUrl("<API key>/delete/" . $model->id . "?pId=" . $pId); ?>');" title="" data-toggle="tooltip" type="button" class="btn btn-white tooltips" data-original-title="Delete"><i class="glyphicon glyphicon-trash"></i></a> </div> </div> <strong><?php // echo $model->branch_name; ?></strong> <br/> <br/> <br/> <?php $this->widget('bootstrap.widgets.TbDetailView', array( 'data' => $model, 'attributes' => array( 'id', 'question', 'created_at', 'update_at', 'branch_id', ), )); ?> </div><!--/ block-web --> </div><!-- /col-sm-9 --> <?php /* @var $this <API key> */ /* @var $model QuestionMaster */ /* //CONTOH array( 'header' => 'Level', 'name'=> 'ref_level_id', 'type'=>'raw', 'value' => ($model->Level->name), // 'value' => ($model->status)?"on":"off", // 'value' => @Admin::model()->findByPk($model->createdBy)->username, ), */ /* * ), )); ?> <?php if (!isset($_GET['asModal'])) { $this->endWidget(); } ?> * */ ?>
(function(KUBE){ "use strict"; /* Load class */ KUBE.LoadSingleton('/Library/DOM/FeatureDetect', FeatureDetect,['/Library/Extend/Object']); /* Declaration */ FeatureDetect.prototype.toString = function(){ return '[object '+this.constructor.name+']' }; function FeatureDetect(){ var detectionCache,$api,testNode; testNode = document.createElement('div'); detectionCache = {}; $api = { 'rgba':rgba, 'hsla':hsla, 'IsRetina':IsRetina, 'FloatType':FloatType, 'LinearGradient':LinearGradient, 'SupportsW3CGradient': SupportsW3CGradient, 'Prefix':Prefix, 'Keyframes':Keyframes, 'Transitions':Transitions }.KUBE().create(FeatureDetect.prototype); return $api; /* Public Methods */ function Prefix(){ var prefix,prop; if(KUBE.Is(detectionCache.prefix) === 'undefined'){ for(prop in testNode.style){ prefix = /^webkit|^ms|^moz/i.exec(prop); if(prefix){ detectionCache.prefix = prefix[0].toLowerCase(); break; } } } return detectionCache.prefix; } function LinearGradient(){ if(KUBE.Is(detectionCache.linearGradient) === 'undefined'){ var prefixArray = [ "linear-gradient(left,black,white)", "-<API key>(left,black,white)", "-moz-linear-gradient(left,black,white)", "-ms-linear-gradient(left,black,white)", "-o-linear-gradient(left,black,white)" ]; detectionCache.linearGradient = false; try{ for(var i=0;i<prefixArray.length;i++){ testNode.style.background = prefixArray[i]; if(testNode.style.background !== ''){ detectionCache.linearGradient = true; break; } } } catch(e){} } return detectionCache.linearGradient; } function SupportsW3CGradient(){ var w3cGradient, webkitGradient; if(detectionCache['w3cGradient'] === undefined){ w3cGradient = "linear-gradient(to top, black 0%, white 100%)"; testNode.style.backgroundImage = w3cGradient; if(testNode.style.backgroundImage !== ''){ detectionCache['w3cGradient'] = true; } } return detectionCache['w3cGradient']; } function IsRetina(){ return (window.devicePixelRatio > 1 ? true : false); } function FloatType(){ if(KUBE.Is(detectionCache.floatType) === 'undefined'){ if(KUBE.Is(testNode.style.cssFloat) !== 'undefined'){ detectionCache.floatType = 'css'; } else{ detectionCache.floatType = 'style'; } } return detectionCache.floatType; } function Keyframes(){ var prefix; if(detectionCache.keyframes === undefined){ detectionCache.keyframes = false; prefix = Prefix(); if(testNode.style['animationName'] !== undefined || testNode.style[prefix+'AnimationName'] !== undefined){ detectionCache.keyframes = true; } } return detectionCache.keyframes; } function Transitions(){ var prefix; if(detectionCache.transitions === undefined){ detectionCache.transitions = false; prefix = Prefix(); if(testNode.style['transition'] !== undefined || testNode.style[prefix+'Transition'] !== undefined){ detectionCache.transitions = true; } } return detectionCache.transitions; } function rgba(){ if(KUBE.Is(detectionCache.rgba) === 'undefined'){ detectionCache.rgba = true; try{ testNode.style.color = 'rgba(1,1,1,0.5)'; } catch(e){ detectionCache.rgba = false; } } return detectionCache.rgba; } function hsla(){ if(KUBE.Is(detectionCache.hsla) === 'undefined'){ detectionCache.hsla = true; try{ testNode.style.color = 'hsla(1,1%,1%,0.5)'; } catch(e){ detectionCache.hsla = false; } } return detectionCache.hsla; } } }(KUBE));
def <API key>(item): ''' Parser for 'ghosttouch.wordpress.com' ''' vol, chp, frag, postfix = <API key>(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return <API key>(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
<?php // Generated automatically by phpdaogen. // Do NOT edit this file. // Any changes made to this file will be overwritten the next time it is generated. abstract class ApppageuriAbstract { public $id; public $when_added; public $page_uri; public static function createDefault() { $v = new Apppageuri(); $v->defaultAllFields(); return $v; } public function defaultAllFields() { $this->id = 0; $this->when_added = date('Y-m-d H:i:s'); $this->page_uri = ""; return $this; } public function loadFromArray($arr) { $this->id = isset($arr['id']) ? (int)$arr['id'] : 0; $this->when_added = isset($arr['when_added']) ? (string)$arr['when_added'] : date('Y-m-d H:i:s'); $this->page_uri = isset($arr['page_uri']) ? (string)$arr['page_uri'] : ""; return $this; } }
<?php use app\models\general\GeneralLabel; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\PlSejarahPerubatan */ $this->title = GeneralLabel::updateTitle.' '.GeneralLabel::<API key>.': ' . ' ' . $model-><API key>; $this->params['breadcrumbs'][] = ['label' => GeneralLabel::<API key>, 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model-><API key>, 'url' => ['view', 'id' => $model-><API key>]]; $this->params['breadcrumbs'][] = 'Update'; ?> <div class="<API key>"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
<?php defined('PHPFOX') or exit('NO DICE!'); class <API key> extends Phpfox_Component { public function process() { $aDraws = phpfox::getService('draw.browse')->getDraws(array( 'order' => 'd.total_comment DESC', 'limit' => 5 ), true); $this->template()->assign(array( 'aDraws' => $aDraws, 'sHeader' => Phpfox::getPhrase('draw.most_comment') )); return 'block'; } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Fri Sep 18 14:09:14 BST 2009 --> <TITLE> uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.service.globus.resource </TITLE> <META NAME="date" CONTENT="2009-09-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.service.globus.resource"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/stubs/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/resource/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> Package uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.service.globus.resource </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/resource/<API key>.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.service.globus.resource"><API key></A></B></TD> <TD>The implementation of this <API key> type.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/resource/<API key>.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.service.globus.resource"><API key></A></B></TD> <TD>DO NOT EDIT: This class is autogenerated! This class is the base class of the resource type created for this service.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/resource/<API key>.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.service.globus.resource"><API key></A></B></TD> <TD>DO NOT EDIT: This class is autogenerated! This class is used by the resource to get configuration information about the resource.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/resource/<API key>.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.job.service.globus.resource"><API key></A></B></TD> <TD>DO NOT EDIT: This class is autogenerated! This class implements the resource home for the resource type represented by this service.</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/stubs/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/job/service/globus/resource/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
from web import views if __name__ == "__main__": views.app.run(debug=True)
#include <stdarg.h> #include "native_client/src/include/portability.h" #include "native_client/src/include/portability_process.h" #include "srpcgen/ppp_rpc.h" #include "native_client/src/shared/ppapi_proxy/plugin_getinterface.h" #include "native_client/src/shared/ppapi_proxy/plugin_globals.h" #include "native_client/src/shared/ppapi_proxy/utility.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "ppapi/c/ppp.h" using ppapi_proxy::DebugPrintf; namespace { // The plugin will make synchronous calls back to the browser on the main // thread. The service exported from the browser is specified in // service_description. bool <API key>(const char* service_description, NaClSrpcChannel* channel) { NaClSrpcService* service = reinterpret_cast<NaClSrpcService*>(calloc(1, sizeof(*service))); if (NULL == service) { return false; } if (!<API key>(service, service_description)) { free(service); return false; } channel->client = service; // Remember the main channel for later calls back from the main thread. ppapi_proxy::SetMainSrpcChannel(channel); return true; } void StopMainSrpcChannel() { NaClSrpcChannel* channel = ppapi_proxy::GetMainSrpcChannel(); NaClSrpcService* service = channel->client; NaClSrpcServiceDtor(service); channel->client = NULL; ppapi_proxy::SetMainSrpcChannel(NULL); } // The plugin will make asynchronous calls to the browser on other threads. // The service exported on this channel will be gotten by service discovery. bool <API key>(NaClSrpcImcDescType upcall_channel_desc) { // Create the upcall srpc client. if (upcall_channel_desc == -1) { return false; } NaClSrpcChannel* upcall_channel = reinterpret_cast<NaClSrpcChannel*>( calloc(1, sizeof(*upcall_channel))); if (NULL == upcall_channel) { return false; } if (!NaClSrpcClientCtor(upcall_channel, upcall_channel_desc)) { free(upcall_channel); return false; } ppapi_proxy::<API key>(upcall_channel); return true; } void <API key>() { NaClSrpcChannel* upcall_channel = ppapi_proxy::<API key>(); NaClSrpcDtor(upcall_channel); ppapi_proxy::<API key>(NULL); } } // namespace // The following methods are the SRPC dispatchers for ppapi/c/ppp.h. void PppRpcServer::<API key>( NaClSrpcRpc* rpc, NaClSrpcClosure* done, int32_t pid, int64_t module, NaClSrpcImcDescType upcall_channel_desc, char* service_description, int32_t* nacl_pid, int32_t* success) { <API key> runner(done); rpc->result = <API key>; DebugPrintf("Plugin::<API key>: %s\n", service_description); // Set up the service for calling back into the browser. if (!<API key>(const_cast<const char*>(service_description), rpc->channel)) { DebugPrintf("Plugin::<API key>: " "failed to export service on main channel\n"); return; } // Set up the upcall channel for calling back into the browser. if (!<API key>(upcall_channel_desc)) { DebugPrintf("Plugin::<API key>: " "failed to construct upcall channel\n"); StopMainSrpcChannel(); return; } ppapi_proxy::<API key>(rpc->channel, module); *success = ::<API key>(module, ppapi_proxy::GetInterfaceProxy); *nacl_pid = GETPID(); rpc->result = NACL_SRPC_RESULT_OK; } void PppRpcServer::PPP_ShutdownModule(NaClSrpcRpc* rpc, NaClSrpcClosure* done) { <API key> runner(done); rpc->result = <API key>; DebugPrintf("Plugin::PPP_ShutdownModule\n"); ::PPP_ShutdownModule(); ppapi_proxy::<API key>(rpc->channel); <API key>(); StopMainSrpcChannel(); rpc->result = NACL_SRPC_RESULT_OK; } void PppRpcServer::PPP_GetInterface(NaClSrpcRpc* rpc, NaClSrpcClosure* done, char* interface_name, int32_t* <API key>) { <API key> runner(done); rpc->result = <API key>; DebugPrintf("Plugin::PPP_GetInterface(%s)\n", interface_name); // Since the proxy will make calls to proxied interfaces, we need simply // to know whether the plugin exports a given interface. const void* plugin_interface = ::PPP_GetInterface(interface_name); *<API key> = (plugin_interface != NULL); rpc->result = NACL_SRPC_RESULT_OK; }
// Use of this source code is governed by a BSD-style package key import ( "encoding/hex" "reflect" "testing" topodatapb "github.com/youtube/vitess/go/vt/proto/topodata" ) func TestKey(t *testing.T) { k0 := Uint64Key(0) k1 := Uint64Key(1) k2 := Uint64Key(0x7FFFFFFFFFFFFFFF) k3 := Uint64Key(0x8000000000000000) k4 := Uint64Key(0xFFFFFFFFFFFFFFFF) f := func(k Uint64Key, x string) { hexK := hex.EncodeToString(k.Bytes()) if x != hexK { t.Errorf("byte mismatch %#v != %#v", k, x) } } f(k0, "0000000000000000") f(k1, "0000000000000001") f(k2, "7fffffffffffffff") f(k3, "8000000000000000") f(k4, "ffffffffffffffff") } func <API key>(t *testing.T) { x40 := []byte{0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} x80 := []byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} goodTable := map[string][]*topodatapb.KeyRange{ "-": {{}}, "-<API key>-": { {End: x40}, {Start: x40, End: x80}, {Start: x80}, }, } badTable := []string{ "4000000000000000", " "<API key>", "<API key>", // not in order } for key, wanted := range goodTable { r, err := ParseShardingSpec(key) if err != nil { t.Errorf("Unexpected error: %v.", err) } if len(r) != len(wanted) { t.Errorf("Wrong result: wanted %v, got %v", wanted, r) continue } for i, w := range wanted { if !reflect.DeepEqual(r[i], w) { t.Errorf("Wrong result: wanted %v, got %v", w, r[i]) break } } } for _, bad := range badTable { _, err := ParseShardingSpec(bad) if err == nil { t.Errorf("Didn't get expected error for %v.", bad) } } } func TestContains(t *testing.T) { var table = []struct { kid string start string end string contained bool }{ {kid: "3000000000000000", start: "3000000000000000", end: "", contained: true}, {kid: "3000000000000000", start: "", end: "3000000000000000", contained: false}, {kid: "4000000000000000", start: "3000000000000000", end: "", contained: true}, {kid: "2000000000000000", start: "3000000000000000", end: "", contained: false}, } for _, el := range table { s, err := hex.DecodeString(el.start) if err != nil { t.Errorf("Unexpected error: %v", err) } e, err := hex.DecodeString(el.end) if err != nil { t.Errorf("Unexpected error: %v", err) } kr := &topodatapb.KeyRange{ Start: s, End: e, } k, err := hex.DecodeString(el.kid) if err != nil { t.Errorf("Unexpected error: %v", err) } if c := KeyRangeContains(kr, k); c != el.contained { t.Errorf("Unexpected result: contains for %v and (%v-%v) yields %v.", el.kid, el.start, el.end, c) } if !KeyRangeContains(nil, k) { t.Errorf("KeyRangeContains(nil, x) should always be true") } } } func <API key>(t *testing.T) { var table = []struct { a string b string c string d string intersects bool overlap string }{ {a: "40", b: "80", c: "c0", d: "d0", intersects: false}, {a: "", b: "80", c: "80", d: "", intersects: false}, {a: "", b: "80", c: "", d: "40", intersects: true, overlap: "-40"}, {a: "80", b: "", c: "c0", d: "", intersects: true, overlap: "c0-"}, {a: "", b: "80", c: "40", d: "80", intersects: true, overlap: "40-80"}, {a: "40", b: "80", c: "60", d: "a0", intersects: true, overlap: "60-80"}, {a: "40", b: "80", c: "50", d: "60", intersects: true, overlap: "50-60"}, {a: "40", b: "80", c: "10", d: "50", intersects: true, overlap: "40-50"}, {a: "40", b: "80", c: "40", d: "80", intersects: true, overlap: "40-80"}, {a: "", b: "80", c: "", d: "80", intersects: true, overlap: "-80"}, {a: "40", b: "", c: "40", d: "", intersects: true, overlap: "40-"}, {a: "40", b: "80", c: "20", d: "40", intersects: false}, {a: "80", b: "", c: "80", d: "c0", intersects: true, overlap: "80-c0"}, {a: "", b: "", c: "c0", d: "d0", intersects: true, overlap: "c0-d0"}, } for _, el := range table { a, err := hex.DecodeString(el.a) if err != nil { t.Errorf("Unexpected error: %v", err) } b, err := hex.DecodeString(el.b) if err != nil { t.Errorf("Unexpected error: %v", err) } left := &topodatapb.KeyRange{Start: a, End: b} c, err := hex.DecodeString(el.c) if err != nil { t.Errorf("Unexpected error: %v", err) } d, err := hex.DecodeString(el.d) if err != nil { t.Errorf("Unexpected error: %v", err) } right := &topodatapb.KeyRange{Start: c, End: d} if c := KeyRangesIntersect(left, right); c != el.intersects { t.Errorf("Unexpected result: KeyRangesIntersect for %v and %v yields %v.", left, right, c) } overlap, err := KeyRangesOverlap(left, right) if el.intersects { if err != nil { t.Errorf("Unexpected result: KeyRangesOverlap for overlapping %v and %v returned an error: %v", left, right, err) } else { got := hex.EncodeToString(overlap.Start) + "-" + hex.EncodeToString(overlap.End) if got != el.overlap { t.Errorf("Unexpected result: KeyRangesOverlap for overlapping %v and %v should have returned: %v but got: %v", left, right, el.overlap, got) } } } else { if err == nil { t.Errorf("Unexpected result: KeyRangesOverlap for non-overlapping %v and %v should have returned an error", left, right) } } } }
// include string.h for memcpy() #include <string.h> // include stdlib.h for malloc() #include <stdlib.h> // include DMA HAL #if DMA #include "sys/alt_dma.h" #include "<API key>.h" /** * DMA channels for transmitting and receiving when SENDING tokens */ alt_dma_txchan transmit_channel; /** * Multiple receive channels, one for each token channel */ alt_dma_rxchan receive_channel[NR_PROCESSES][NR_PROCESSES]; int dma_result; // static volatile int rx_done = 0; // Callback function that obtains notification that the data is received. // static void done (void *handle, void *data) // rx_done++; #endif // include FIFO HAL if a FIFO is connected to the CPU #if FIFO #include "<API key>.h" #include "<API key>.h" #endif /** * This function is used to initialize the shared memory circular buffer structures with the appropriate values * @param cb A pointer to the CircularBuffer structure at the lowest address in the shared memory. * @param size The maximum number of tokens to be set for the current shared memory. */ void cbInit(volatile CircularBuffer *cb, int size) { cb->size = size; cb->start = 0; cb->count = 0; } /** * This function checks if a circular buffer is currently full * @param cb A pointer to the CircularBuffer structure. * @return 1, if the buffer is full; 0, if it is not. */ int cbIsFull(volatile CircularBuffer *cb) { return cb->count == cb->size; } /** * This function checks if a circular buffer is currently empty * @param cb A pointer to the CircularBuffer structure. * @return 1, if the buffer is empty; 0, if it is not. */ int cbIsEmpty(volatile CircularBuffer *cb) { return cb->count == 0; } /** * This function implements a busy wait. * @param counter A counter used as the length of the wait. */ void sleep(int counter) { int i; for (i = 0; i < counter; i++); } /** * This function is used by the programmer to send a token from one SDF actor to another, across CPU borders. * @details By using the channel-specific information found in the buffers.h header, this function identifies the size of a token * to be sent via a shared module. The type of this shared module, either a hardware FIFO or shared memory managed using a software FIFO * (the circular buffer structure), is also determined by the information in this header file. * @param sender The number of the process aiming to send data. * @param receiver The number of the process to receive the data. * @param content_to_send A pointer to the local CPU memory where the data to be sent is located. * @todo Replace modulo operations as they take ages on the Nios II/e. */ void send_token(unsigned int sender, unsigned int receiver, void *content_to_send) { if (fifo_list[sender][receiver] != 0) { #if FIFO <API key>(fifo_list[sender][receiver], content_to_send); #endif } else { // get the base address of the circular buffer volatile CircularBuffer *current_buffer = address_map[sender][receiver]; // get the size of one data element in this buffer size_t data_length = token_sizes[sender][receiver]; // printf("send address: %x\n", current_buffer); while (current_buffer->count == current_buffer->size) { sleep(1000); // printf("full\n"); } // calculate the next fill status of the buffer size_t end = (current_buffer->start + current_buffer->count) % current_buffer->size; // calculate the target address for the next message in the shared memory, considering the fill status of the buffer void *content_target_base = (void *) (((void *) (((void *) current_buffer) + 3 * sizeof(int))) + ((data_length + sizeof(int)) * end)); // write the message counter for the next message to be sent in the shared memory // *((unsigned int *) content_target_base) = <API key>++; // if DMA is set to true in the processor's buffers.h, use the DMA controller to send data #if DMA // do not attempt to post a new write request if the DMA is not yet done while (!(<API key>(THIS_DMA_BASE) == 0)); // printf("Using DMA\n"); // set DMA transmit request into the DMA controller queue if ((dma_result = alt_dma_txchan_send (transmit_channel, content_to_send, data_length, NULL, NULL)) < 0) { printf("Failed to post transmit request, reason = %i\n", dma_result); exit (1); } // set DMA receive request into the controller queue if ((dma_result = <API key> (receive_channel[sender][receiver], content_target_base, data_length, NULL, // function pointed to here will be called via an interrupt when the DMA finishes its operation NULL)) < 0) { printf("Failed to post read request, reason = %i\n", dma_result); exit (1); } // while (!rx_done); #else // printf("Using memcpy\n"); memcpy(content_target_base + sizeof(int), content_to_send, data_length); #endif if (current_buffer->count == current_buffer->size) // the buffer is now full { current_buffer->start = (current_buffer->start + 1) % current_buffer->size; } else // there is room for at least one more element { current_buffer->count = current_buffer->count + 1; } // printf("write: start: %d\n", current_buffer->start); // printf("write: size: %d\n", current_buffer->size); // printf("write: count: %d\n", current_buffer->count); // printf("write: end: %d\n", end); } } /** * A helper function for receive_token() reading data from the circular buffer structure. * @param cb A pointer to the CircularBuffer structure. * @param data_length The size of the token to be read. * @param target_address A pointer to the local CPU memory where the received data is to be stored. * @todo Replace modulo operations as they take ages on the Nios II/e. */ void cbRead(volatile CircularBuffer *cb, void *target_address, size_t data_length) { int start = cb->start; // printf("Reading...\n"); // set the correct source of the content // use byte-wise increment for pointers and skip the id that gets written void *content_source = (void *) (((void *) cb) + 3 * sizeof(int)) + (start * (data_length + sizeof(int)));// + sizeof(int); // printf("target_address before: %x\n", target_address); // copy the data from the shared memory to the provided address memcpy(target_address, content_source, data_length); // printf("target_address after: %x\n", target_address); // printf("Copied...\n"); // set the next start cb->start = (cb->start + 1) % cb->size; cb->count = cb->count - 1; // printf("read: start: %d\n", cb->start); // printf("read: size: %d\n", cb->size); // printf("read: count: %d\n", cb->count); // printf("read: end: %d\n", end); // printf("Ready, current count: %d, size: %d, start: %d\n", cb->count, cb->size, cb->start); } /** * This function is used by the programmer to receive a token from one SDF actor to another, across CPU borders. * @details By using the channel-specific information found in the buffers.h header, this function identifies the size of a token * to be received via a shared module. The type of this shared module, either a hardware FIFO or shared memory managed using a software FIFO * (the circular buffer structure), is also determined by the information in this header file. * @param sender The number of the process aiming to send data. * @param receiver The number of the process to receive the data. * @param target_address A pointer to the local CPU memory where the received data is to be stored. */ void receive_token(unsigned int sender, unsigned int receiver, void *target_address) { if (fifo_list[sender][receiver] != 0) { #if FIFO *((unsigned int *) target_address) = <API key>(fifo_list[sender][receiver]); #endif } else { // get the address of the correct buffer according to sending and receiving process volatile CircularBuffer *current_buffer = address_map[sender][receiver]; // printf("receive address: %x\n", current_buffer); // check if this buffer is currently empty // if it is, wait a little while, then try again while (cbIsEmpty(current_buffer)) { sleep(1000); // printf("empty\n"); } // then read the value from it and write it to the provided address cbRead(current_buffer, target_address, token_sizes[sender][receiver]); // printf("Data read...\n"); } } /** * This function initializes CircularBuffer data structures * @details This function needs to be called by each CPU before performing any send_token() or receive_token() operations as it * sets the FIFO management information in the structures and opens the DMA controller send and receive channels, provided * DMA controllers are connected to the CPU. */ void initialize_buffers() { int i, j; for (i = 0; i < NR_PROCESSES; i++) { for (j = 0; j < NR_PROCESSES; j++) { if (!(address_map[i][j] == 0)) { // clean all the space required for the current buffer // correct token size + one integer to store message if // everything plus three integers for buffer header information memset((void *)address_map[i][j], 0, ((token_sizes[i][j] + sizeof(int)) * buffer_length[i][j]) + 3 * sizeof(int)); // set buffer size information cbInit(address_map[i][j], buffer_length[i][j]); } } } #if DMA // create the DMA transmitter channel to be used by this processor if ((transmit_channel = alt_dma_txchan_open(THIS_DMA_NAME)) == NULL) { printf ("Failed to open transmit channel\n"); exit (1); } for (i = 0; i < NR_PROCESSES; i++) { for (j = 0; j < NR_PROCESSES; j++) { if (!(address_map[i][j] == 0)) { // create the DMA receiver channels if ((receive_channel[i][j] = alt_dma_rxchan_open(THIS_DMA_NAME)) == NULL) { printf ("Failed to open receive channel\n"); exit (1); } } } } #endif }
// of patent rights can be found in the PATENTS file in the same directory. // pink/pink/src/pink_cli.cc #include "utils/pink_cli.h" #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <fcntl.h> #include <netdb.h> #include <poll.h> #include <unistd.h> namespace bubblefs { namespace mypink { struct PinkCli::Rep { std::string peer_ip; int peer_port; int send_timeout; int recv_timeout; int connect_timeout; bool keep_alive; bool is_block; int sockfd; bool available; Rep() : send_timeout(0), recv_timeout(0), connect_timeout(1000), keep_alive(0), is_block(true), available(false) { } Rep(const std::string& ip, int port) : peer_ip(ip), peer_port(port), send_timeout(0), recv_timeout(0), connect_timeout(1000), keep_alive(0), is_block(true), available(false) { } }; PinkCli::PinkCli(const std::string& ip, const int port) : rep_(new Rep(ip, port)) { } PinkCli::~PinkCli() { Close(); delete rep_; } bool PinkCli::Available() const { return rep_->available; } Status PinkCli::Connect(const std::string &bind_ip) { return Connect(rep_->peer_ip, rep_->peer_port, bind_ip); } Status PinkCli::Connect(const std::string &ip, const int port, const std::string &bind_ip) { Rep* r = rep_; Status s; int rv; char cport[6]; struct addrinfo hints, *servinfo, *p; snprintf(cport, sizeof(cport), "%d", port); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; // We do not handle IPv6 if ((rv = getaddrinfo(ip.c_str(), cport, &hints, &servinfo)) != 0) { return Status::IOError("connect getaddrinfo error for ", ip); } for (p = servinfo; p != NULL; p = p->ai_next) { if ((r->sockfd = socket( p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } // bind if needed if (!bind_ip.empty()) { struct sockaddr_in localaddr; localaddr.sin_family = AF_INET; localaddr.sin_addr.s_addr = inet_addr(bind_ip.c_str()); localaddr.sin_port = 0; // Any local port will do bind(r->sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr)); } int flags = fcntl(r->sockfd, F_GETFL, 0); fcntl(r->sockfd, F_SETFL, flags | O_NONBLOCK); if (connect(r->sockfd, p->ai_addr, p->ai_addrlen) == -1) { if (errno == EHOSTUNREACH) { close(r->sockfd); continue; } else if (errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK) { struct pollfd wfd[1]; wfd[0].fd = r->sockfd; wfd[0].events = POLLOUT; int res; if ((res = poll(wfd, 1, r->connect_timeout)) == -1) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect poll error"); } else if (res == 0) { close(r->sockfd); freeaddrinfo(servinfo); return Status::Timeout(""); } int val = 0; socklen_t lon = sizeof(int); if (getsockopt(r->sockfd, SOL_SOCKET, SO_ERROR, &val, &lon) == -1) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect host getsockopt error"); } if (val) { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "connect host error"); } } else { close(r->sockfd); freeaddrinfo(servinfo); return Status::IOError("EHOSTUNREACH", "The target host cannot be reached"); } } struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); getsockname(r->sockfd, (struct sockaddr*) &laddr, &llen); std::string lip(inet_ntoa(laddr.sin_addr)); int lport = ntohs(laddr.sin_port); if (ip == lip && port == lport) { return Status::IOError("EHOSTUNREACH", "same ip port"); } flags = fcntl(r->sockfd, F_GETFL, 0); fcntl(r->sockfd, F_SETFL, flags & ~O_NONBLOCK); freeaddrinfo(servinfo); // connect ok rep_->available = true; return s; } if (p == NULL) { s = Status::IOError(strerror(errno), "Can't create socket "); return s; } freeaddrinfo(servinfo); freeaddrinfo(p); set_tcp_nodelay(); return s; } Status PinkCli::SendRaw(void *buf, size_t count) { char* wbuf = reinterpret_cast<char*>(buf); size_t nleft = count; int pos = 0; ssize_t nwritten; while (nleft > 0) { if ((nwritten = write(rep_->sockfd, wbuf + pos, nleft)) < 0) { if (errno == EINTR) { continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return Status::Timeout("Send timeout"); } else { return Status::IOError("write error " + std::string(strerror(errno))); } } else if (nwritten == 0) { return Status::IOError("write nothing"); } nleft -= nwritten; pos += nwritten; } return Status::OK(); } Status PinkCli::RecvRaw(void *buf, size_t *count) { Rep* r = rep_; char* rbuf = reinterpret_cast<char*>(buf); size_t nleft = *count; size_t pos = 0; ssize_t nread; while (nleft > 0) { if ((nread = read(r->sockfd, rbuf + pos, nleft)) < 0) { if (errno == EINTR) { continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return Status::Timeout("Send timeout"); } else { return Status::IOError("read error " + std::string(strerror(errno))); } } else if (nread == 0) { return Status::EndFile("socket closed"); } nleft -= nread; pos += nread; } *count = pos; return Status::OK(); } int PinkCli::fd() const { return rep_->sockfd; } void PinkCli::Close() { if (rep_->available) { close(rep_->sockfd); rep_->available = false; } } void PinkCli::set_connect_timeout(int connect_timeout) { rep_->connect_timeout = connect_timeout; } int PinkCli::set_send_timeout(int send_timeout) { Rep* r = rep_; int ret = 0; if (send_timeout > 0) { r->send_timeout = send_timeout; struct timeval timeout = {r->send_timeout / 1000, (r->send_timeout % 1000) * 1000}; ret = setsockopt( r->sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); } return ret; } int PinkCli::set_recv_timeout(int recv_timeout) { Rep* r = rep_; int ret = 0; if (recv_timeout > 0) { r->recv_timeout = recv_timeout; struct timeval timeout = {r->recv_timeout / 1000, (r->recv_timeout % 1000) * 1000}; ret = setsockopt( r->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); } return ret; } int PinkCli::set_tcp_nodelay() { Rep* r = rep_; int val = 1; int ret = 0; ret = setsockopt(r->sockfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); return ret; } void DeletePinkCli(PinkCli** cli) { delete (*cli); *cli = nullptr; } } // namespace mypink } // namespace bubblefs
<?php namespace app\models; use Yii; /** * This is the model class for table "comments". * * @property integer $comment_id * @property integer $section_id * @property integer $student_id * @property string $interim_quality * @property string $interim_improvement * @property string $interim_comment * @property string $grade_comment */ class Comments extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'comments'; } /** * @inheritdoc */ public function rules() { return [ [['section_id', 'student_id', 'interim_quality', 'interim_improvement', 'interim_comment', 'grade_comment'], 'required'], [['section_id', 'student_id'], 'integer'], [['interim_quality', 'interim_improvement', 'interim_comment', 'grade_comment'], 'string'], [['section_id', 'student_id'], 'unique', 'targetAttribute' => ['section_id', 'student_id'], 'message' => 'The combination of Section ID and Student ID has already been taken.'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'comment_id' => 'Comment ID', 'section_id' => 'Section ID', 'student_id' => 'Student ID', 'interim_quality' => 'Interim Quality', 'interim_improvement' => 'Interim Improvement', 'interim_comment' => 'Interim Comment', 'grade_comment' => 'Grade Comment', ]; } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http: <html> <head> <title>SHTOOLS - Localized spectral analysis</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../../css/sh.css"> <link rel="icon" type="image/vnd.microsoft.icon" href="../../images/favicon.ico"> </head> <body> <div class="main"> <p class="centeredimage"><img src="../../images/logo.jpg" width=894 height=135 alt="SHTOOLS --- Tools for working with spherical harmonics"></p> <table class="menu"> <tbody> <tr> <td><a href="http://shtools.ipgp.fr/">HOME</a></td> <td><a href="https://github.com/SHTOOLS/SHTOOLS/releases">DOWNLOAD</a></td> <td class="selected"><a href="../../documentation.html">DOCUMENTATION</a></td> <td><a href="../../faq.html">FAQ</a> </td> </tr> </tbody> </table> <p class="dir"> > <a href="../../../index.html" class="dir">Home</a> > <a href="../../documentation.html" class="dir">Documentation</a> > <a href="../../python-routines.html" class="dir">Python</a> > <a href="../../pylocalized.html" class="dir">Localized Spectral Analysis</a></p> <h1 id="shmultitaperse">SHMultiTaperSE</h1> <p>Perform a localized multitaper spectral analysis using spherical cap windows.</p> <h1 id="usage">Usage</h1> <p><code>mtse</code>, <code>sd</code> = pyshtools.SHMultiTaperSE (<code>sh</code>, <code>tapers</code>, <code>taper_order</code>, [<code>lmax</code>, <code>lmaxt</code>, <code>k</code>, <code>lat</code>, <code>lon</code>, <code>taper_wt</code>, <code>norm</code>, <code>csphase</code>])</p> <h1 id="returns">Returns</h1> <dl> <dt><code>mtse</code> : float dimension (<code>lmax</code>-<code>lmaxt</code>+1)</dt> <dd>The localized multitaper power spectrum estimate. </dd> <dt><code>sd</code> : float, dimension (<code>lmax</code>-<code>lmaxt</code>+1)</dt> <dd>The standard error of the localized multitaper power spectral estimates. </dd> </dl> <h1 id="parameters">Parameters</h1> <dl> <dt><code>sh</code> : float, dimension (2, <code>lmaxin</code>+1, <code>lmaxin</code>+1)</dt> <dd>The spherical harmonic coefficients of the function to be localized. </dd> <dt><code>tapers</code> : float, dimension (<code>lmaxtin</code>+1, <code>kin</code>)</dt> <dd>An array of the <code>k</code> windowing functions, arranged in columns, obtained from a call to <code>SHReturnTapers</code>. Each window has non-zero coefficients for a single angular order that is specified in the array <code>taper_order</code>. </dd> <dt><code>taper_order</code> : integer, dimension (<code>kin</code>)</dt> <dd>An array containing the angular orders of the spherical harmonic coefficients in each column of the array <code>tapers</code>. </dd> <dt><code>lmax</code> : optional, integer, default = <code>lmaxin</code></dt> <dd>The spherical harmonic bandwidth of <code>sh</code>. This must be less than or equal to <code>lmaxin</code>. </dd> <dt><code>lmaxt</code> : optional, integer, default = <code>lmaxtin</code></dt> <dd>The spherical harmonic bandwidth of the windowing functions in the array <code>tapers</code>. </dd> <dt><code>k</code> : optional, integer, default = <code>kin</code></dt> <dd>The number of tapers to be utilized in performing the multitaper spectral analysis. </dd> <dt><code>lat</code> : optional, float, default = 90</dt> <dd>The latitude in degrees of the localized analysis. The default is to perform the spectral analysis at the north pole. </dd> <dt><code>lon</code> : optional, float, default = 0</dt> <dd>The longitude in degrees of the localized analysis. </dd> <dt><code>taper_wt</code> : optional, float, dimension (<code>kin</code>), default = -1</dt> <dd>The weights used in calculating the multitaper spectral estimates and standard error. Optimal values of the weights (for a known global power spectrum) can be obtained from the routine <code>SHMTVarOpt</code>. The default value specifies not to use <code>taper_wt</code>. </dd> <dt><code>norm</code> : optional, integer, default = 1</dt> <dd>1 (default) = 4-pi (geodesy) normalized harmonics; 2 = Schmidt semi-normalized harmonics; 3 = unnormalized harmonics; 4 = orthonormal harmonics. </dd> <dt><code>csphase</code> : optional, integer, default = 1</dt> <dd>1 (default) = do not apply the Condon-Shortley phase factor to the associated Legendre functions; -1 = append the Condon-Shortley phase factor of (-1)^m to the associated Legendre functions. </dd> </dl> <h1 id="description">Description</h1> <p><code>SHMultiTaperSE</code> will perform a localized multitaper spectral analysis of an input function expressed in spherical harmonics. The maximum degree of the localized multitaper cross-power spectrum estimate is <code>lmax-lmaxt</code>. The coefficients and angular orders of the windowing coefficients (<code>tapers</code> and <code>taper_order</code>) are obtained by a call to <code>SHReturnTapers</code>. If <code>lat</code> and <code>lon</code> are specified, the symmetry axis of the localizing windows will be rotated to these coordinates. Otherwise, the localized spectral analysis will be centered over the north pole.</p> <p>If the optional array <code>taper_wt</code> is specified, these weights will be used in calculating a weighted average of the individual <code>k</code> tapered estimates <code>mtse</code> and the corresponding standard error of the estimates <code>sd</code>. If not present, the weights will all be assumed to be equal. When <code>taper_wt</code> is not specified, the mutltitaper spectral estimate for a given degree is calculated as the average obtained from the <code>k</code> individual tapered estimates. The standard error of the multitaper estimate at degree <code>l</code> is simply the population standard deviation, <code>S = sqrt(sum (Si - mtse)^2 / (k-1))</code>, divided by <code>sqrt(k)</code>. See Wieczorek and Simons (2007) for the relevant expressions when weighted estimates are used.</p> <p>The employed spherical harmonic normalization and Condon-Shortley phase convention can be set by the optional arguments <code>norm</code> and <code>csphase</code>; if not set, the default is to use geodesy 4-pi normalized harmonics that exclude the Condon-Shortley phase of (-1)^m.</p> <h1 id="references">References</h1> <p>Wieczorek, M. A. and F. J. Simons, Minimum-variance multitaper spectral estimation on the sphere, J. Fourier Anal. Appl., 13, doi:10.1007/s00041-006-6904-1, 665-692, 2007.</p> <h1 id="see-also">See also</h1> <p><a href="pyshmultitapercse.html">shmultitapercse</a>, <a href="pyshreturntapers.html">shreturntapers</a>, <a href="pyshreturntapersm.html">shreturntapersm</a>, <a href="pyshmtvaropt.html">shmtvaropt</a></p> <p class="dir"> > <a href="../../../index.html" class="dir">Home</a> > <a href="../../documentation.html" class="dir">Documentation</a> > <a href="../../python-routines.html" class="dir">Python</a> > <a href="../../pylocalized.html" class="dir">Localized Spectral Analysis</a></p> <table class="footer2" summary = "SHTOOLS; Fortran and Python spherical harmonic transform software package"> <tbody> <tr> <td class="c1"><a href="http: <td class="c2"><a href="http: <td class="c3">&copy; 2016 <a href="https://github.com/SHTOOLS">SHTOOLS</a></td> </tr> </tbody> </table> </div> </body> </html>
<!DOCTYPE html> <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>colour.recovery.dataset.smits1999 &mdash; Colour 0.3.6 documentation</title> <link rel="stylesheet" href="../../../../_static/basic.css" type="text/css" /> <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../../../../_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="../../../../_static/bootstrap-sphinx.css" type="text/css" /> <link rel="stylesheet" href="../../../../_static/styles.css" type="text/css" /> <script type="text/javascript"> var <API key> = { URL_ROOT: '../../../../', VERSION: '0.3.6', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../../../_static/jquery.js"></script> <script type="text/javascript" src="../../../../_static/underscore.js"></script> <script type="text/javascript" src="../../../../_static/doctools.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=<API key>"></script> <script type="text/javascript" src="../../../../_static/js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../../../../_static/js/jquery-fix.js"></script> <script type="text/javascript" src="../../../../_static/bootstrap-3.1.0/js/bootstrap.min.js"></script> <script type="text/javascript" src="../../../../_static/bootstrap-sphinx.js"></script> <link rel="top" title="Colour 0.3.6 documentation" href="../../../../index.html" /> <link rel="up" title="colour.recovery" href="../../recovery.html" /> <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.0, maximum-scale=1'> <meta name="<API key>" content="yes"> </head> <body> <div id="navbar" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- .btn-navbar is used as the toggle for collapsed navbar content --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../index.html"><img src="../../../../_static/<API key>.png"> Colour&nbsp;0.3</a> <!--<span class="navbar-text navbar-version pull-left"><b>0.3</b></span>--> </div> <div class="collapse navbar-collapse nav-collapse"> <ul class="nav navbar-nav"> <li class="divider-vertical"></li> <li><a href="http://colour-science.org">colour-science.org</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-life-ring">&nbsp;Documentation</i><b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="api.html" class="fa fa-life-ring">&nbsp;API Reference</a> </li> <li> <a href="http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/colour.ipynb', True)" class="fa fa-book">&nbsp;IPython Notebooks</a> </li> <li> <a href="http://colour-science.org/features.php" class="fa fa-lightbulb-o">&nbsp;Features</a> </li> <li> <a href="http://colour-science.org/contributing.php"><span class="fa fa-gears">&nbsp;Contributing</span></a> </li> </ul> </li> </ul> <form class="navbar-form navbar-right" action="../../../../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-12"> <h1>Source code for colour.recovery.dataset.smits1999</h1><div class="highlight"><pre> <span class="c">#!/usr/bin/env python</span> <span class="c"># -*- coding: utf-8 -*-</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd">Smits (1999) - Reflectance Recovery Dataset</span> <span class="sd">===========================================</span> <span class="sd">Defines the dataset for reflectance recovery using Smits (1999) method.</span> <span class="sd">References</span> <span class="sd"> <span class="sd">.. [1] Smits, B. (1999). An RGB-to-Spectrum Conversion for Reflectances.</span> <span class="sd"> Journal of Graphics Tools, 4(4), 11–22.</span> <span class="sd"> doi:10.1080/10867651.1999.10487511</span> <span class="sd">&quot;&quot;&quot;</span> <span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">division</span><span class="p">,</span> <span class="n">unicode_literals</span> <span class="kn">from</span> <span class="nn">colour.colorimetry.spectrum</span> <span class="kn">import</span> <span class="n"><API key></span> <span class="kn">from</span> <span class="nn">colour.utilities</span> <span class="kn">import</span> <span class="n"><API key></span> <span class="n">__author__</span> <span class="o">=</span> <span class="s">&#39;Colour Developers&#39;</span> <span class="n">__copyright__</span> <span class="o">=</span> <span class="s">& <span class="n">__license__</span> <span class="o">=</span> <span class="s">& <span class="n">__maintainer__</span> <span class="o">=</span> <span class="s">&#39;Colour Developers&#39;</span> <span class="n">__email__</span> <span class="o">=</span> <span class="s">&#39;colour-science@googlegroups.com&#39;</span> <span class="n">__status__</span> <span class="o">=</span> <span class="s">&#39;Production&#39;</span> <span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;<API key>&#39;</span><span class="p">,</span> <span class="s">&#39;SMITS_1999_SPDS&#39;</span><span class="p">]</span> <span class="n"><API key></span> <span class="o">=</span> <span class="p">{</span> <span class="s">&#39;white&#39;</span><span class="p">:</span> <span class="p">{</span> <span class="mf">380.0000</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">417.7778</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">455.5556</span><span class="p">:</span> <span class="mf">0.9999</span><span class="p">,</span> <span class="mf">493.3333</span><span class="p">:</span> <span class="mf">0.9993</span><span class="p">,</span> <span class="mf">531.1111</span><span class="p">:</span> <span class="mf">0.9992</span><span class="p">,</span> <span class="mf">568.8889</span><span class="p">:</span> <span class="mf">0.9998</span><span class="p">,</span> <span class="mf">606.6667</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">644.4444</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">682.2222</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">720.0000</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">},</span> <span class="s">&#39;cyan&#39;</span><span class="p">:</span> <span class="p">{</span> <span class="mf">380.0000</span><span class="p">:</span> <span class="mf">0.9710</span><span class="p">,</span> <span class="mf">417.7778</span><span class="p">:</span> <span class="mf">0.9426</span><span class="p">,</span> <span class="mf">455.5556</span><span class="p">:</span> <span class="mf">1.0007</span><span class="p">,</span> <span class="mf">493.3333</span><span class="p">:</span> <span class="mf">1.0007</span><span class="p">,</span> <span class="mf">531.1111</span><span class="p">:</span> <span class="mf">1.0007</span><span class="p">,</span> <span class="mf">568.8889</span><span class="p">:</span> <span class="mf">1.0007</span><span class="p">,</span> <span class="mf">606.6667</span><span class="p">:</span> <span class="mf">0.1564</span><span class="p">,</span> <span class="mf">644.4444</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">682.2222</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">720.0000</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">},</span> <span class="s">&#39;magenta&#39;</span><span class="p">:</span> <span class="p">{</span> <span class="mf">380.0000</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">417.7778</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">455.5556</span><span class="p">:</span> <span class="mf">0.9685</span><span class="p">,</span> <span class="mf">493.3333</span><span class="p">:</span> <span class="mf">0.2229</span><span class="p">,</span> <span class="mf">531.1111</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">568.8889</span><span class="p">:</span> <span class="mf">0.0458</span><span class="p">,</span> <span class="mf">606.6667</span><span class="p">:</span> <span class="mf">0.8369</span><span class="p">,</span> <span class="mf">644.4444</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">682.2222</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">720.0000</span><span class="p">:</span> <span class="mf">0.9959</span><span class="p">},</span> <span class="s">&#39;yellow&#39;</span><span class="p">:</span> <span class="p">{</span> <span class="mf">380.0000</span><span class="p">:</span> <span class="mf">0.0001</span><span class="p">,</span> <span class="mf">417.7778</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">455.5556</span><span class="p">:</span> <span class="mf">0.1088</span><span class="p">,</span> <span class="mf">493.3333</span><span class="p">:</span> <span class="mf">0.6651</span><span class="p">,</span> <span class="mf">531.1111</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">568.8889</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">606.6667</span><span class="p">:</span> <span class="mf">0.9996</span><span class="p">,</span> <span class="mf">644.4444</span><span class="p">:</span> <span class="mf">0.9586</span><span class="p">,</span> <span class="mf">682.2222</span><span class="p">:</span> <span class="mf">0.9685</span><span class="p">,</span> <span class="mf">720.0000</span><span class="p">:</span> <span class="mf">0.9840</span><span class="p">},</span> <span class="s">&#39;red&#39;</span><span class="p">:</span> <span class="p">{</span> <span class="mf">380.0000</span><span class="p">:</span> <span class="mf">0.1012</span><span class="p">,</span> <span class="mf">417.7778</span><span class="p">:</span> <span class="mf">0.0515</span><span class="p">,</span> <span class="mf">455.5556</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">493.3333</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">531.1111</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">568.8889</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">606.6667</span><span class="p">:</span> <span class="mf">0.8325</span><span class="p">,</span> <span class="mf">644.4444</span><span class="p">:</span> <span class="mf">1.0149</span><span class="p">,</span> <span class="mf">682.2222</span><span class="p">:</span> <span class="mf">1.0149</span><span class="p">,</span> <span class="mf">720.0000</span><span class="p">:</span> <span class="mf">1.0149</span><span class="p">},</span> <span class="s">&#39;green&#39;</span><span class="p">:</span> <span class="p">{</span> <span class="mf">380.0000</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">417.7778</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">455.5556</span><span class="p">:</span> <span class="mf">0.0273</span><span class="p">,</span> <span class="mf">493.3333</span><span class="p">:</span> <span class="mf">0.7937</span><span class="p">,</span> <span class="mf">531.1111</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">568.8889</span><span class="p">:</span> <span class="mf">0.9418</span><span class="p">,</span> <span class="mf">606.6667</span><span class="p">:</span> <span class="mf">0.1719</span><span class="p">,</span> <span class="mf">644.4444</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">682.2222</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">720.0000</span><span class="p">:</span> <span class="mf">0.0025</span><span class="p">},</span> <span class="s">&#39;blue&#39;</span><span class="p">:</span> <span class="p">{</span> <span class="mf">380.0000</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">417.7778</span><span class="p">:</span> <span class="mf">1.0000</span><span class="p">,</span> <span class="mf">455.5556</span><span class="p">:</span> <span class="mf">0.8916</span><span class="p">,</span> <span class="mf">493.3333</span><span class="p">:</span> <span class="mf">0.3323</span><span class="p">,</span> <span class="mf">531.1111</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">568.8889</span><span class="p">:</span> <span class="mf">0.0000</span><span class="p">,</span> <span class="mf">606.6667</span><span class="p">:</span> <span class="mf">0.0003</span><span class="p">,</span> <span class="mf">644.4444</span><span class="p">:</span> <span class="mf">0.0369</span><span class="p">,</span> <span class="mf">682.2222</span><span class="p">:</span> <span class="mf">0.0483</span><span class="p">,</span> <span class="mf">720.0000</span><span class="p">:</span> <span class="mf">0.0496</span><span class="p">}}</span> <span class="n">SMITS_1999_SPDS</span> <span class="o">=</span> <span class="n"><API key></span><span class="p">({</span> <span class="s">&#39;white&#39;</span><span class="p">:</span> <span class="n"><API key></span><span class="p">(</span> <span class="s">&#39;white&#39;</span><span class="p">,</span> <span class="n"><API key></span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;white&#39;</span><span class="p">)),</span> <span class="s">&#39;cyan&#39;</span><span class="p">:</span> <span class="n"><API key></span><span class="p">(</span> <span class="s">&#39;cyan&#39;</span><span class="p">,</span> <span class="n"><API key></span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;cyan&#39;</span><span class="p">)),</span> <span class="s">&#39;magenta&#39;</span><span class="p">:</span> <span class="n"><API key></span><span class="p">(</span> <span class="s">&#39;magenta&#39;</span><span class="p">,</span> <span class="n"><API key></span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;magenta&#39;</span><span class="p">)),</span> <span class="s">&#39;yellow&#39;</span><span class="p">:</span> <span class="n"><API key></span><span class="p">(</span> <span class="s">&#39;yellow&#39;</span><span class="p">,</span> <span class="n"><API key></span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;yellow&#39;</span><span class="p">)),</span> <span class="s">&#39;red&#39;</span><span class="p">:</span> <span class="n"><API key></span><span class="p">(</span> <span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="n"><API key></span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;red&#39;</span><span class="p">)),</span> <span class="s">&#39;green&#39;</span><span class="p">:</span> <span class="n"><API key></span><span class="p">(</span> <span class="s">&#39;green&#39;</span><span class="p">,</span> <span class="n"><API key></span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;green&#39;</span><span class="p">)),</span> <span class="s">&#39;blue&#39;</span><span class="p">:</span> <span class="n"><API key></span><span class="p">(</span> <span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="n"><API key></span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">))})</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd">Smits (1999) spectral power distributions.</span> <span class="sd">SMITS_1999_SPDS : <API key></span> <span class="sd">&quot;&quot;&quot;</span> </pre></div> </div> </div> </div> <footer class="footer"> <div class="container"> <p class="pull-right"> <a href="#">Back to top</a> </p> <p> &copy; Copyright 2013 - 2015, Colour Developers.<br/> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.2.<br/> </p> </div> </footer> </body> </html>
<?php require_once dirname(__FILE__) . '/Message.php'; require_once dirname(__FILE__) . '/Part.php'; require_once dirname(__FILE__) . '/../MIME.php'; class MIME_Structure { /** * Given the results of imap_fetchstructure(), parse the structure * of the message, figuring out correct bodypart numbers, etc. * * @param stdClass $body The result of imap_fetchstructure(). * * @return &MIME_Message The message parsed into a MIME_Message object. */ function &parse($body) { $msgOb = &new MIME_Message(); $msgOb->addPart(MIME_Structure::_parse($body)); $msgOb->buildMessage(); $ptr = array(&$msgOb); MIME_Structure::addMultipartInfo($ptr); return $msgOb; } /** * Given the results of imap_fetchstructure(), parse the structure * of the message, figuring out correct bodypart numbers, etc. * * @access private * * @param stdClass $body The result of imap_fetchstructure(). * @param string $ref The current bodypart. * * @return MIME_Part A MIME_Part object. */ function &_parse($body, $ref = 0) { static $message, $multipart; if (!isset($message)) { $message = MIME::type('message'); $multipart = MIME::type('multipart'); } $mime_part = &new MIME_Part(null, null, null); /* Top multiparts don't get their own line. */ if (empty($ref) && (!isset($body->type) || ($body->type != $multipart))) { $ref = 1; } MIME_Structure::_setInfo($body, $mime_part, $ref); if (isset($body->type) && ($body->type == $message) && $body->ifsubtype && ($body->subtype == 'RFC822')) { $mime_part->setMIMEId($ref . '.0'); } else { $mime_part->setMIMEId($ref); } /* Deal with multipart data. */ if (isset($body->parts)) { $sub_id = 1; reset($body->parts); while (list(,$sub_part) = each($body->parts)) { /* Are we dealing with a multipart message? */ if (isset($body->type) && ($body->type == $message) && isset($sub_part->type) && ($sub_part->type == $multipart)) { $sub_ref = $ref; } else { $sub_ref = (empty($ref)) ? $sub_id : $ref . '.' . $sub_id; } $mime_part->addPart(MIME_Structure::_parse($sub_part, $sub_ref), $sub_id++); } } return $mime_part; } /** * Given a mime part from imap_fetchstructure(), munge it into a * useful form and make sure that any parameters which are missing * are given default values. * * To specify the default character set, define the global variable * $GLOBALS['mime_strucutre']['default_charset']. * * @access private * * @param stdClass $part The original part info. * @param MIME_Part &$ob A MIME_Part object. * @param string $ref The ID of this part. */ function _setInfo($part, &$ob, $ref) { /* Store Content-type information. */ $primary_type = (isset($part->type)) ? MIME::type($part->type, MIME_STRING) : 'text'; $sec_type = ($part->ifsubtype && $part->subtype) ? $part->subtype : 'x-unknown'; $ob->setType($primary_type . '/' . $sec_type); /* Set transfer encoding. */ if (isset($part->encoding)) { $encoding = $part->encoding; $ob->setTransferEncoding($encoding); } else { $encoding = null; } /* Set transfer disposition. */ $ob->setDisposition(($part->ifdisposition) ? $part->disposition : <API key>); /* If 'body' is set, set as the contents of the part. */ if (isset($part->body)) { $ob->setContents($part->body, $encoding); } /* If 'bytes' is set, store as information variable. */ if (isset($part->bytes)) { $ob->setBytes($part->bytes); } /* Set the part's identification string, if available. */ if (!empty($ref) && $part->ifid) { $ob->setContentID($part->id); } /* Go through the content-type parameters, if any. */ foreach (MIME_Structure::_getParameters($part, 1) as $key => $val) { if ($key == 'charset') { $ob->setCharset($val); } else { $ob-><API key>($key, $val); } } /* Set the default character set. */ if (($ob->getPrimaryType() == 'text') && (String::lower($ob->getCharset()) == 'us-ascii') && isset($GLOBALS['mime_structure']['default_charset'])) { $ob->setCharset($GLOBALS['mime_structure']['default_charset']); } /* Go through the disposition parameters, if any. */ foreach (MIME_Structure::_getParameters($part, 2) as $key => $val) { $ob-><API key>($key, $val); } /* Set the name. */ if (($fname = $ob-><API key>('filename'))) { $ob->setName($fname); } elseif (($fname = $ob-><API key>('filename'))) { $ob->setName($fname); } /* Set the description. */ if (isset($part->description)) { $ob->setDescription(preg_replace('/\s+/', ' ', $part->description)); } } /** * Get all parameters for a given portion of a message. * * @access private * * @param stdClass $part The original part info. * @param integer $type The parameter type to retrieve. * 1 = content * 2 = disposition * * @return array An array of parameter key/value pairs. */ function _getParameters($part, $type) { $param_list = array(); $ptype = ($type == 1) ? 'parameters' : 'dparameters'; $pexists = 'if' . $ptype; if ($part->$pexists) { $attr_list = $rfc2231_list = array(); foreach ($part->$ptype as $param) { $param->value = str_replace(array("\t", '\"'), array(' ', '"'), $param->value); /* Look for an asterisk in the attribute name. If found we * know we have RFC 2231 information. */ $pos = strpos($param->attribute, '*'); if ($pos) { $attr = substr($param->attribute, 0, $pos); $rfc2231_list[$attr][] = $param->attribute . '=' . $param->value; } else { $attr_list[$param->attribute] = $param->value; } } foreach ($rfc2231_list as $val) { $res = MIME::decodeRFC2231(implode(' ', $val)); if ($res) { $attr_list[$res['attribute']] = $res['value']; } } foreach ($attr_list as $attr => $val) { $field = String::lower($attr); if ($field == 'type') { if (($type = MIME::type($val))) { $param_list['type'] = $type; } } else { $param_list[$field] = $val; } } } return $param_list; } /** * Set the special information for certain MIME types. * * @since Horde 3.2 * * @param array &$parts The list of parts contained within the multipart * object. * @param array $info Information about the multipart structure. */ function addMultipartInfo(&$parts, $info = array()) { if (empty($parts)) { return; } reset($parts); while (list($key,) = each($parts)) { $ptr = &$parts[$key]; $new_info = $info; if (isset($info['alt'])) { $ptr->setInformation('alternative', (is_null($info['alt'])) ? '-' : $info['alt']); } if (isset($info['related'])) { $ptr->setInformation('related_part', $info['related']->getMIMEId()); if ($id = $ptr->getContentID()) { $info['related']->addCID(array($ptr->getMIMEId() => $id)); } } if (isset($info['rfc822'])) { $ptr->setInformation('rfc822_part', $info['rfc822']); } switch ($ptr->getType()) { case 'multipart/alternative': $new_info['alt'] = $ptr->getMIMEId(); break; case 'multipart/related': $new_info['related'] = &$ptr; break; case 'message/rfc822': $new_info['rfc822'] = $ptr->getMIMEId(); $ptr->setInformation('header', true); break; } MIME_Structure::addMultipartInfo($ptr->_parts, $new_info); } } /** * Attempts to build a MIME_Message object from a text message. * * @param string $text The text of the MIME message. * * @return MIME_Message A MIME_Message object, or false on error. */ function &<API key>($text) { /* Set up the options for the mimeDecode class. */ $decode_args = array( 'include_bodies' => true, 'decode_bodies' => false, 'decode_headers' => false ); require_once 'Mail/mimeDecode.php'; $mimeDecode = &new Mail_mimeDecode($text, MIME_PART_EOL); if (!($structure = $mimeDecode->decode($decode_args))) { $message = false; } else { /* Put the object into imap_parsestructure() form. */ MIME_Structure::<API key>($structure); $message = MIME_Structure::parse($structure); } return $message; } /** * Convert the output from mimeDecode::decode() into a structure that * matches imap_fetchstructure() output. * * @access private * * @param stdClass &$ob The output from mimeDecode::decode(). */ function <API key>(&$ob) { /* Primary content-type. */ if (!isset($ob->ctype_primary)) { $ob->ctype_primary = 'application'; $ob->ctype_secondary = 'octet-stream'; } $ob->type = intval(MIME::type($ob->ctype_primary)); /* Secondary content-type. */ if (isset($ob->ctype_secondary)) { $ob->subtype = String::upper($ob->ctype_secondary); $ob->ifsubtype = 1; } else { $ob->ifsubtype = 0; } /* Content transfer encoding. */ if (isset($ob->headers['<API key>'])) { $ob->encoding = MIME::encoding($ob->headers['<API key>']); } /* Content-type and Disposition parameters. */ $param_types = array('ctype_parameters' => 'parameters', 'd_parameters' => 'dparameters'); foreach ($param_types as $param_key => $param_value) { $if_var = 'if' . $param_value; if (isset($ob->$param_key)) { $ob->$if_var = 1; $ob->$param_value = array(); foreach ($ob->$param_key as $key => $val) { $newOb = &new stdClass; $newOb->attribute = $key; $newOb->value = $val; array_push($ob->$param_value, $newOb); } } else { $ob->$if_var = 0; } } /* Content-Disposition. */ if (isset($ob->headers['content-disposition'])) { $ob->ifdisposition = 1; $hdr = $ob->headers['content-disposition']; $pos = strpos($hdr, ';'); if ($pos !== false) { $hdr = substr($hdr, 0, $pos); } $ob->disposition = $hdr; } else { $ob->ifdisposition = 0; } /* Content-ID. */ if (isset($ob->headers['content-id'])) { $ob->ifid = 1; $ob->id = $ob->headers['content-id']; } else { $ob->ifid = 0; } /* Get file size (if 'body' text is set). */ if (isset($ob->body)) { $ob->bytes = strlen($ob->body); } /* Process parts also. */ if (isset($ob->parts)) { reset($ob->parts); while (list($key,) = each($ob->parts)) { MIME_Structure::<API key>($ob->parts[$key]); } } } /** * Builds an array consisting of MIME header/value pairs. * * @param string $headers A text string containing the headers (e.g. * output from imap_fetchheader()). * @param boolean $decode Should the headers be decoded? * @param boolean $lowercase Should the keys be in lowercase? * * @return array An array consisting of the header name as the key and * the header value as the value. * A header with multiple entries will be stored in * 'value' as an array. */ function parseMIMEHeaders($headers, $decode = true, $lowercase = false) { $header = $headval = ''; $ob = $toprocess = array(); foreach (explode("\n", $headers) as $val) { $val = rtrim($val); if (preg_match("/^([^\s]+)\:\s*(.*)/", $val, $matches)) { if (!empty($header)) { $toprocess[] = array($header, $headval); } $header = $matches[1]; $headval = $matches[2]; } else { $val = ltrim($val); if ($val) { $headval .= ' ' . ltrim($val); } else { break; } } } if (!empty($header)) { $toprocess[] = array($header, $headval); } foreach ($toprocess as $val) { if ($decode) { // Fields defined in RFC 2822 that contain address information if (in_array(String::lower($val[0]), array('from', 'to', 'cc', 'bcc', 'reply-to', 'resent-to', 'resent-cc', 'resent-bcc', 'resent-from', 'sender'))) { $val[1] = MIME::decodeAddrString($val[1]); } else { $val[1] = MIME::decode($val[1]); } } if (isset($ob[$val[0]])) { if (!is_array($ob[$val[0]])) { $temp = $ob[$val[0]]; $ob[$val[0]] = array(); $ob[$val[0]][] = $temp; } $ob[$val[0]][] = $val[1]; } else { $ob[$val[0]] = $val[1]; } } return ($lowercase) ? <API key>($ob, CASE_LOWER) : $ob; } }
package com.vmware.vim25; /** @author Steve Jin (sjin@vmware.com) */ public enum <API key> { inherit ("inherit"), vmDirectory ("vmDirectory"), hostLocal ("hostLocal"); private final String val; private <API key>(String val) { this.val = val; } }
#pragma once #include <memory> namespace DAVA { #if defined(<API key>) // FIX: replace DefaultSTLAllocator with TrackingAllocator after fixing framework and game codebases template <typename T> using DefaultSTLAllocator = std::allocator<T>; //using DefaultSTLAllocator = TrackingAllocator<T, ALLOC_POOL_DEFAULT>; #else template <typename T> using DefaultSTLAllocator = std::allocator<T>; #endif }
#import <UIKit/UIKit.h> #import <ABI39_0_0React/ABI39_0_0RCTBridge.h> #import <ABI39_0_0React/<API key>.h> typedef void (^<API key>)(int64_t progress, int64_t total); typedef void (^<API key>)(UIImage *image); typedef void (^<API key>)(NSError *error, UIImage *image); typedef dispatch_block_t <API key>; /** * Provides the interface needed to register an image loader. Image data * loaders are also bridge modules, so should be registered using * <API key>(). */ @protocol <API key> <<API key>> /** * Indicates whether this data loader is capable of processing the specified * request URL. Typically the handler would examine the scheme/protocol of the * URL to determine this. */ - (BOOL)canLoadImageURL:(NSURL *)requestURL; /** * Send a network request to load the request URL. The method should call the * progressHandler (if applicable) and the completionHandler when the request * has finished. The method should also return a cancellation block, if * applicable. */ - (<API key>)loadImageForURL:(NSURL *)imageURL size:(CGSize)size scale:(CGFloat)scale resizeMode:(<API key>)resizeMode progressHandler:(<API key>)progressHandler partialLoadHandler:(<API key>)partialLoadHandler completionHandler:(<API key>)completionHandler; @optional /** * If more than one <API key> responds YES to `-canLoadImageURL:` * then `loaderPriority` is used to determine which one to use. The loader * with the highest priority will be selected. Default priority is zero. If * two or more valid loaders have the same priority, the selection order is * undefined. */ - (float)loaderPriority; /** * If the loader must be called on the serial url cache queue, and whether the completion * block should be dispatched off the main thread. If this is NO, the loader will be * called from the main queue. Defaults to YES. * * Use with care: disabling scheduling will reduce <API key>'s ability to throttle * network requests. */ - (BOOL)requiresScheduling; /** * If images loaded by the loader should be cached in the decoded image cache. * Defaults to YES. */ - (BOOL)<API key>; @end
describe('Generic location view', function () { describe('opening an info window', function () { beforeEach(function () { spyOn(suApp.view.GenericLocationView.prototype, "render"); this.view = new suApp.view.GenericLocationView({ model: new Backbone.Model() }); }); it('should open infoWindow and pan to marker', function () { this.view.gmap = new google.maps.Map(); this.anchor = new google.maps.Anchor(); this.view.infoWindow = new suApp.view.InfoWindowView({ appModel: new suApp.model.AppModel() }); spyOn(this.view, 'getCenter').andCallFake(function () { return 2; }); spyOn(this.view.infoWindow, "open"); spyOn(this.view.gmap, "panTo"); spyOn(this.view.gmap, "panBy"); this.view.openInfoWindow(0, this.anchor); expect(this.view.gmap.panTo).toHaveBeenCalled(); expect(this.view.gmap.panBy).toHaveBeenCalled(); expect(this.view.infoWindow.open).<API key>(0, this.anchor, 2); }); }); describe('remove', function () { beforeEach(function () { spyOn(suApp.view.GenericLocationView.prototype, "render"); this.view = new suApp.view.GenericLocationView({ model: new Backbone.Model(), infoWindow: new suApp.view.InfoWindowView({ appModel: new suApp.model.AppModel() }) }); }); it('should close info window on remove', function () { spyOn(this.view.infoWindow, "close"); this.view.marker = {}; this.view.marker.setMap = function (foo) { }; this.view.remove(); expect(this.view.infoWindow.close).toHaveBeenCalled(); }); it('should clear map for marker', function () { var setMapHasRun = false; this.view.marker = {}; this.view.marker.setMap = function (foo) { setMapHasRun = true; }; this.view.remove(); expect(setMapHasRun).toBeTruthy(); }); it('should nullify marker', function () { this.view.marker = {}; this.view.marker.setMap = function (foo) { }; this.view.remove(); expect(this.view.marker).toBeNull(); }); }); describe('updateVisibility', function () { beforeEach(function () { suApp.view.GenericLocationView.prototype.render = function () { }; this.view = new suApp.view.GenericLocationView({ model: new suApp.model.Location(), infoWindow: new suApp.view.InfoWindowView({ appModel: new suApp.model.AppModel() }) }); }); it('should set visibility of model on marker', function () { this.view.marker = new google.maps.Marker(); spyOn(this.view.marker, 'setVisible'); this.view.model.set('visible', true); this.view.updateVisibility(); expect(this.view.marker.setVisible).<API key>(true); this.view.model.set('visible', false); this.view.updateVisibility(); expect(this.view.marker.setVisible).<API key>(false); }); }); describe('handleMarkerClick', function () { beforeEach(function () { suApp.view.GenericLocationView.prototype.render = function () { }; this.view = new suApp.view.GenericLocationView({ model: new suApp.model.Location(), infoWindow: new suApp.view.InfoWindowView({ appModel: new suApp.model.AppModel() }) }); }); it('should set trigger the "clicked" event on its model', function () { spyOn(this.view, 'openInfoWindow'); var clicked = false; this.view.model.on('clicked', function () { clicked = true; }); this.view.handleMarkerClick({latLng: ''}); expect(clicked).toBeTruthy(); }); it('should call openInfoWindow', function () { spyOn(this.view, 'openInfoWindow'); this.view.handleMarkerClick({latLng: ''}); expect(this.view.openInfoWindow).<API key>(this.view.model, this.view.marker); }); it('should set destination on infoWindow if directionAware=true', function () { spyOn(this.view, 'openInfoWindow'); spyOn(this.view.infoWindow, 'setDestination'); this.view.model.set('directionAware', true); this.view.handleMarkerClick({latLng: ''}); expect(this.view.infoWindow.setDestination).<API key>(this.view.getCenter()); }); it('should not set destination on infoWindow if directionAware=false', function () { spyOn(this.view, 'openInfoWindow'); spyOn(this.view.infoWindow, 'setDestination'); this.view.model.set('directionAware', false); this.view.handleMarkerClick({latLng: ''}); expect(this.view.infoWindow.setDestination).not.toHaveBeenCalled(); }); }); describe('getCenter', function () { beforeEach(function () { suApp.view.GenericLocationView.prototype.render = function () { }; }); it('should return correct results for point', function () { this.view = new suApp.view.GenericLocationView({ model: new suApp.model.Location({ coords: [ [10, 10] ] }) }); expect(this.view.getCenter().lat()).toEqual(10); expect(this.view.getCenter().lng()).toEqual(10); }); it('should return correct results for line', function () { this.view = new suApp.view.GenericLocationView({ model: new suApp.model.Location({ coords: [ [10, 10], [20, 20] ] }) }); expect(this.view.getCenter().lat()).toEqual(15); expect(this.view.getCenter().lng()).toEqual(15); }); it('should return correct results for polygon', function () { this.view = new suApp.view.GenericLocationView({ model: new suApp.model.Location({ coords: [ [10, 10], [20, 20], [10, 20], [20, 10] ] }) }); expect(this.view.getCenter().lat()).toEqual(15); expect(this.view.getCenter().lng()).toEqual(15); }); it('should return -1 for no GPoints', function () { this.view = new suApp.view.GenericLocationView({ model: new suApp.model.Location({ coords: [] }) }); expect(this.view.getCenter()).toEqual(-1); }); }); });
<?php namespace backend\models; use Composer\Package\Loader\<API key>; use Yii; use frontend\models\Chat; use frontend\models\Statistics; use frontend\models\Chatnot; /** * This is the model class for table "welcome". * * @property integer $u_id * @property string $lytis * @property string $orentacija * @property integer $amzius * @property string $msg */ const CREATED_OFFSET = 1462924800; class Welcome extends \yii\db\ActiveRecord { public $players; public $run = [ 'tryFirst', 'trySecond', 'tryThird', ]; public $ataskaita; /** * @inheritdoc */ public static function tableName() { return 'welcome'; } /** * @inheritdoc */ public function rules() { return [ [['u_id', 'lytis', 'orentacija', 'amzius'], 'required'], [['u_id', 'amzius'], 'integer'], [['msg'], 'string'], [['lytis'], 'string', 'max' => 1], [['orentacija'], 'string', 'max' => 225], [['u_id'], 'unique'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'u_id' => 'U ID', 'lytis' => 'Lytis', 'orentacija' => 'Orentacija', 'amzius' => 'Amzius', 'msg' => 'Msg', ]; } public function addToGame($id) { $model = \frontend\models\UserPack::find()->where(['id' => $id])->one(); if(!self::find()->where(['u_id' => $id])->one()) { $this->u_id = $model->id; $this->lytis = substr($model->info->iesko, 0, 1); $this->orentacija = $model->info->orentacija; $this->amzius = \frontend\models\Misc::getAmzius($model->info->diena, $model->info->menuo, $model->info->metai); if($this->save()) return true; }else{ Yii::$app->session->setFlash('warning', 'Šis narys jau pridėtas'); return true; } $pretty = function($v='',$c="&nbsp;&nbsp;&nbsp;&nbsp;",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'&lt;NULL&gt;':"<strong>$v</strong>");}return$r;}; echo $pretty($this->getErrors()); return false; } public function sendFfm($sender, $msg, $gavejas) { if($sender && $msg){ $gavejas->firstFakeMsg += 1; if($gavejas->ffmSenders === ''){ $gavejas->ffmSenders = $sender->id; }else{ $gavejas->ffmSenders = $gavejas->ffmSenders.",".$sender->id; } if($gavejas->save(false)) { $chat = new Chat; $chat->tryEmail($sender, $gavejas, true); $chat->sendMsgGlobal($sender->id, $gavejas->id, $msg); Statistics::addRecieved($gavejas->id); $not = new Chatnot; $not->insertNotGlobal($sender->id, $gavejas->id); }else{ Yii::$app->mailer->compose() ->setFrom('cronjob@pazintyslietuviams.co.uk') ->setTo('rokasr788@gmail.com') ->setSubject('Klaida: sendFFM') ->setHtmlBody('Neišsaugojo $gavejo Welcome->sendFfm(). UserPack modelio vardumpas: <br>'.var_dump($gavejas->getErrors())) ->send(); } } } public function getMsg($model) { $msgs = explode('||', $model->msg); $key = rand(0, count($msgs)-1); return $msgs[$key]; } public function getSender($user) { $id = null; $msg = null; $skirtumas = 3000; //jei nera info table tam zmogui if(!$user->info) return null; $iesko = substr($user->info->iesko, 1); $used = explode(',',$user->ffmSenders); $amzius = \frontend\models\Misc::getAmzius($user->info->diena, $user->info->menuo, $user->info->metai); //isrenka labiausiai atitinkanti siunteja foreach ($this->players as $model) { //lytis turi atikti zmogaus paieska if ($model->lytis == $iesko) { //sis zaidejas dar nebuvo parases FFM zmogui if (array_search($model->u_id, $used) === false) { //jei skirtumas yra mazesnis uz paskutini skirtuma if (abs($model->amzius - $amzius) < $skirtumas) { //patikrina ar toks zaidejas egzistuoja if($sender = \frontend\models\UserPack::find()->where(['id' => $model->u_id])->one()) { //zaidejas ir zmogus dar niekada nebuvo bendrave if(!\frontend\models\Chat::find()->where(['and',['sender' => $model->u_id, 'reciever' => $user->id]])->orWhere(['and',['reciever' => $model->u_id, 'sender' => $user->id]])->one()){ $skirtumas = abs($model->amzius - $amzius); $id = $sender; $msg = $this->getMsg($model); } }else{ $model->delete(); } } } } } //viskas gerai -> returnina siuntja if($id && $msg){ $sender = [ 'id' => $id, 'msg' => $msg ]; return $sender; } return null; } public function proceedWithQuery($users, $name) { set_time_limit(false); session_write_close(); $i = 0; foreach($users as $user){ if($s = $this->getSender($user)) { $this->sendFfm($s['id'], $s['msg'], $user); $this->ataskaita[$name][] = ['siuntejas' => $s['id'], 'gavejas' => $user->username, 'msg' => $s['msg']]; } $i++; if($i > 50){ $i = 0; sleep(1); } } } public function tryFirst() { //pasirenka publika $users = \frontend\models\UserPack::find() ->where(['firstFakeMsg' => 0]) ->andWhere(['<=', 'created_at', time() - 60 * 2]) ->andWhere(['>=', 'created_at', CREATED_OFFSET]) ->all(); $this->proceedWithQuery($users, 'tryFirst'); } public function trySecond() { //pasirenka publika $users = \frontend\models\UserPack::find() ->where(['firstFakeMsg' => 1]) ->andWhere(['<=', 'created_at', time() - 60 * 10]) ->andWhere(['>=', 'created_at', CREATED_OFFSET]) ->all(); $this->proceedWithQuery($users, 'trySecond'); } public function tryThird() { //pasirenka publika $users = \frontend\models\UserPack::find() ->where(['firstFakeMsg' => 2]) ->andWhere(['<=', 'created_at', time() - 60 * 60 * 27]) ->andWhere(['>=', 'expires', time()]) ->andWhere(['>=', 'created_at', CREATED_OFFSET]) ->all(); $this->proceedWithQuery($users, 'tryThird'); } public function trySend() { //pupulates players $this->players = self::find()->all(); foreach ($this->run as $v) $this->$v(); $pretty = function($v='',$c="&nbsp;&nbsp;&nbsp;&nbsp;",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'&lt;NULL&gt;':"<strong>$v</strong>");}return$r;}; echo $pretty($this->ataskaita); } }
package kiwi.service.revision; import java.io.IOException; import java.io.Serializable; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.Stateless; import javax.mail.<API key>; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.<API key>; import javax.xml.parsers.<API key>; import kiwi.api.config.<API key>; import kiwi.api.content.ContentItemService; import kiwi.api.revision.<API key>; import kiwi.api.revision.<API key>; import kiwi.api.transaction.TransactionService; import kiwi.api.triplestore.TripleStore; import kiwi.exception.<API key>; import kiwi.exception.<API key>; import kiwi.exception.<API key>; import kiwi.exception.<API key>; import kiwi.exception.<API key>; import kiwi.exception.<API key>; import kiwi.model.Constants; import kiwi.model.content.ContentItem; import kiwi.model.content.ContentItemI; import kiwi.model.content.TextContent; import kiwi.model.revision.CIVersion; import kiwi.model.revision.TextContentUpdate; import kiwi.model.revision.<API key>; import kiwi.util.KiWiStringUtils; import nu.xom.Attribute; import nu.xom.Builder; import nu.xom.Document; import nu.xom.Element; import nu.xom.<API key>; import nu.xom.Node; import nu.xom.Nodes; import nu.xom.ParsingException; import nu.xom.Text; import nu.xom.ValidityException; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.log.Log; /** * This service prepares textcontent changes for updates. * It is committed when transaction reached the beforeCompletion() * method. * @author Stephanie Stroka * (sstroka@salzburgresearch.at) * */ @Stateless @Name("<API key>") @AutoCreate @Scope(ScopeType.STATELESS) public class <API key> implements Serializable, <API key>, <API key> { /** * Generated serialization id */ private static final long serialVersionUID = 1L; /** * injected Logger */ @Logger private static Log log; /** * transaction service, needed to add the update to a transaction resource */ @In private TransactionService transactionService; @In private EntityManager entityManager; /* (non-Javadoc) * @see kiwi.api.revision.<API key>#updateTextContent(kiwi.model.content.ContentItem, java.lang.String) */ public TextContentUpdate updateTextContent(ContentItemI itemI, TextContent tc) { ContentItem item = itemI.getDelegate(); // first check if the content item contains a collection of revisions if(item.getVersions() == null) { // if it doesn't, create one item.setVersions(new ArrayList<CIVersion>()); } // create new TextContentUpdate TextContentUpdate tcu = new TextContentUpdate(); TextContent old = null; String lastContent = null; // does a text content exist? if(item.getTextContent() == null) { /*Can't use storingPipeline here, concurrent access to the storingPipeline * if this service called from a savelet (ComponentSavelet * needs to use the updateTextContent service to update the components) */ //lastContent = storingPipeline.processHtmlSource(item.getResource(), " "); lastContent = "<div xmlns=\"http: } else { old = item.getTextContent(); lastContent = old.getXmlString(); } // generate changes between previous and current text content List<<API key>> changes = generateChanges(tc.getXmlString(), lastContent); tcu.setChanges(changes); tcu.setTextContent(tc); EntityManager entityManager = (EntityManager) Component.getInstance("entityManager"); TripleStore tripleStore = (TripleStore) Component.getInstance("tripleStore"); entityManager.persist(tc); tripleStore.persist(item); // kiwiEntityManager.persist(item); // add this update to the current transaction data try { transactionService.<API key>(item).<API key>(tcu); log.debug("<API key>.updateTextContent() called ts.<API key>()"); } catch (<API key> e) { e.printStackTrace(); } return tcu; } /** * generates the changes between original and modified text * @param curXMLContent * @param prevXMLContent * @return a list of diffs between original and modified text */ public List<<API key>> generateChanges( String curXMLContent, String prevXMLContent ) { // preparing the text means to add spaces between tags, // to delete line feeds and to put replacement character // for spaces inside of a tag curXMLContent = KiWiStringUtils.prepareHtmlText(curXMLContent); curXMLContent.trim(); prevXMLContent = KiWiStringUtils.prepareHtmlText(prevXMLContent); prevXMLContent.trim(); // create a list of strings of the words in the previous text List<String> origwords = new ArrayList<String>( Arrays.asList(prevXMLContent.split(" ")) ); // and remove all empty entries while(origwords.remove("")); // create a list of strings of the words in the current text List<String> modwords = new ArrayList<String>( Arrays.asList(curXMLContent.split(" ")) ); // and remove all empty entries while(modwords.remove("")); // return the differenced listed in a string return LCS.diff(origwords, modwords); } /** * Surrounds the word(s) that have changed with a style tag. * @param content * @param additionalAtts * @return */ private Element addRevStyleElement(String content, Attribute... additionalAtts) { // create a new <span> element Element span = new Element("span"); span.addAttribute(new Attribute("class" ,"revision")); if(additionalAtts != null) { for(int i = 0; i < additionalAtts.length; i++) { span.addAttribute(additionalAtts[i]); } } // and add the string with a space as a child node span.appendChild(content + " "); return span; } /** * Surrounds the word(s) that have been deleted with a style tag. * @param content * @param additionalAtts * @return */ private Element <API key>(String content, Attribute... additionalAtts) { // create a new <span> element Element span = new Element("span"); span.addAttribute(new Attribute("class" ,"revision_deleted")); if(additionalAtts != null) { for(int i = 0; i < additionalAtts.length; i++) { span.addAttribute(additionalAtts[i]); } } // and add the string with a space as a child node span.appendChild(content + " "); return span; } /** * Returns the xom-node that has been changed in the TextContentUpdate. * * @param currentDoc * @param d * @return * @throws <API key> */ private Node getDiffNode(Document currentDoc, <API key> d) throws <API key> { Nodes nodes = currentDoc.query(d.getXPath()); if(currentDoc == null) { log.error("Queried node #0 is null", d.getXPath()); return null; } log.info("Document: #0 ", currentDoc.toXML()); // we expect the nodelist to contain just 1 node if(nodes.size() != 1) { throw new <API key>("Expected one node, but received: " + nodes.size()); } return nodes.get(0); } /** * * @param keySet * @param n * @return * @throws Exception */ private Set<String> checkSurroundingTag(Set<String> keySet, Node n) throws Exception { DecimalFormat df = new DecimalFormat("000000"); if(keySet.contains("000000.000000") && keySet.contains(df.format(999999) + ".000000")) { log.debug("Node has been added"); // create a new element <span> Element info = new Element("span"); info.addAttribute(new Attribute("class", "info")); Element text = new Element("span"); text.addAttribute(new Attribute("class", "text")); text.appendChild("Format has changed"); info.appendChild(text); n.getParent().replaceChild(n, info); info.appendChild(n); if(!keySet.remove("000000.000000")) { log.error("The element \"000000.000000\" has to be removable"); } if(!keySet.remove(df.format(999999) + ".000000")) { log.error("The element \""+df.format(999999) +".000000\" has to be removable"); } } else if(keySet.contains("000000.000000")) { log.error("Opening tag has been added, but closing tag hasn't!"); throw new <API key>("Closing tag has been added, but openening tag hasn't!"); } else if(keySet.contains(df.format(999999) + ".000000")) { log.error("Closing tag has been added, but openening tag hasn't!"); throw new <API key>("Closing tag has been added, but openening tag hasn't!"); } return keySet; } /** * Helper method that extracts the name of the tag from the tag. * @param str * @return */ private Element <API key>(String str, Map<String,String> allNamespaces) { if(!str.startsWith("</") && str.startsWith("<")) { String[] tmp = str.split("[{]attrGap[}]"); // delete the first '<' String tmpTag = tmp[0].substring(1); String tag = new String(); if(tmpTag.toString().endsWith("/>")) { // delete the last two characters '/>' tag = tmpTag.substring(0, tmpTag.length()-2); } else if (tmpTag.toString().endsWith(">")) { // delete the last character '>' tag = tmpTag.substring(0, tmpTag.length()-1); } else { tag = tmpTag; } Element element = new Element(tag); // ensure that all namespaces are declared for(String prefix : allNamespaces.keySet()) { log.info("========== prefix: #0 ", prefix); log.info("========== uri: #0 ", allNamespaces.get(prefix)); if(!prefix.isEmpty()) { element.<API key>(prefix, allNamespaces.get(prefix)); } } for(int i = 1; i < tmp.length; i++) { String[] attrArray = tmp[i].split("=\""); if(attrArray.length != 2) { attrArray = tmp[i].split("='"); } if(attrArray.length == 2) { String value = attrArray[1].substring(0, attrArray[1].length()-1); String wholeAttrName = attrArray[0]; String[] attrName = attrArray[0].split(":"); String prefix = null; String name = null; if(attrName.length == 2) { prefix = attrName[0]; name = attrName[1]; log.info("prefix for attribute: #0 is #1 ", name, prefix); } else { name = attrName[0]; log.info("attribute: #0 does not have a prefix ", name); } try { if(prefix != null && !prefix.equals("xmlns")) { element.addAttribute(new Attribute(wholeAttrName, allNamespaces.get(prefix), value)); } else { element.addAttribute(new Attribute(name, value)); } } catch (<API key> e) { log.error("Element attribute #0 does not have a declared namespace", attrArray[0]); } } } return element; } return null; } /** * Adds space characters and the word to the new formatted text. * @param newContent * @param word * @throws <API key> */ private void appendTextBuffer(StringBuilder newContent, String word) throws <API key> { // check if the current textposition is NOT marked as a changed word position .. // for every word that hasn't changed, add it to the buffer if(newContent.length()>0 && !newContent.toString().endsWith(" ")) { log.debug("Adding word #0 ", word); newContent.append(" " + word + " "); } else { log.debug("Adding word #0 ", word); newContent.append(word + " "); } } /** * Sets the <span style..> tags for displaying revision changes * @param current * @param currentPos * @param diff * @param styled * @param showDeleted shows or doesn't show the deleted words * @return a list of strings which form a preview of the styled text * @throws Exception */ public nu.xom.Document setStyleWithXOM(nu.xom.Document doc, List<<API key>> diff, Long revisionId, boolean showDeleted) throws Exception { Collections.sort(diff); // deep copy, do not violate the original document nu.xom.Document currentDoc = (Document) doc.copy(); for(<API key> d : diff) { Set<String> keySet = new HashSet<String>( d.getChangedWordsMap().keySet() ); // query the diff node Node node = null; try { node = getDiffNode(currentDoc, d); } catch (<API key> e1) { log.error("Expected one node"); return currentDoc; } Element newElement = null; Element e = null; // if the node is an Element we can cast it if(node instanceof Element) { e = (Element) node; newElement = new Element(e.getQualifiedName()); } else { log.error("Expected an element, but was: #0 ", node.getClass()); return currentDoc; } keySet = checkSurroundingTag(keySet, node); // get the positions that indicate // changed words in this xpath location List<String> positions = new ArrayList<String>( keySet ); // sort the positions Collections.sort(positions); log.debug("Positions in xpath #0: #1 ", d.getXPath(), positions); Iterator<String> iter = positions.iterator(); // if there exist no positions -> break for loop if(iter.hasNext()) { Integer wordCountInXPath = new Integer(0); // new string buffer for text content StringBuilder newContent = new StringBuilder(); Integer position = null; Integer fraction = null; String sPos = null; boolean interrupt = false; log.debug("This element contains #0 nodes", e.getChildCount()); // get the child nodes of this node for(int i=0; i<e.getChildCount(); i++) { Node child = e.getChild(i); // if there is a text child node .... if(child instanceof Text) { if(!interrupt) { wordCountInXPath++; } Text c = (Text) child; log.debug("Node is a text: #0 ", c.getValue()); // split the text into words List<String> text = new ArrayList<String>(Arrays.asList(c.getValue().trim().split(" "))); while(text.remove("")); if(!interrupt) { if(iter.hasNext()) { sPos = iter.next(); if(sPos.split("\\.") != null && sPos.split("\\.").length == 2) { position = new Integer(sPos.split("\\.")[0]); fraction = new Integer(sPos.split("\\.")[1]); } else { position = new Integer(sPos); fraction = new Integer(0); } log.debug("checking word at position #0 with fraction #1 ", position, fraction); } else { position = null; fraction = null; log.debug("There are no more changed positions"); } } else { interrupt = false; } int tmpAmountOfWords = wordCountInXPath+text.size()-1; log.debug("tmpAmountOfWords: #0 ", tmpAmountOfWords); // if the position is not in that element if(position == null || position > tmpAmountOfWords) { // just add the element Text newText = (Text) c.copy(); newElement.appendChild(newText); // and append a space character to the buffer newContent.append(" "); wordCountInXPath = tmpAmountOfWords + 1; } // else if the position is in that element else { // iterate through the text for(String word : text) { Element deletedElement = null; log.debug("Checking word: #0 ", word); // while the amount of words unter // that xpath are less than the // position at which a word has changed if(position == null || (fraction != null && !fraction.equals(0) && wordCountInXPath.equals(position)) || wordCountInXPath < position) { if(position != null && wordCountInXPath < position) { log.debug("wordCountInXPath #0 < position #1 ", wordCountInXPath, position); } else if(position != null && (fraction != null && !fraction.equals(0) && wordCountInXPath.equals(position))) { log.debug("wordCountInXPath #0 <= position #1 ", wordCountInXPath, position); } else { log.debug("appending the rest of the text, wordCountInXPath #0", wordCountInXPath); } try { // append the unchanged text appendTextBuffer(newContent, word); wordCountInXPath++; } catch (<API key> e1) { throw new <API key>("Style could not be created"); } } else if(position != null && position > tmpAmountOfWords) { log.error("Position ( #0 ) cannot be bigger than text size ( #1 ) ", position, text.size()); } else if(position != null && fraction.equals(0) && wordCountInXPath >= position) { log.debug("At this position #0 , something has been changed", position); // if there is something in the buffer, // append it as a text node if(newContent.length()>0) { newElement.appendChild(newContent.toString()); newContent = new StringBuilder(); } newElement.appendChild(addRevStyleElement(word)); wordCountInXPath++; if(iter.hasNext()) { sPos = iter.next(); if(sPos.split("\\.") != null && sPos.split("\\.").length == 2) { position = new Integer(sPos.split("\\.")[0]); fraction = new Integer(sPos.split("\\.")[1]); } else { position = new Integer(sPos); fraction = new Integer(0); } log.debug("checking word at position #0 with fraction #1 ", position, fraction); } else { sPos = null; position = null; log.debug("There are no more changed positions"); } } if(position != null && wordCountInXPath > position) { Integer lastPosition = position; while(position != null && ((lastPosition.equals(position) && !fraction.equals(0)) || position == 0)) { // if there is something in the buffer, // append it as a text node if(newContent.length()>0) { newElement.appendChild(newContent.toString()); newContent = new StringBuilder(); } // we add the string and decorate it with a 'text-decoration: line-through' style String prevWord; if((prevWord = d.getChangedWordsMap().get(sPos)) != null) { prevWord = prevWord.trim(); if(showDeleted && !prevWord.equals("")) { // finally, append the new element if(prevWord.startsWith("<")) { if(!prevWord.startsWith("</")) { Map<String,String> namespaces = extractNamespaces(currentDoc); deletedElement = <API key>(prevWord, namespaces); } else { if(deletedElement != null) { newElement.appendChild(deletedElement); deletedElement = null; } } } else { if(deletedElement != null) { deletedElement.appendChild(<API key>(prevWord)); } else { newElement.appendChild(<API key>(prevWord)); } } } } if(iter.hasNext()) { sPos = iter.next(); if(sPos.split("\\.") != null && sPos.split("\\.").length == 2) { position = new Integer(sPos.split("\\.")[0]); fraction = new Integer(sPos.split("\\.")[1]); } else { position = new Integer(sPos); fraction = new Integer(0); } log.debug("checking word at position #0 with fraction #1 ", position, fraction); } else { lastPosition = -1; sPos = null; position = null; log.debug("There are no more changed positions"); } } } } // if there is something in the buffer, // append it as a text node if(newContent.length()>0) { newElement.appendChild(newContent.toString()); newContent = new StringBuilder(); } } } // if the child is another element (e.g. <b> ..) else if (child instanceof Element){ log.debug("Node is another element: #0 ", ((Element) child).getLocalName()); // if we don't have any changes at this // position, just add the element Element newChild = (Element) child.copy(); newElement.appendChild(newChild); // and append a space character to the buffer newContent.append(" "); interrupt = true; } } // replace the previous node with the new node node.getParent().replaceChild(node, newElement); } log.info("Document: #0 ", currentDoc.toXML()); } return currentDoc; } private Map<String, String> extractNamespaces(Document currentDoc) { Map<String, String> namespaces = new HashMap<String, String>(); Element root = currentDoc.getRootElement(); for(int j=0; j<root.<API key>(); j++) { String prefix = root.getNamespacePrefix(j); namespaces.put(prefix, root.getNamespaceURI(prefix)); } return namespaces; } /* * (non-Javadoc) * @see kiwi.api.revision.<API key>#createPreview( * kiwi.model.revision.TextContentUpdate, * kiwi.api.revision.<API key>.PreviewStyle, * boolean) */ public String createPreview(CIVersion version, PreviewStyle style, boolean showDeleted) { String preview = null; EntityManager entityManager = (EntityManager) Component.getInstance("entityManager"); if(version.<API key>() == null) { javax.persistence.Query q = entityManager.createNamedQuery("version.lastTextContent"); q.setParameter("ci", version.<API key>()); q.setParameter("vid", version.getVersionId()); q.setMaxResults(1); TextContent textContent; try { textContent = (TextContent) q.getSingleResult(); preview = textContent.getHtmlContent(); } catch (NoResultException e) { preview = "<div xmlns=\"http: .NS_KIWI_HTML+"\" kiwi:type=\"page\"><i>Initial ContentItem creation</i></div>"; } } else { TextContentUpdate tcu = version.<API key>(); switch (style) { case LAST: if((preview = tcu.getPreviewText()) == null) { TextContent tc = tcu.getTextContent(); Document doc = tc.getXmlDocument(); // creates a styled xml tree try { doc = setStyleWithXOM(doc, tcu.getChanges(), version.getVersionId(), showDeleted); } catch (<API key> e) { e.printStackTrace(); log.error("#0", e); } catch (<API key> e) { e.printStackTrace(); log.error("#0", e); } catch(Exception e) { e.printStackTrace(); log.error("#0", e); } finally { log.info("Document: #0 ", doc.toXML()); preview = doc.toXML(); } } break; case ALLAUTHORS: if((preview = tcu.getPreviewText()) == null) { <API key> conf = (<API key>) Component .getInstance("<API key>"); try { Builder build = new Builder(); TextContent tc = tcu.getTextContent(); Document doc = build.build(tc.getXmlString(), conf.getBaseUri()); // creates a styled xml tree try { doc = setStyleWithXOM(doc, tcu.getChanges(), version.getVersionId(), showDeleted); } catch (<API key> e) { log.error("#0", e); e.printStackTrace(); } catch (<API key> e) { log.error("#0", e); e.printStackTrace(); } catch(Exception e) { log.error("#0", e); e.printStackTrace(); } finally { log.info("Document: #0 ", doc.toXML()); preview = doc.toXML(); } } catch (ValidityException e) { log.error("#0", e); } catch (ParsingException e) { log.error("#0", e); } catch (IOException e) { log.error("#0", e); } } break; case ALLUPDATES: if((preview = tcu.getPreviewText()) == null) { <API key> conf = (<API key>) Component .getInstance("<API key>"); try { Builder build = new Builder(); TextContent tc = tcu.getTextContent(); Document doc = build.build(tc.getXmlString(), conf.getBaseUri()); // creates a styled xml tree try { doc = setStyleWithXOM(doc, tcu.getChanges(), version.getVersionId(), showDeleted); } catch (<API key> e) { log.error("#0", e); e.printStackTrace(); } catch (<API key> e) { log.error("#0", e); e.printStackTrace(); } catch(Exception e) { log.error("#0", e); e.printStackTrace(); } finally { log.info("Document: #0 ", doc.toXML()); preview = doc.toXML(); } } catch (ValidityException e) { log.error("#0", e); } catch (ParsingException e) { log.error("#0", e); } catch (IOException e) { log.error("#0", e); } } break; default: break; } } return preview; } /** * converts org.w3c.dom.Document into nu.xom.Document * @param dom * @return */ public nu.xom.Document dom2xom( org.w3c.dom.Document dom ) { return nu.xom.converters.DOMConverter.convert(dom); } /** * converts a nu.xom.Document into org.w3c.dom.Document * @param xom * @return */ public org.w3c.dom.Document xom2dom( nu.xom.Document xom ) { try { <API key> factory = <API key>.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return nu.xom.converters.DOMConverter.convert(xom, builder.<API key>()); } catch (<API key> e) { e.printStackTrace(); return null; } } /* (non-Javadoc) * @see kiwi.api.revision.<API key>#undo(kiwi.model.revision.TextContent.TextContentUpdate) */ public void restore(CIVersion vers) { TextContent tc = null; EntityManager entityManager = (EntityManager) Component.getInstance("entityManager"); ContentItemService cis = (ContentItemService) Component.getInstance("contentItemService"); ContentItem item = vers.<API key>(); if(vers.<API key>() == null) { javax.persistence.Query q = entityManager.createNamedQuery("version.lastTextContent"); q.setParameter("ci",vers.<API key>()); q.setParameter("vid",vers.getVersionId()); q.setMaxResults(1); try { tc = (TextContent) q.getSingleResult(); } catch (NoResultException ex) { // this should never happen if you call it from inside the Wiki, // because the RenderingPipeline is always creating a TextContent log.debug("No previous textcontent to restore. Thus, we just delete the current TextContent."); } } else { tc = vers.<API key>().getTextContent(); } if(tc != null) { cis.<API key>(item, tc.getXmlString()); } else { cis.<API key>(item, ""); } } /* (non-Javadoc) * @see kiwi.api.revision.<API key>#commitUpdate(kiwi.model.revision.TextContent.TextContentUpdate) */ public void commitUpdate(CIVersion version) { if(version.<API key>() != null) { entityManager.persist(version.<API key>()); } } /* (non-Javadoc) * @see kiwi.api.revision.<API key>#rollbackUpdate(kiwi.model.revision.TextContent.TextContentUpdate) */ public void rollbackUpdate(CIVersion version) { version.<API key>(null); } /* * (non-Javadoc) * @see kiwi.api.revision.KiWiUpdateService#undo(kiwi.model.revision.CIVersion) */ @Override public void undo(CIVersion version) throws <API key> { try { throw new <API key>("<API key>.restore(CIVersion version) is not supported"); } catch (<API key> e) { e.printStackTrace(); } } }
<body><h2>Population Estimates with k shares per contributor using dtree and attribute selection method non_zero</h2><table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>all</th> <th>giraffes</th> <th>zebras</th> </tr> <tr> <th>num_images</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>2</th> <td>1408.000000</td> <td>48.000000</td> <td>34680.000000</td> </tr> <tr> <th>3</th> <td>981.666667</td> <td>60.000000</td> <td>1050.000000</td> </tr> <tr> <th>4</th> <td>1666.666667</td> <td>84.000000</td> <td>1887.000000</td> </tr> <tr> <th>5</th> <td>2170.666667</td> <td>90.000000</td> <td>2521.500000</td> </tr> <tr> <th>6</th> <td>2358.750000</td> <td>105.000000</td> <td>2480.000000</td> </tr> <tr> <th>7</th> <td>3105.000000</td> <td>111.000000</td> <td>3325.000000</td> </tr> <tr> <th>8</th> <td>3712.500000</td> <td>117.000000</td> <td>4011.000000</td> </tr> <tr> <th>9</th> <td>3521.600000</td> <td>82.000000</td> <td>4734.666667</td> </tr> <tr> <th>10</th> <td>4102.800000</td> <td>92.000000</td> <td>5476.000000</td> </tr> <tr> <th>11</th> <td>4777.000000</td> <td>92.000000</td> <td>6480.000000</td> </tr> <tr> <th>12</th> <td>5310.000000</td> <td>92.000000</td> <td>7281.333333</td> </tr> <tr> <th>13</th> <td>6028.800000</td> <td>92.000000</td> <td>8372.000000</td> </tr> <tr> <th>14</th> <td>5070.000000</td> <td>96.000000</td> <td>5959.000000</td> </tr> <tr> <th>15</th> <td>4353.666667</td> <td>127.500000</td> <td>4679.142857</td> </tr> <tr> <th>16</th> <td>3517.083333</td> <td>104.000000</td> <td>3899.777778</td> </tr> <tr> <th>17</th> <td>3527.615385</td> <td>108.000000</td> <td>3818.000000</td> </tr> <tr> <th>18</th> <td>3258.333333</td> <td>112.000000</td> <td>3440.000000</td> </tr> <tr> <th>19</th> <td>3249.187500</td> <td>114.000000</td> <td>3386.153846</td> </tr> <tr> <th>20</th> <td>3238.941176</td> <td>114.000000</td> <td>3346.285714</td> </tr> <tr> <th>21</th> <td>3076.578947</td> <td>114.000000</td> <td>3128.125000</td> </tr> <tr> <th>22</th> <td>3039.600000</td> <td>116.000000</td> <td>3066.941176</td> </tr> <tr> <th>23</th> <td>3114.400000</td> <td>120.000000</td> <td>3136.294118</td> </tr> <tr> <th>24</th> <td>3016.363636</td> <td>128.000000</td> <td>3005.526316</td> </tr> <tr> <th>25</th> <td>3120.869565</td> <td>128.000000</td> <td>3103.100000</td> </tr> <tr> <th>26</th> <td>3195.500000</td> <td>130.000000</td> <td>3164.476190</td> </tr> <tr> <th>27</th> <td>2935.111111</td> <td>134.000000</td> <td>2856.416667</td> </tr> <tr> <th>28</th> <td>2876.896552</td> <td>156.333333</td> <td>2766.000000</td> </tr> <tr> <th>29</th> <td>2864.533333</td> <td>156.333333</td> <td>2750.370370</td> </tr> <tr> <th>30</th> <td>2994.866667</td> <td>158.666667</td> <td>2880.111111</td> </tr> <tr> <th>31</th> <td>3141.866667</td> <td>165.666667</td> <td>3012.592593</td> </tr> <tr> <th>32</th> <td>3168.000000</td> <td>168.000000</td> <td>3029.642857</td> </tr> <tr> <th>33</th> <td>3141.750000</td> <td>175.000000</td> <td>2983.655172</td> </tr> <tr> <th>34</th> <td>3094.818182</td> <td>179.666667</td> <td>2924.100000</td> </tr> <tr> <th>35</th> <td>3137.911765</td> <td>205.333333</td> <td>2946.580645</td> </tr> <tr> <th>36</th> <td>3069.916667</td> <td>208.000000</td> <td>2869.090909</td> </tr> <tr> <th>37</th> <td>3150.000000</td> <td>213.333333</td> <td>2950.606061</td> </tr> <tr> <th>38</th> <td>3172.162162</td> <td>213.333333</td> <td>2970.000000</td> </tr> <tr> <th>39</th> <td>3152.000000</td> <td>213.333333</td> <td>2947.714286</td> </tr> <tr> <th>40</th> <td>3075.000000</td> <td>213.333333</td> <td>2865.789474</td> </tr> <tr> <th>41</th> <td>3090.214286</td> <td>213.333333</td> <td>2879.794872</td> </tr> <tr> <th>42</th> <td>3159.809524</td> <td>213.333333</td> <td>2948.846154</td> </tr> <tr> <th>43</th> <td>3145.465116</td> <td>216.000000</td> <td>2930.350000</td> </tr> <tr> <th>44</th> <td>3171.159091</td> <td>216.000000</td> <td>2955.365854</td> </tr> <tr> <th>45</th> <td>3132.434783</td> <td>218.666667</td> <td>2916.372093</td> </tr> <tr> <th>46</th> <td>3213.913043</td> <td>224.000000</td> <td>2987.534884</td> </tr> <tr> <th>47</th> <td>3150.000000</td> <td>224.000000</td> <td>2926.044444</td> </tr> <tr> <th>48</th> <td>3220.500000</td> <td>224.000000</td> <td>2995.777778</td> </tr> <tr> <th>49</th> <td>3261.224490</td> <td>189.000000</td> <td>3087.200000</td> </tr> <tr> <th>50</th> <td>3304.000000</td> <td>210.000000</td> <td>3117.466667</td> </tr> <tr> <th>51</th> <td>3308.235294</td> <td>212.500000</td> <td>3116.042553</td> </tr> <tr> <th>52</th> <td>3368.647059</td> <td>212.500000</td> <td>3176.425532</td> </tr> <tr> <th>53</th> <td>3382.500000</td> <td>212.500000</td> <td>3189.625000</td> </tr> <tr> <th>54</th> <td>3457.269231</td> <td>212.500000</td> <td>3265.000000</td> </tr> <tr> <th>55</th> <td>3504.346154</td> <td>215.000000</td> <td>3307.333333</td> </tr> <tr> <th>56</th> <td>3528.000000</td> <td>215.000000</td> <td>3331.125000</td> </tr> <tr> <th>57</th> <td>3565.769231</td> <td>215.000000</td> <td>3368.750000</td> </tr> <tr> <th>58</th> <td>3632.596154</td> <td>217.500000</td> <td>3430.666667</td> </tr> <tr> <th>59</th> <td>3592.528302</td> <td>217.500000</td> <td>3389.448980</td> </tr> <tr> <th>60</th> <td>3635.773585</td> <td>217.500000</td> <td>3433.673469</td> </tr> <tr> <th>61</th> <td>3531.272727</td> <td>217.500000</td> <td>3326.980392</td> </tr> <tr> <th>62</th> <td>3623.272727</td> <td>217.500000</td> <td>3418.352941</td> </tr> <tr> <th>63</th> <td>3614.035714</td> <td>220.000000</td> <td>3403.615385</td> </tr> <tr> <th>64</th> <td>3665.125000</td> <td>220.000000</td> <td>3455.000000</td> </tr> <tr> <th>65</th> <td>3655.298246</td> <td>220.000000</td> <td>3443.811321</td> </tr> <tr> <th>66</th> <td>3674.385965</td> <td>220.000000</td> <td>3463.660377</td> </tr> <tr> <th>67</th> <td>3748.684211</td> <td>220.000000</td> <td>3538.301887</td> </tr> <tr> <th>68</th> <td>3739.500000</td> <td>222.500000</td> <td>3523.703704</td> </tr> <tr> <th>69</th> <td>3795.362069</td> <td>225.000000</td> <td>3575.000000</td> </tr> <tr> <th>70</th> <td>3846.793103</td> <td>225.000000</td> <td>3626.666667</td> </tr> <tr> <th>71</th> <td>3880.706897</td> <td>225.000000</td> <td>3661.925926</td> </tr> <tr> <th>72</th> <td>3842.084746</td> <td>225.000000</td> <td>3621.781818</td> </tr> <tr> <th>73</th> <td>3917.542373</td> <td>227.500000</td> <td>3693.381818</td> </tr> <tr> <th>74</th> <td>3978.305085</td> <td>227.500000</td> <td>3753.818182</td> </tr> </tbody> </table><iframe id="igraph" scrolling="no" style="border:none;" seamless="seamless" src="https://plot.ly/~smenon8/281.embed" height="525px" width="100%"></iframe></body>
<?php use yii\helpers\Url; ?> <script type="text/javascript"> </script> <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-content text-center p-md"> <h2><span class="text-navy">INSPINIA 55555 - Responsive Admin Theme</span> is provided with two main layouts <br/>three skins and separate configure options.</h2> <textarea type="text" name="content" id="content">waerewfwef</textarea> <button type="submit" class="btn btn-danger copyeditor">Save</button> <p> <button onclick="contestButton_click()" id="contestButton" type="button" class="btn btn-w-m btn-success">Contest</button> <button onclick="reviewButton_click()" id="reviewButton" type="button" class="btn btn-w-m btn-success">Review</button> <button onclick="videoButton_click()" id="videoButton" type="button" class="btn btn-w-m btn-success">Video / Image</button> </p> </div> </div> </div> </div> <div id="contest_frame" class="row animated fadeInRight" style="display:none"> <div class="col-lg-5"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Create New Contest</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="dropdown-toggle" data-toggle="dropdown" href=" <i class="fa fa-wrench"></i> </a> <ul class="dropdown-menu dropdown-user"> <li><a href="#">Config option 1</a> </li> <li><a href="#">Config option 2</a> </li> </ul> </div> </div> <div class="ibox-content"> <form class="form-horizontal"> <p>Let we know your contest's name.</p> <div class="form-group"><label class="col-lg-3 control-label">Contest Name</label> <div class="col-lg-10"><input type="email" placeholder="Email" class="form-control"> <span class="help-block m-b-none">Example block-level help text here.</span> </div> </div> <div class="text-center"> <a data-toggle="modal" class="btn btn-primary" href="#modal-form">Form in simple modal box</a> </div> </form> </div> </div> </div> </div> <div id="videoimage_frame" class="row animated fadeInRight" style="display:none"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-content text-center p-md"> <h4 class="m-b-xxs">Video :: Image Layout <span class="label label-primary">NEW</span></h4> <small>(optional layout)</small> <p>Avalible configure options</p> <span class="simple_tag">Scroll navbar</span> <span class="simple_tag">Boxed layout</span> <span class="simple_tag">Scroll footer</span> <span class="simple_tag">Fixed footer</span> <div class="m-t-md"> <p>Check the Outlook view in in full height page</p> <div class="p-lg "> <a href="full_height.html"><img class="img-responsive img-shadow" src="img/full_height.jpg" alt=""></a> </div> </div> </div> </div> </div> </div> <div id="review_frame" class="row animated fadeInLeft" style="display:none"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Wyswig Summernote Editor</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> <a class="dropdown-toggle" data-toggle="dropdown" href=" <i class="fa fa-wrench"></i> </a> <ul class="dropdown-menu dropdown-user"> <li><a href="#">Config option 1</a> </li> <li><a href="#">Config option 2</a> </li> </ul> </div> </div> <div class="ibox-content no-padding"> <div class="summernote"> <h3>Lorem Ipsum is simply</h3> ly unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with <br/> <br/> <ul> <li>Remaining essentially unchanged</li> <li>Make a type specimen book</li> <li>Unknown printer</li> </ul> </div> </div> </div> </div> </div> </div> <?php $this->beginBlock('JavascriptInit'); ?> <script> $(document).ready(function(){ $('.summernote').summernote(); var sHTML = $('.summernote').code(); alert(sHTML); }); var edit = function() { alert('edit!'); $('.click2edit').summernote({focus: true}); }; var save = function() { var aHTML = $('.click2edit').code(); //save HTML If you need(aHTML: array). $('.click2edit').destroy(); }; $(".copyeditor").on("click", function() { var targetName = $("#editor").attr('data-target'); $('#content').val($('.summernote').code()); }); </script> <?php $this->endBlock(); ?>
package org.basex.query.func.fn; import static org.basex.query.QueryError.*; import org.basex.build.json.*; import org.basex.build.json.JsonOptions.JsonFormat; import org.basex.io.parse.json.*; import org.basex.query.*; import org.basex.query.func.*; import org.basex.query.value.item.*; import org.basex.query.value.map.*; import org.basex.query.value.type.*; import org.basex.util.*; public class FnParseJson extends Parse { /** Function taking and returning a string. */ private static final FuncType STRFUNC = FuncType.get(SeqType.STR, SeqType.STR); @Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { final Item it = exprs[0].atomItem(qc, info); if(it == null) return null; return parse(toToken(it), false, qc, ii); } /** * Parses the specified JSON string. * @param json json string * @param xml convert to xml * @param qc query context * @param ii input info * @return resulting item * @throws QueryException query exception */ final Item parse(final byte[] json, final boolean xml, final QueryContext qc, final InputInfo ii) throws QueryException { final JsonParserOptions opts = new JsonParserOptions(); if(exprs.length > 1) { final Map options = toMap(exprs[1], qc); try { new FuncOptions(null, info).acceptUnknown().parse(options, opts); } catch(final QueryException ex) { throw JSON_OPT_X.get(ii, ex.getLocalizedMessage()); } } final boolean unesc = opts.get(JsonParserOptions.UNESCAPE); final FuncItem fb = opts.get(JsonParserOptions.FALLBACK); final FItem fallback; if(fb == null) { fallback = null; } else { try { fallback = STRFUNC.cast(fb, qc, sc, ii); } catch(final QueryException ex) { throw JSON_OPT_X.get(ii, ex.getLocalizedMessage()); } } try { opts.set(JsonOptions.FORMAT, xml ? JsonFormat.BASIC : JsonFormat.MAP); final JsonConverter conv = JsonConverter.get(opts); if(unesc && fallback != null) conv.fallback(new JsonFallback() { @Override public String convert(final String string) { try { return Token.string(fallback.invokeItem(qc, ii, Str.get(string)).string(ii)); } catch(final QueryException ex) { throw new QueryRTException(ex); } } }); return conv.convert(json, null); } catch(final QueryRTException ex) { final QueryException qe = ex.getCause(); final QueryError err = qe.error(); if(err != INVPROMOTE_X_X && err != INVPROMOTE_X_X_X) throw qe; Util.debug(ex); throw JSON_OPT_X.get(ii, qe.getLocalizedMessage()); } catch(final QueryIOException ex) { Util.debug(ex); final QueryException qe = ex.getCause(info); final QueryError error = qe.error(); final String message = ex.getLocalizedMessage(); if(error == BXJS_PARSE_X_X_X) throw JSON_PARSE_X.get(ii, message); if(error == BXJS_DUPLICATE_X) throw JSON_DUPLICATE_X.get(ii, message); if(error == BXJS_INVALID_X) throw JSON_OPT_X.get(ii, message); throw qe; } } }
<html> <body> <script language="JavaScript"> TargetDate = "12/31/2020 5:00 AM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "It is finally here!"; </script> <script> function calcage(secs, num1, num2) { s = ((Math.floor(secs/num1))%num2).toString(); if (LeadingZero && s.length < 2) s = "0" + s; return "<b>" + s + "</b>"; } function CountBack(secs) { if (secs < 0) { document.getElementById("cntdwn").innerHTML = FinishMessage; return; } DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000)); DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24)); DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60)); DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60)); document.getElementById("cntdwn").innerHTML = DisplayStr; if (CountActive) setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod); } function putspan(backcolor, forecolor) { document.write("<span id='cntdwn' style='background-color:" + backcolor + "; color:" + forecolor + "'></span>"); } if (typeof(BackColor)=="undefined") BackColor = "white"; if (typeof(ForeColor)=="undefined") ForeColor= "black"; if (typeof(TargetDate)=="undefined") TargetDate = "12/31/2020 5:00 AM"; if (typeof(DisplayFormat)=="undefined") DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; if (typeof(CountActive)=="undefined") CountActive = true; if (typeof(FinishMessage)=="undefined") FinishMessage = ""; if (typeof(CountStepper)!="number") CountStepper = -1; if (typeof(LeadingZero)=="undefined") LeadingZero = true; CountStepper = Math.ceil(CountStepper); if (CountStepper == 0) CountActive = false; var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990; putspan(BackColor, ForeColor); var dthen = new Date(TargetDate); var dnow = new Date(); if(CountStepper>0) ddiff = new Date(dnow-dthen); else ddiff = new Date(dthen-dnow); gsecs = Math.floor(ddiff.valueOf()/1000); CountBack(gsecs); </script> </body> </html>
<?php namespace frontend\controllers; use Yii; use app\models\Jurulatih; // use frontend\models\<API key>; use yii\web\Controller; use yii\web\<API key>; use yii\filters\VerbFilter; use yii\web\UploadedFile; use app\models\general\Upload; use app\models\general\GeneralVariable; use app\models\general\GeneralLabel; use common\models\general\GeneralFunction; /** * <API key> implements the upload actions for <API key> model. */ class <API key> extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all <API key> models. * @return mixed */ // public function actionIndex() // $searchModel = new <API key>(); // $dataProvider = $searchModel->search(Yii::$app->request->queryParams); // return $this->render('index', [ // 'searchModel' => $searchModel, // 'dataProvider' => $dataProvider, /** * Displays a single <API key> model. * @param integer $id * @return mixed */ public function actionView($id) { // return $this->render('view', [ // 'model' => $this->findModel($id), } /** * Creates a new <API key> model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate($id) { $model = $this->findModel($id); if(Yii::$app->request->post()) { $haveFile = false; $file = UploadedFile::getInstance($model, 'borang_maklumat'); if(isset($file) && $file != null){ if($model->borang_maklumat != '' || $model->borang_maklumat != null){ unlink($model->borang_maklumat); } $filename = $model->jurulatih_id . "-borang_maklumat"; $model->borang_maklumat = Upload::uploadFile($file, Upload::jurulatihFolder, $filename); $haveFile = true; } $file = UploadedFile::getInstance($model, 'borang_kesihatan'); if(isset($file) && $file != null){ if($model->borang_kesihatan != '' || $model->borang_kesihatan != null){ unlink($model->borang_kesihatan); } $filename = $model->jurulatih_id . "-borang_kesihatan"; $model->borang_kesihatan = Upload::uploadFile($file, Upload::jurulatihFolder, $filename); $haveFile = true; } $file = UploadedFile::getInstance($model, 'borang_hrmis'); if(isset($file) && $file != null){ if($model->borang_hrmis != '' || $model->borang_hrmis != null){ unlink($model->borang_hrmis); } $filename = $model->jurulatih_id . "-borang_hrmis"; $model->borang_hrmis = Upload::uploadFile($file, Upload::jurulatihFolder, $filename); $haveFile = true; } $file = UploadedFile::getInstance($model, 'borang_rawatan'); if(isset($file) && $file != null){ if($model->borang_rawatan != '' || $model->borang_rawatan != null){ unlink($model->borang_rawatan); } $filename = $model->jurulatih_id . "-borang_rawatan"; $model->borang_rawatan = Upload::uploadFile($file, Upload::jurulatihFolder, $filename); $haveFile = true; } $file = UploadedFile::getInstance($model, 'borang_keselamatan'); if(isset($file) && $file != null){ if($model->borang_keselamatan != '' || $model->borang_keselamatan != null){ unlink($model->borang_keselamatan); } $filename = $model->jurulatih_id . "-borang_keselamatan"; $model->borang_keselamatan = Upload::uploadFile($file, Upload::jurulatihFolder, $filename); $haveFile = true; } $file = UploadedFile::getInstance($model, 'borang_pelekat'); if(isset($file) && $file != null){ if($model->borang_pelekat != '' || $model->borang_pelekat != null){ unlink($model->borang_pelekat); } $filename = $model->jurulatih_id . "-borang_pelekat"; $model->borang_pelekat = Upload::uploadFile($file, Upload::jurulatihFolder, $filename); $haveFile = true; } $file = UploadedFile::getInstance($model, 'borang_income_tax'); if(isset($file) && $file != null){ if($model->borang_income_tax != '' || $model->borang_income_tax != null){ unlink($model->borang_income_tax); } $filename = $model->jurulatih_id . "-borang_income_tax"; $model->borang_income_tax = Upload::uploadFile($file, Upload::jurulatihFolder, $filename); $haveFile = true; } if($haveFile){ if($model->save()) return '1'; } } return $this->renderAjax('create', [ 'model' => $model, ]); } /** * Updates an existing <API key> model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ // public function actionUpdate($id) // $model = $this->findModel($id); // if ($model->load(Yii::$app->request->post()) && $model->save()) { // return $this->redirect(['view', 'id' => $model->id]); // } else { // return $this->render('update', [ // 'model' => $model, /** * Deletes an existing <API key> model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ // public function actionDelete($id) // $this->findModel($id)->delete(); // return $this->redirect(['index']); /** * Finds the <API key> model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return <API key> the loaded model * @throws <API key> if the model cannot be found */ protected function findModel($id) { if (($model = Jurulatih::findOne($id)) !== null) { return $model; } else { throw new <API key>('The requested page does not exist.'); } } }
package com.twelvemonkeys.servlet.jsp.droplet.taglib; import com.twelvemonkeys.servlet.jsp.droplet.Param; import com.twelvemonkeys.servlet.jsp.taglib.ExTagSupport; import javax.servlet.jsp.JspException; public class ParamTag extends ExTagSupport { /** * This is the name of the parameter to be inserted into the {@code * PageContext.REQUEST_SCOPE} scope. */ private String parameterName; /** * This is the value for the parameter to be inserted into the {@code * PageContext.REQUEST_SCOPE} scope. */ private Object parameterValue; /** * This method allows the JSP page to set the name for the parameter by * using the {@code name} tag attribute. * * @param pName The name for the parameter to insert into the {@code * PageContext.REQUEST_SCOPE} scope. */ public void setName(String pName) { parameterName = pName; } /** * This method allows the JSP page to set the value for hte parameter by * using the {@code value} tag attribute. * * @param pValue The value for the parameter to insert into the <code> * PageContext.REQUEST_SCOPE</page> scope. */ public void setValue(String pValue) { parameterValue = new Param(pValue); } /** * Ensure that the tag implemented by this class is enclosed by an {@code * IncludeTag}. If the tag is not enclosed by an * {@code IncludeTag} then a {@code JspException} is thrown. * * @return If this tag is enclosed within an {@code IncludeTag}, then * the default return value from this method is the {@code * TagSupport.SKIP_BODY} value. * @exception JspException */ public int doStartTag() throws JspException { //<API key>(); addParameter(); return SKIP_BODY; } /** * This is the method responsible for actually testing that the tag * implemented by this class is enclosed within an {@code IncludeTag}. * * @exception JspException */ /* protected void <API key>() throws JspException { Tag parentTag = getParent(); if ((parentTag != null) && (parentTag instanceof IncludeTag)) { return; } String msg = "A class that extends <API key> " + "is not enclosed within an IncludeTag."; log(msg); throw new JspException(msg); } */ /** * This method adds the parameter whose name and value were passed to this * object via the tag attributes to the parent {@code Include} tag. */ private void addParameter() { IncludeTag includeTag = (IncludeTag) getParent(); includeTag.addParameter(parameterName, parameterValue); } /** * This method cleans up the member variables for this tag in preparation * for being used again. This method is called when the tag finishes it's * current call with in the page but could be called upon again within this * same page. This method is also called in the release stage of the tag * life cycle just in case a JspException was thrown during the tag * execution. */ protected void clearServiceState() { parameterName = null; parameterValue = null; } }
<?php /** * UserDao */ require_once('../bean/User.php'); class UserDao { function addUser(User $user){ return true; } function deleteUser(User $user){ return true; } function updateUser(){ $user = new User(); $user->userId = 1; $user->userName = 'update'; $user->password = 'psswd'; $user->sex = 'boy'; $user->age = 23; return $user; } function queryUser(){ $user = new User(); $user->userId = 2; $user->userName = 'query'; $user->password = 'psswd'; $user->sex = 'girl'; $user->age = 21; return $user; } function __construct() { # code... } } ?>
package com.smartdevicelink.test.rpc.enums; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import com.smartdevicelink.proxy.rpc.enums.ImageFieldName; /** * This is a unit test class for the SmartDeviceLink library project class : * {@link com.smartdevicelink.rpc.enums.ImageFieldName} */ public class ImageFieldNameTests extends TestCase { /** * Verifies that the enum values are not null upon valid assignment. */ public void testValidEnums () { String example = "softButtonImage"; ImageFieldName enumSoftButtonImage = ImageFieldName.valueForString(example); example = "choiceImage"; ImageFieldName enumChoiceImage = ImageFieldName.valueForString(example); example = "<API key>"; ImageFieldName enumSecondaryImage = ImageFieldName.valueForString(example); example = "vrHelpItem"; ImageFieldName enumVrHelpItem = ImageFieldName.valueForString(example); example = "turnIcon"; ImageFieldName enumTurnIcon = ImageFieldName.valueForString(example); example = "menuIcon"; ImageFieldName enumMenuIcon = ImageFieldName.valueForString(example); example = "cmdIcon"; ImageFieldName enumCmdIcon = ImageFieldName.valueForString(example); example = "appIcon"; ImageFieldName enumAppIcon = ImageFieldName.valueForString(example); example = "graphic"; ImageFieldName enumGraphicIcon = ImageFieldName.valueForString(example); example = "showConstantTBTIcon"; ImageFieldName <API key> = ImageFieldName.valueForString(example); example = "<API key>"; ImageFieldName <API key> = ImageFieldName.valueForString(example); example = "locationImage"; ImageFieldName enumLocationImage = ImageFieldName.valueForString(example); assertNotNull("softButtonImage returned null", enumSoftButtonImage); assertNotNull("choiceImage returned null", enumChoiceImage); assertNotNull("<API key> returned null", enumSecondaryImage); assertNotNull("vrHelpItem returned null", enumVrHelpItem); assertNotNull("turnIcon returned null", enumTurnIcon); assertNotNull("menuIcon returned null", enumMenuIcon); assertNotNull("cmdIcon returned null", enumCmdIcon); assertNotNull("appIcon returned null", enumAppIcon); assertNotNull("graphic returned null", enumGraphicIcon); assertNotNull("showConstantTBTIcon returned null", <API key>); assertNotNull("<API key> returned null", <API key>); assertNotNull("location image returned null", enumLocationImage); } /** * Verifies that an invalid assignment is null. */ public void testInvalidEnum () { String example = "sofTbUtTOnImagE"; try { ImageFieldName temp = ImageFieldName.valueForString(example); assertNull("Result of valueForString should be null.", temp); } catch (<API key> exception) { fail("Invalid enum throws <API key>."); } } /** * Verifies that a null assignment is invalid. */ public void testNullEnum () { String example = null; try { ImageFieldName temp = ImageFieldName.valueForString(example); assertNull("Result of valueForString should be null.", temp); } catch (<API key> exception) { fail("Null string throws <API key>."); } } /** * Verifies the possible enum values of ImageFieldName. */ public void testListEnum() { List<ImageFieldName> enumValueList = Arrays.asList(ImageFieldName.values()); List<ImageFieldName> enumTestList = new ArrayList<ImageFieldName>(); enumTestList.add(ImageFieldName.softButtonImage); enumTestList.add(ImageFieldName.choiceImage); enumTestList.add(ImageFieldName.<API key>); enumTestList.add(ImageFieldName.vrHelpItem); enumTestList.add(ImageFieldName.turnIcon); enumTestList.add(ImageFieldName.menuIcon); enumTestList.add(ImageFieldName.cmdIcon); enumTestList.add(ImageFieldName.appIcon); enumTestList.add(ImageFieldName.graphic); enumTestList.add(ImageFieldName.showConstantTBTIcon); enumTestList.add(ImageFieldName.<API key>); enumTestList.add(ImageFieldName.locationImage); assertTrue("Enum value list does not match enum class list", enumValueList.containsAll(enumTestList) && enumTestList.containsAll(enumValueList)); } }
<?php use yii\helpers\Html; //use yii\grid\GridView; use kartik\grid\GridView; use miloschuman\highcharts\Highcharts; use app\models\RepChildDevR6; /* @var $this yii\web\View */ /* @var $searchModel app\models\CampaignSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Campaigns'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="container"> <div class="campaign-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Create Campaign', ['create'], ['class' => 'btn btn-primary']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'title', //'target_age_start', //'target_age_end', //'target_sex', // 'target_provcode', // 'target_distcode', // 'target_subdistcode', // 'target_hospcode', // 'target_chronic', // 'detail_url:url', // 'thumbnail_url:url', // 'intro:ntext', 'startdate', 'enddate', // 'userid', 'publisher_id', // 'publisher_url:url', // 'hotline_number', // 'redirect2publisher', // 'full_detail:ntext', // 'publish', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div> <?php $sql = " SELECT ROUND(IFNULL(SUM(if(r.areacode LIKE '11%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '11%', r.total_targer, 0)) ,0),2) AS p11, ROUND(IFNULL(SUM(if(r.areacode LIKE '20%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '20%', r.total_targer, 0)) ,0),2) AS p20, ROUND(IFNULL(SUM(if(r.areacode LIKE '21%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '21%', r.total_targer, 0)) ,0),2) AS p21, ROUND(IFNULL(SUM(if(r.areacode LIKE '22%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '22%', r.total_targer, 0)) ,0),2) AS p22, ROUND(IFNULL(SUM(if(r.areacode LIKE '23%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '23%', r.total_targer, 0)) ,0),2) AS p23, ROUND(IFNULL(SUM(if(r.areacode LIKE '24%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '24%', r.total_targer, 0)) ,0),2) AS p24, ROUND(IFNULL(SUM(if(r.areacode LIKE '25%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '25%', r.total_targer, 0)) ,0),2) AS p25, ROUND(IFNULL(SUM(if(r.areacode LIKE '27%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '27%', r.total_targer, 0)) ,0),2) AS p27 FROM rep_child_dev_r6 r GROUP BY r.age_month ORDER BY r.age_month "; $rep = RepChildDevR6::findBySql($sql)->asArray()->all(); // echo '<br>'.implode(',', $rep[0]); // echo '<br>'.implode(',', $rep[1]); // echo '<br>'.implode(',', $rep[2]); // echo '<br>'.implode(',', $rep[3]); // $value=var_dump(array_map('intVal', array_values($rep[0]))); // echo print_r($value); echo Highcharts::widget([ 'scripts' => array( 'highcharts-more', // enables supplementary chart types (gauge, arearange, columnrange, etc.) 'modules/exporting', // adds Exporting button/menu to chart //'themes/grid-light' // applies global 'grid' theme to all charts ), 'options' => array( 'title' => array('text' => 'ร้อยละของเด็กที่มีพัฒนาการสมวัยตามช่วงอายุ 0-5 ปี เขตบริการสุขภาพที่ 6'), 'xAxis' => array( 'categories' => array('สมุทรปราการ','ชลบุรี','ระยอง','จันทบุรี','ตราด','ฉะเชิงเทรา','ปราจีนบุรี','สระแก้ว') ), 'yAxis' => array( 'title' => array('text' => 'ร้อยละของเด็กที่มีพัฒนาการสมวัย') ), 'colors'=>array('#2D7EC8', '#21A7DA', '#29D1D9', '#2FD1A5'), 'gradient' => array('enabled'=> true), 'credits' => array('enabled' => false), /*'exporting' => array('enabled' => false),*/ //to turn off exporting uncomment 'chart' => array( 'plotBackgroundColor' => '#ffffff', 'plotBorderWidth' => null, 'plotShadow' => false, 'height' => 400, ), 'title' => false, 'series' => array( array('type'=>'column','name' => 'อายุ 9 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[0])) ), array('type'=>'column','name' => 'อายุ 18 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[1])) ), array('type'=>'column','name' => 'อายุ 30 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[2])) ), array('type'=>'column','name' => 'อายุ 42 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[3])) ), ), ) ]); ?> </div>
<?php namespace yii\liuxy\helpers; use Yii; use yii\liuxy\gearman\Client; class IdGeneratorHelper { const PREFIX = 'id.generator'; /** * @param $category * @param string $cacheName */ public static function get($category) { $key = self::PREFIX.$category; if (!Yii::$app->cache->exists($key)) { $item = Yii::$app->db->createCommand('select category,value from tids where category=:category', [':category'=>$category])->queryOne(); if ($item) { Yii::$app->cache->set($key, $item['value']); } else { $ret = Yii::$app->db->createCommand()->insert('tids',[ 'category'=>$category,'value'=>1 ]); if ($ret) { Yii::$app->cache->set($key, 0); } } } $ret = Yii::$app->cache->increment($key); if ($ret) { $idClient = new Client('id'); $idClient->doBackground('common/id/execute', json_encode([ 'tids', ['value'=>1], ['category'=>$category] ])); } return $ret; } }
from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse from django.db import models from django.utils.html import strip_tags from django.utils.safestring import mark_safe from django.core.exceptions import ValidationError from make_mozilla.core import fields class Page(models.Model): title = models.CharField(max_length=255) path = models.SlugField() real_path = models.CharField(max_length=1024, unique=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, help_text='This will allow you to use URLs like /about/foo - parent.path + path', related_name='children') show_subnav = models.BooleanField(default=False, verbose_name='Show sub-navigation menu') subnav_title = models.CharField(max_length=100, blank=True, null=True, verbose_name='Menu title', help_text='This can be left blank if you do not need a title') additional_content = models.TextField(blank=True, null=True) def has_ancestor(self, page): if not self.parent: return False if self.parent.id == page.id: return True return self.parent.has_ancestor(page) def get_section_root(self): return self.real_path.split('/')[0] def clean(self): self.path = self.path.strip('/') if self.parent: if self.parent.has_ancestor(self): raise ValidationError('Cannot set page parent to one of its descendants') self.real_path = '%s/%s' % (self.parent.real_path, self.path) else: self.real_path = self.path try: if Page.objects.exclude(id__exact=self.id).get(real_path=self.real_path): raise ValidationError('This path/parent combination already exists.') except Page.DoesNotExist: # We can safely ignore this, as it means we're in the clear and our path is fine pass def save(self, *args, **kwargs): super(Page, self).save(*args, **kwargs) # Now we tell our children to update their real paths # This will happen recursively, so we don't need to worry about that logic here for child in self.children.all(): child.real_path = '%s/%s' % (self.real_path, child.path) child.save() def __unicode__(self): return self.title @property def indented_title(self): indent = len(self.real_path.split('/')) - 1 if not indent: return self.title return '%s %s' % ('-' * indent, self.title) def get_absolute_url(self): return reverse('page', args=[self.real_path]) class PageSection(models.Model): title = models.CharField(max_length=255) subnav_title = models.CharField(max_length=255, blank=True, null=True, verbose_name='Sub-navigation title', help_text='Will use the section title if blank') page = models.ForeignKey('Page', related_name='sections') poster = fields.SizedImageField( blank=True, null=True, upload_to='pages', storage=FileSystemStorage(**settings.UPLOADED_IMAGES), sizes={ 'standard': 900, 'tablet': 700, 'handheld': 500, }) content = models.TextField() sidebar = models.TextField(blank=True, null=True) quotes = models.ManyToManyField('Quote', blank=True, null=True) class Meta: verbose_name = 'section' ordering = ['id'] def __unicode__(self): return mark_safe(self.title) @property def nav_title(self): if self.subnav_title: return mark_safe(self.subnav_title) return unicode(self) @property def has_sidebar(self): return self.sidebar or self.quotes.count() class Quote(models.Model): quote = models.CharField(max_length=1000) source = models.ForeignKey('QuoteSource', blank=True, null=True) url = models.URLField(blank=True, null=True, verbose_name='URL') show_source_image = models.BooleanField(default=False, help_text='Show the source\'s image next to this quote, if available') @property def clean_quote(self): return strip_tags(self.quote) def __unicode__(self): quote = self.clean_quote if len(quote) > 25: quote = quote[:25] + '...' if not self.source: return quote return '%s (%s)' % (quote, self.source.name) class QuoteSource(models.Model): name = models.CharField(max_length=255) strapline = models.CharField(max_length=255, blank=True, null=True, help_text='"Teacher", "CEO, MegaCorp", ...') url = models.URLField(blank=True, null=True, verbose_name='URL') avatar = fields.SizedImageField( blank=True, null=True, verbose_name='Image', upload_to='avatars', storage=FileSystemStorage(**settings.UPLOADED_IMAGES), sizes={ 'adjusted': (90,90), }) class Meta: verbose_name = 'source' def __unicode__(self): if self.strapline: return '%s - %s' % (self.name, self.strapline) return self.name
var <API key> = [ [ "apply", "<API key>.html#<API key>", null ], [ "setF", "<API key>.html#<API key>", null ], [ "f", "<API key>.html#<API key>", null ] ];
// .NAME <API key> - create a ellipsoidal-shaped button // .SECTION Description // <API key> creates a ellipsoidal shaped button with // texture coordinates suitable for application of a texture map. This // provides a way to make nice looking 3D buttons. The buttons are // represented as vtkPolyData that includes texture coordinates and // normals. The button lies in the x-y plane. // To use this class you must define the major and minor axes lengths of an // ellipsoid (expressed as width (x), height (y) and depth (z)). The button // has a rectangular mesh region in the center with texture coordinates that // range smoothly from (0,1). (This flat region is called the texture // region.) The outer, curved portion of the button (called the shoulder) has // texture coordinates set to a user specified value (by default (0,0). // (This results in coloring the button curve the same color as the (s,t) // location of the texture map.) The resolution in the radial direction, the // texture region, and the shoulder region must also be set. The button can // be moved by specifying an origin. #ifndef <API key> #define <API key> #include "vtkButtonSource.h" class vtkCellArray; class vtkFloatArray; class vtkPoints; class VTK_GRAPHICS_EXPORT <API key> : public vtkButtonSource { public: void PrintSelf(ostream& os, vtkIndent indent); <API key>(<API key>,vtkButtonSource); // Description: // Construct a circular button with depth 10% of its height. static <API key> *New(); // Description: // Set/Get the width of the button (the x-ellipsoid axis length * 2). vtkSetClampMacro(Width,double,0.0,VTK_DOUBLE_MAX); vtkGetMacro(Width,double); // Description: // Set/Get the height of the button (the y-ellipsoid axis length * 2). vtkSetClampMacro(Height,double,0.0,VTK_DOUBLE_MAX); vtkGetMacro(Height,double); // Description: // Set/Get the depth of the button (the z-eliipsoid axis length). vtkSetClampMacro(Depth,double,0.0,VTK_DOUBLE_MAX); vtkGetMacro(Depth,double); // Description: // Specify the resolution of the button in the circumferential direction. vtkSetClampMacro(<API key>,int,4,VTK_LARGE_INTEGER); vtkGetMacro(<API key>,int); // Description: // Specify the resolution of the texture in the radial direction in the // texture region. vtkSetClampMacro(TextureResolution,int,1,VTK_LARGE_INTEGER); vtkGetMacro(TextureResolution,int); // Description: // Specify the resolution of the texture in the radial direction in the // shoulder region. vtkSetClampMacro(ShoulderResolution,int,1,VTK_LARGE_INTEGER); vtkGetMacro(ShoulderResolution,int); // Description: // Set/Get the radial ratio. This is the measure of the radius of the // outer ellipsoid to the inner ellipsoid of the button. The outer // ellipsoid is the boundary of the button defined by the height and // width. The inner ellipsoid circumscribes the texture region. Larger // RadialRatio's cause the button to be more rounded (and the texture // region to be smaller); smaller ratios produce sharply curved shoulders // with a larger texture region. vtkSetClampMacro(RadialRatio,double,1.0,VTK_DOUBLE_MAX); vtkGetMacro(RadialRatio,double); protected: <API key>(); ~<API key>() {} int RequestData(vtkInformation *, <API key> **, <API key> *); double Width; double Height; double Depth; int <API key>; int TextureResolution; int ShoulderResolution; double RadialRatio; private: <API key>(const <API key>&); // Not implemented. void operator=(const <API key>&); // Not implemented. //internal variable related to axes of ellipsoid double A; double A2; double B; double B2; double C; double C2; double ComputeDepth(int inTextureRegion, double x, double y, double n[3]); void InterpolateCurve(int inTextureRegion, vtkPoints *newPts, int numPts, vtkFloatArray *normals, vtkFloatArray *tcoords, int res, int c1StartPoint,int c1Incr, int c2StartPoint,int s2Incr, int startPoint,int incr); void CreatePolygons(vtkCellArray *newPolys, int num, int res, int startIdx); void <API key>(double a2, double b2, double dX, double dY, double& xe, double& ye); }; #endif
body[device='tablet'] #open_tabs_container { padding-bottom: 40px; } body[device='tablet'] #open_tabs_container .page-list>div { box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.16); margin: 40px auto 0 auto; min-width: 500px; max-width: 550px; } @media only screen and (min-device-width: 700px) { body[device='tablet'] #open_tabs_container .page-list>div { max-width: 650px; } } body[device='tablet'] .<API key>>div:last-child { border-bottom: none; } body[device='tablet'] #open_tabs_container .session-header .list-item { background: #F2F2F2; border-bottom: 1px solid #E7E7E7; color: #777; font-size: 0.8em; padding: 20px 0px 20px 0px; } body[device='tablet'] #open_tabs_container .list-item { background: #FAFAFA; border: 1px solid #E0E0E0; border-bottom: none; } body[device='tablet'] #open_tabs_container .list-item-active, body[device='tablet'] #open_tabs_container .session-header .list-item.list-item-active { background: rgba(51, 181, 229, 0.4); -<API key>: transparent; } body[device='tablet'] .session-name { font-weight: bold; font-size: 1.1em; color: #333; line-height: 1.8em; } body[device='tablet'] .session-last-synced { font-weight: normal; } body[device='tablet'] #open_tabs_container .<API key> .list-item:first-child { border-top: none; }
""" Query subclasses which provide extra functionality beyond simple data retrieval. """ from django.core.exceptions import FieldError from django.db import connections from django.db.models.sql.constants import * from django.db.models.sql.datastructures import Date from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.query import Query from django.db.models.sql.where import AND, Constraint __all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'DateQuery', 'AggregateQuery'] class DeleteQuery(Query): """ Delete queries are done through this class, since they are more constrained than general queries. """ compiler = 'SQLDeleteCompiler' def do_query(self, table, where, using): self.tables = [table] self.where = where self.get_compiler(using).execute_sql(None) def delete_batch(self, pk_list, using): """ Set up and execute delete queries for all the objects in pk_list. More than one physical query may be executed if there are a lot of values in pk_list. """ for offset in range(0, len(pk_list), <API key>): where = self.where_class() field = self.model._meta.pk where.add((Constraint(None, field.column, field), 'in', pk_list[offset : offset + <API key>]), AND) self.do_query(self.model._meta.db_table, where, using=using) class UpdateQuery(Query): """ Represents an "update" SQL query. """ compiler = 'SQLUpdateCompiler' def __init__(self, *args, **kwargs): super(UpdateQuery, self).__init__(*args, **kwargs) self._setup_query() def _setup_query(self): """ Runs on initialization and after cloning. Any attributes that would normally be set in __init__ should go in here, instead, so that they are also set up after a clone() call. """ self.values = [] self.related_ids = None if not hasattr(self, 'related_updates'): self.related_updates = {} def clone(self, klass=None, **kwargs): return super(UpdateQuery, self).clone(klass, related_updates=self.related_updates.copy(), **kwargs) def clear_related(self, related_field, pk_list, using): """ Set up and execute an update query that clears related entries for the keys in pk_list. This is used by the QuerySet.delete_objects() method. """ for offset in range(0, len(pk_list), <API key>): self.where = self.where_class() f = self.model._meta.pk self.where.add((Constraint(None, f.column, f), 'in', pk_list[offset : offset + <API key>]), AND) self.values = [(related_field, None, None)] self.get_compiler(using).execute_sql(None) def add_update_values(self, values): """ Convert a dictionary of field name to value mappings into an update query. This is the entry point for the public update() method on querysets. """ values_seq = [] for name, val in values.iteritems(): field, model, direct, m2m = self.model._meta.get_field_by_name(name) if not direct or m2m: raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field) if model: self.add_related_update(model, field, val) continue values_seq.append((field, model, val)) return self.add_update_fields(values_seq) def add_update_fields(self, values_seq): """ Turn a sequence of (field, model, value) triples into an update query. Used by add_update_values() as well as the "fast" update path when saving models. """ self.values.extend(values_seq) def add_related_update(self, model, field, value): """ Adds (name, value) to an update query for an ancestor model. Updates are coalesced so that we only run one update query per ancestor. """ try: self.related_updates[model].append((field, None, value)) except KeyError: self.related_updates[model] = [(field, None, value)] def get_related_updates(self): """ Returns a list of query objects: one for each update required to an ancestor model. Each query will have the same filtering conditions as the current query but will only update a single table. """ if not self.related_updates: return [] result = [] for model, values in self.related_updates.iteritems(): query = UpdateQuery(model) query.values = values if self.related_ids: query.add_filter(('pk__in', self.related_ids)) result.append(query) return result class InsertQuery(Query): compiler = 'SQLInsertCompiler' def __init__(self, *args, **kwargs): super(InsertQuery, self).__init__(*args, **kwargs) self.columns = [] self.values = [] self.params = () def clone(self, klass=None, **kwargs): extras = { 'columns': self.columns[:], 'values': self.values[:], 'params': self.params } extras.update(kwargs) return super(InsertQuery, self).clone(klass, **extras) def insert_values(self, insert_values, raw_values=False): """ Set up the insert query from the 'insert_values' dictionary. The dictionary gives the model field names and their target values. If 'raw_values' is True, the values in the 'insert_values' dictionary are inserted directly into the query, rather than passed as SQL parameters. This provides a way to insert NULL and DEFAULT keywords into the query, for example. """ placeholders, values = [], [] for field, val in insert_values: placeholders.append((field, val)) self.columns.append(field.column) values.append(val) if raw_values: self.values.extend([(None, v) for v in values]) else: self.params += tuple(values) self.values.extend(placeholders) class DateQuery(Query): """ A DateQuery is a normal query, except that it specifically selects a single date field. This requires some special handling when converting the results back to Python objects, so we put it in a separate class. """ compiler = 'SQLDateCompiler' def add_date_select(self, field, lookup_type, order='ASC'): """ Converts the query into a date extraction query. """ result = self.setup_joins([field.name], self.get_meta(), self.get_initial_alias(), False) alias = result[3][-1] select = Date((alias, field.column), lookup_type) self.select = [select] self.select_fields = [None] self.select_related = False # See #7097. self.set_extra_mask([]) self.distinct = True self.order_by = order == 'ASC' and [1] or [-1] class AggregateQuery(Query): """ An AggregateQuery takes another query as a parameter to the FROM clause and only selects the elements in the provided list. """ compiler = '<API key>' def add_subquery(self, query, using): self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True)
Flywheel - Remote SDK for JavaScript JavaScript SDK for HTML5 compliant web browsers. # About Given the simplicity of the protocol, you can connect to Flywheel directly over a stock HTML5 `WebSocket` - as long as you're willing to perform some trivial string manipulation to handle `B`, `P` and `R` frames, and handle socket events. This library saves you the hassle, providing - * A convenient wrapper around the HTML5 `WebSocket` object; * Event logging of `WebSocket` life-cycle events and message receival; * Flywheel wire protocol - (un)marshaling of text frames and delegating to the appropriate handler; * Connection maintenance - detecting connection failure and automatically reconnecting after a set interval. # Limitations * Only the text protocol is currently supported. # Usage The example below instantiates a remote node and opens a nexus to `ws://localhost:8080/broker`, with the reconnection option set. It then subscribes to the `time` and `communal` topics, and after binding will publish a single `Hello world!` text message over the `communal` topic. After ten seconds of messaging activity, the remote node will permanently close the nexus. Note: this assumes that `flywheel-remote.js` has been imported into your project. javascript // configure the remote node const conf = { // mandatory - the WebSocket endpoint URL url: "ws://localhost:8080/broker", // optional // - if set, the remote node will maintain the connection open with a given backoff // - otherwise the connection will be a one-off <API key>: 1000, // optional - if set, connection events and message receival will be logged log: true }; // create a remote node and initiate the connection const remoteNode = new RemoteNode() .onOpen((nexus, wsEvent) => { // Called when a connection has been established (first time, or following a reconnect). // Normally this is where you would bind your subscriptions, provide initial auth credentials, etc. console.log(`Opened ${nexus}`); const bind = { subscribe: ["time", "communal"], auth: {type: "Basic", username: "user", password: "pass"} }; nexus.bind(bind, bindResponse => { console.log(`Bind response: ${bindResponse}`); // handle the bind response from the edge node if (bindResponse.errors.length !== 0) { // some errors occurred... display them and close the remote node (which will also close the current nexus) console.log(`Binding errors: ${JSON.stringify(bindResponse.errors)}`); nexus.remote.close(); } else { // no errors... publish a single 'Hello world!' message (which we will also receive ourselves) nexus.publishText("communal", "Hello world!"); } }); }) .onClose((nexus, wsEvent) => { console.log(`Closed ${nexus}, code: ${wsEvent.code}, reason: ${wsEvent.reason}`); }) .open(conf); // open() can only be called once; calling it a second time will have no effect unless close() is called const someTimeLater = setTimeout(() => { remoteNode.close(); // calling close() will close the nexus and stop any further reconnection attempts clearTimeout(someTimeLater); }, 10000);
<?php namespace Application\Entity; use Core\Entity\Entity; use Core\Entity\EntityException; use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping\SequenceGenerator; use Doctrine\ORM\Mapping\PrePersist; use Zend\InputFilter\InputFilter; use Zend\InputFilter\Factory as InputFactory; use Zend\InputFilter\<API key>; use Zend\InputFilter\<API key>; class Aluno extends Entity { /** * @var int $id * * @ORM\Id * @ORM\Column(type="integer", nullable=false) * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string $matricula * * @ORM\Column(type="string", unique=true, length=14) */ protected $matricula; /** * @var string $nome * * @ORM\Column(type="string", length=80) */ protected $nome; /** * getters and setters */ public function getId() { return $this->id; } public function setId($value) { $this->id = $this->valid("id", $value); } public function getMatricula() { return $this->matricula; } public function setMatricula($value) { $this->matricula = $this->valid("matricula", $value); } /** * [$inputFilter description] * @var [type] */ protected $inputFilter; /** * Configura os filtros dos campos da entidade * * @return Zend\InputFilter\Inputfilter */ public function getInputFilter() { if (!$this->inputFilter){ $inputFilter = new InputFilter(); $factory = new InputFactory(); $inputFilter->add($factory->createInput(array( 'name' => 'id', 'required' => true, 'filters' => array( array('name' => 'Int'), ), ))); $inputFilter->add($factory->createInput(array( 'name' => 'nome', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), ))); $inputFilter->add($factory->createInput(array( 'name' => 'matricula', 'required' => true, 'filters' => array( array('name' => 'StripTags'), array('name' => 'StringTrim'), ), ))); $this->inputFilter = $inputFilter; } return $this->inputFilter; } }
#!/bin/bash # Bucket location export AWS_S3_BUCKET="YourBucket/install" export AWS_DEFAULT_REGION=eu-central-1 # Download the files from S3 echo "Downloading install files" >> /home/ec2-user/log.txt aws s3 cp --region $AWS_DEFAULT_REGION s3://$AWS_S3_BUCKET/install/install-unrealircd.sh /home/ec2-user/install-unrealircd.sh >> /home/ec2-user/log.txt aws s3 cp --region $AWS_DEFAULT_REGION s3://$AWS_S3_BUCKET/install/install-anope.sh /home/ec2-user/install-anope.sh >> /home/ec2-user/log.txt # Make the scripts executable echo "Making scripts executable" >> /home/ec2-user/log.txt chmod +x /home/ec2-user/install-unrealircd.sh >> /home/ec2-user/log.txt chmod +x /home/ec2-user/install-anope.sh >> /home/ec2-user/log.txt # Installing UnrealIRCd echo "Starting install of UnrealIRCd (check log-unrealircd.txt)" >> /home/ec2-user/log.txt touch /home/ec2-user/log-unrealircd.txt /home/ec2-user/install-unrealircd.sh >> /home/ec2-user/log-unrealircd.txt # Installing Anope echo "Starting install of Anope (check log-anope.txt)" >> /home/ec2-user/log.txt touch /home/ec2-user/log-anope.txt /home/ec2-user/install-anope.sh >> /home/ec2-user/log-anope.txt
{% extends "account/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Change Password" %}{% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-5"> <h2>{% trans "Change Password" %}</h2> <form method="POST" action="." class="password_change"> {% csrf_token %} {{ form|crispy }} <button class="btn" type="submit" name="action">{% trans "Change Password" %}</button> </form> </div> </div> </div> {% endblock %}
package abi10_0_0.host.exp.exponent.modules.api; import android.util.Base64; import abi10_0_0.com.facebook.react.bridge.Arguments; import abi10_0_0.com.facebook.react.bridge.Promise; import abi10_0_0.com.facebook.react.bridge.<API key>; import abi10_0_0.com.facebook.react.bridge.<API key>; import abi10_0_0.com.facebook.react.bridge.ReactMethod; import abi10_0_0.com.facebook.react.bridge.WritableMap; import java.security.InvalidKeyException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class CryptoModule extends <API key> { public CryptoModule(<API key> reactContext) { super(reactContext); } @Override public String getName() { return "ExponentCrypto"; } @ReactMethod public void getHmacSHA1Async(String key, String bytes, final Promise promise) { WritableMap result = Arguments.createMap(); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] output = mac.doFinal(bytes.getBytes()); result.putBoolean("success", true); result.putString("output", Base64.encodeToString(output, Base64.DEFAULT)); } catch (InvalidKeyException e) { result.putBoolean("success", false); result.putString("error", "Invalid key"); } catch (Exception e) { result.putBoolean("success", false); } promise.resolve(result); } }
obj-y := main.o obj-y += mm.o obj-y += signal.o obj-$(CONFIG_MCACHE) += mcache.o obj-y += spawn.o obj-y += libc-support.o obj-y += scheduler.o obj-$(CONFIG_SCHED_RR) += scheduler-rr.o obj-$(CONFIG_SCHED_FIFO) += scheduler-fifo.o obj-y += task.o obj-y += panic.o obj-y += syscall.o obj-$(CONFIG_ELF) += elf-loader.o obj-y += dev.o ld-script-y += kernel.ld
<h1>TABLE "<?= $table ?>"</h1> <?= $this->render('_form', ['columns'=>$columns, 'row'=>$row]) ?>
<?php namespace ClipRest\Model; use Zend\Db\TableGateway\TableGateway; class ClipTable { protected $tableGateway; public function __construct(TableGateway $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll() { $resultSet = $this->tableGateway->select(); return $resultSet; } public function fetchAllWithSources() { $resultSet = $this->tableGateway->select(); $resultSet->buffer(); $out = array(); foreach ($resultSet as $row) { $row->clipSources = $row->getClipSources(); array_push($out, $row); } unset($row); return $out; } public function getClip($id) { $id = (int) $id; $rowset = $this->tableGateway->select(array('id' => $id)); $row = $rowset->current(); if (!$row) { throw new \Exception("Could not find row $id"); } return $row; } public function getClipWithSources($id) { $row = $this->getClip($id); $row->clipSources = $row->getClipSources(); return $row; } public function saveClip(Clip $clip) { $data = array( 'title' => $clip->title, 'defaultImage' => $clip->defaultImage, 'playingImage' => $clip->playingImage, 'info' => $clip->info, ); $id = (int)$clip->id; if ($id == 0) { $this->tableGateway->insert($data); } else { if ($this->getClip($id)) { $this->tableGateway->update($data, array('id' => $id)); } else { throw new \Exception('Form id does not exist'); } } } public function deleteClip($id) { $this->tableGateway->delete(array('id' => $id)); } }
""" Test if Matplotlib is using PyQt4 as backend """ def <API key>(): print ("testing matplotlib qt backend ...") try: # Matplot changed its file structure several times in history, so we # must test all try: from matplotlib.backends.qt_compat import QtCore except: try: from matplotlib.backends.qt4_compat import QtCore except: from matplotlib.backends.qt import QtCore from PyQt4 import QtCore as QtCore4 if QtCore is QtCore4: print ("... test passed") return True else: using = QtCore.__name__.split('.')[0] expect = QtCore4.__name__.split('.')[0] print ("... test FAIL\n" + " Matplotlib is using %s\n" % using + " It must use %s\n" % expect + " Possible reasons for that are that " + "%s is not installed " % expect + "or the envoriment variable QT_API is overwriting it.") return False except: import traceback print(traceback.format_exc()) print ("... Test fail is an expected way! We would like to know why, " "please report in 'https://github.com/nguy/artview/issues'") return None if __name__ == '__main__': <API key>()
package gov.hhs.fha.nhinc.docsubmission.inbound; import org.apache.log4j.Logger; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.docsubmission.DocSubmissionUtils; import gov.hhs.fha.nhinc.docsubmission.<API key>; import gov.hhs.fha.nhinc.docsubmission.XDRAuditLogger; import gov.hhs.fha.nhinc.docsubmission.XDRPolicyChecker; import gov.hhs.fha.nhinc.docsubmission.adapter.proxy.<API key>; import gov.hhs.fha.nhinc.largefile.<API key>; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.nhinclib.NullChecker; import gov.hhs.fha.nhinc.properties.<API key>; import gov.hhs.fha.nhinc.properties.PropertyAccessor; import ihe.iti.xds_b._2007.<API key>; import oasis.names.tc.ebxml_regrep.xsd.rs._3.<API key>; /** * @author akong * */ public class <API key> extends <API key> { private static final Logger LOG = Logger.getLogger(<API key>.class); private <API key> msgUtils = <API key>.getInstance(); private PropertyAccessor propertyAccessor; private XDRPolicyChecker policyChecker; /** * Constructor. */ public <API key>() { this(new <API key>(), new XDRPolicyChecker(), PropertyAccessor.getInstance(), new XDRAuditLogger()); } /** * Constructor with dependency injection of strategy components. * * @param adapterFactory * @param policyChecker * @param propertyAccessor * @param auditLogger */ public <API key>(<API key> adapterFactory, XDRPolicyChecker policyChecker, PropertyAccessor propertyAccessor, XDRAuditLogger auditLogger) { super(adapterFactory, auditLogger); this.policyChecker = policyChecker; this.propertyAccessor = propertyAccessor; } @Override <API key> <API key>(<API key> body, AssertionType assertion) { <API key> response = null; String localHCID = getLocalHCID(); if (isPolicyValid(body, assertion, localHCID)) { try { <API key>(body, assertion); <API key>().<API key>(body); response = sendToAdapter(body, assertion); } catch (<API key> lpe) { LOG.error("Failed to retrieve payload document.", lpe); response = <API key>.getInstance().<API key>(); } } else { LOG.error("Failed policy check. Sending error response."); response = msgUtils.<API key>(); } <API key>(response, assertion); return response; } private boolean isPolicyValid(<API key> request, AssertionType assertion, String receiverHCID) { if (!hasHomeCommunityId(assertion)) { LOG.warn("Failed policy check. Received assertion does not have a home community id."); return false; } String senderHCID = assertion.getHomeCommunity().getHomeCommunityId(); return policyChecker.<API key>(request, assertion, senderHCID, receiverHCID, NhincConstants.<API key>); } private boolean hasHomeCommunityId(AssertionType assertion) { if (assertion != null && assertion.getHomeCommunity() != null && NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { return true; } return false; } private String getLocalHCID() { String localHCID = ""; try { localHCID = propertyAccessor.getProperty(NhincConstants.<API key>, NhincConstants.<API key>); } catch (<API key> ex) { LOG.error("Failed to retrieve local HCID from properties file", ex); } return localHCID; } public DocSubmissionUtils <API key>(){ return DocSubmissionUtils.getInstance(); } }
<?php namespace backend\models; use Yii; /** * This is the model class for table "auth_item". * * @property string $name * @property integer $type * @property string $description * @property string $rule_name * @property string $data * @property integer $created_at * @property integer $updated_at * * @property AuthAssignment[] $authAssignments * @property AuthRule $ruleName * @property AuthItemChild[] $authItemChildren */ class AuthItem extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'auth_item'; } /** * @inheritdoc */ public function rules() { return [ [['name', 'type'], 'required'], [['type', 'created_at', 'updated_at'], 'integer'], [['description', 'data'], 'string'], [['name', 'rule_name'], 'string', 'max' => 64] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'name' => 'Name', 'type' => 'Type', 'description' => 'Description', 'rule_name' => 'Rule Name', 'data' => 'Data', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * @return \yii\db\ActiveQuery */ public function getAuthAssignments() { return $this->hasMany(AuthAssignment::className(), ['item_name' => 'name']); } /** * @return \yii\db\ActiveQuery */ public function getRuleName() { return $this->hasOne(AuthRule::className(), ['name' => 'rule_name']); } /** * @return \yii\db\ActiveQuery */ public function getAuthItemChildren() { return $this->hasMany(AuthItemChild::className(), ['child' => 'name']); } }
package net.fortuna.ical4j.model.parameter; import net.fortuna.ical4j.model.Content; import net.fortuna.ical4j.model.Encodable; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterFactory; import net.fortuna.ical4j.util.Strings; import java.net.URISyntaxException; /** * $Id$ [18-Apr-2004] * * Defines a Value Data Type parameter. * @author Ben Fortuna */ public class Value extends Parameter implements Encodable { private static final long serialVersionUID = -<API key>; private static final String VALUE_BINARY = "BINARY"; private static final String VALUE_BOOLEAN = "BOOLEAN"; private static final String VALUE_CAL_ADDRESS = "CAL-ADDRESS"; private static final String VALUE_DATE = "DATE"; private static final String VALUE_DATE_TIME = "DATE-TIME"; private static final String VALUE_DURATION = "DURATION"; private static final String VALUE_FLOAT = "FLOAT"; private static final String VALUE_INTEGER = "INTEGER"; private static final String VALUE_PERIOD = "PERIOD"; private static final String VALUE_RECUR = "RECUR"; private static final String VALUE_TEXT = "TEXT"; private static final String VALUE_TIME = "TIME"; private static final String VALUE_URI = "URI"; private static final String VALUE_UTC_OFFSET = "UTC-OFFSET"; /** * Binary value type. */ public static final Value BINARY = new Value(VALUE_BINARY); /** * Boolean value type. */ public static final Value BOOLEAN = new Value(VALUE_BOOLEAN); /** * Calendar address value type. */ public static final Value CAL_ADDRESS = new Value(VALUE_CAL_ADDRESS); /** * Date value type. */ public static final Value DATE = new Value(VALUE_DATE); /** * Date-time value type. */ public static final Value DATE_TIME = new Value(VALUE_DATE_TIME); /** * Duration value type. */ public static final Value DURATION = new Value(VALUE_DURATION); /** * Float value type. */ public static final Value FLOAT = new Value(VALUE_FLOAT); /** * Integer value type. */ public static final Value INTEGER = new Value(VALUE_INTEGER); /** * Period value type. */ public static final Value PERIOD = new Value(VALUE_PERIOD); /** * Recurrence value type. */ public static final Value RECUR = new Value(VALUE_RECUR); /** * Text value type. */ public static final Value TEXT = new Value(VALUE_TEXT); /** * Time value type. */ public static final Value TIME = new Value(VALUE_TIME); /** * URI value type. */ public static final Value URI = new Value(VALUE_URI); /** * UTC offset value type. */ public static final Value UTC_OFFSET = new Value(VALUE_UTC_OFFSET); private final String value; /** * @param aValue a string representation of a value data type */ public Value(final String aValue) { super(VALUE, new Factory()); this.value = Strings.unquote(aValue); } /** * {@inheritDoc} */ @Override public final String getValue() { return value; } public static class Factory extends Content.Factory implements ParameterFactory<Value> { private static final long serialVersionUID = 1L; public Factory() { super(VALUE); } @Override public Value createParameter(final String value) throws URISyntaxException { switch (value) { case VALUE_BINARY: return BINARY; case VALUE_BOOLEAN: return BOOLEAN; case VALUE_DATE: return DATE; case VALUE_CAL_ADDRESS: return CAL_ADDRESS; case VALUE_DATE_TIME: return DATE_TIME; case VALUE_DURATION: return DURATION; case VALUE_FLOAT: return FLOAT; case VALUE_INTEGER: return INTEGER; case VALUE_PERIOD: return PERIOD; case VALUE_RECUR: return RECUR; case VALUE_TEXT: return TEXT; case VALUE_TIME: return TIME; case VALUE_URI: return URI; case VALUE_UTC_OFFSET: return UTC_OFFSET; } return new Value(value); } } }
{-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE <API key> #-} {-# LANGUAGE <API key> #-} -- modification, are permitted provided that the following conditions are met: -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module Feldspar.Core.Constructs.MutableToPure ( MutableToPure (..) ) where import qualified Control.Exception as C import Data.Array.IArray import Data.Array.MArray (freeze) import Data.Array.Unsafe (unsafeFreeze) import System.IO.Unsafe import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Binding.HigherOrder (CLambda) import Feldspar.Lattice import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Binding data MutableToPure a where RunMutableArray :: Type a => MutableToPure (Mut (MArr a) :-> Full [a]) WithArray :: Type b => MutableToPure (MArr a :-> ([a] -> Mut b) :-> Full (Mut b)) instance Semantic MutableToPure where semantics RunMutableArray = Sem "runMutableArray" runMutableArrayEval semantics WithArray = Sem "withArray" withArrayEval runMutableArrayEval :: forall a . Mut (MArr a) -> [a] runMutableArrayEval m = unsafePerformIO $ do marr <- m iarr <- unsafeFreeze marr return (elems (iarr :: Array Integer a)) withArrayEval :: forall a b. MArr a -> ([a] -> Mut b) -> Mut b withArrayEval ma f = do a <- f (elems (unsafePerformIO $ freeze ma :: Array Integer a)) C.evaluate a instance Typed MutableToPure where typeDictSym RunMutableArray = Just Dict typeDictSym _ = Nothing semanticInstances ''MutableToPure instance EvalBind MutableToPure where evalBindSym = evalBindSymDefault instance AlphaEq dom dom dom env => AlphaEq MutableToPure MutableToPure dom env where alphaEqSym = alphaEqSymDefault instance Sharable MutableToPure instance Cumulative MutableToPure instance SizeProp MutableToPure where sizeProp RunMutableArray (WrapFull arr :* Nil) = infoSize arr sizeProp WithArray (_ :* WrapFull fun :* Nil) = snd $ infoSize fun instance ( MutableToPure :<: dom , Let :<: dom , (Variable :|| Type) :<: dom , CLambda Type :<: dom , OptimizeSuper dom ) => Optimize MutableToPure dom where optimizeFeat opts sym@WithArray (arr :* fun@(lam :$ body) :* Nil) | Dict <- exprDict fun , Dict <- exprDict body , Just (SubConstr2 (Lambda _)) <- prjLambda lam = do arr' <- optimizeM opts arr let (szl :> sze) = infoSize (getInfo arr') fun' <- optimizeFunction opts (optimizeM opts) (mkInfo (szl :> sze)) fun constructFeat opts sym (arr' :* fun' :* Nil) optimizeFeat opts sym args = optimizeFeatDefault opts sym args constructFeatUnOpt opts RunMutableArray args = <API key> opts typeRep RunMutableArray args constructFeatUnOpt opts WithArray args = <API key> opts (MutType typeRep) WithArray args
#![allow( dead_code, non_snake_case, <API key>, <API key> )] #[allow(non_snake_case, <API key>, <API key>)] pub mod root { #[allow(unused_imports)] use self::super::root; pub mod Halide { #[allow(unused_imports)] use self::super::super::root; #[derive(Debug, Default, Copy, Clone)] pub struct Type { pub _address: u8, } extern "C" { #[link_name = "\u{1}_ZN6Halide4Type1bE"] pub static mut Type_b: root::a; } #[test] fn <API key>() { assert_eq!( ::std::mem::size_of::<Type>(), 1usize, concat!("Size of: ", stringify!(Type)) ); assert_eq!( ::std::mem::align_of::<Type>(), 1usize, concat!("Alignment of ", stringify!(Type)) ); } } #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum a { <API key> = 0, } }
package com.atlassian.plugin.loaders; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.PluginArtifact; import com.atlassian.plugin.<API key>; import com.atlassian.plugin.event.PluginEventManager; import com.atlassian.plugin.factories.PluginFactory; import com.atlassian.plugin.impl.<API key>; import com.atlassian.plugin.loaders.classloading.Scanner; import com.atlassian.plugin.util.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Plugin loader that can find plugins via a single URL, and treats all plugins loaded from * the directory as bundled plugins, meaning they can can be upgraded, but not deleted. * <p> * Depending on the URL: * <ul> * <li>If it is a file:// url and represents a directory, all the files in that directory are scanned.</li> * <li>if it is a file:// url and represents a file with a <code>.list</code> suffix, each line in that files * is read as a path to a plugin jar.</li> * <li>Otherwise it assumes the URL is a zip and unzips plugins from it into a local directory, * and ensures that directory only contains plugins from that zip file. It also</li> * </ul> * */ public class BundledPluginLoader extends <API key> { public BundledPluginLoader(final URL zipUrl, final File pluginPath, final List<PluginFactory> pluginFactories, final PluginEventManager eventManager) { super(buildScanner(zipUrl, pluginPath), pluginFactories, eventManager); } @Override protected Plugin postProcess(final Plugin plugin) { if (plugin instanceof <API key>) { return new <API key>((<API key>)plugin); } return new <API key>(plugin); } private static Scanner buildScanner(final URL url, final File pluginPath) { if (url == null) { throw new <API key>("Bundled plugins url cannot be null"); } Scanner scanner = null; final File file = FileUtils.toFile(url); if (file != null) { if (file.isDirectory()) { // URL points directly to a directory of jars scanner = new DirectoryScanner(file); } else if (file.isFile() && file.getName().endsWith(".list")) { // URL points to a file containg a list of jars final List<File> files = readListFile(file); scanner = new FileListScanner(files); } } if (scanner == null) { // default: assume it is a zip FileUtils.<API key>(url, pluginPath); scanner = new DirectoryScanner(pluginPath); } return scanner; } private static List<File> readListFile(final File file) { try { final List<String> fnames = (List<String>) org.apache.commons.io.FileUtils.readLines(file); final List<File> files = new ArrayList<File>(); for (String fname : fnames) { files.add(new File(fname)); } return files; } catch (IOException e) { throw new <API key>("Unable to read list from " + file, e); } } /** * Delegate that overrides methods to enforce bundled plugin behavior * * @since 2.2.0 */ private static class <API key> extends <API key> { public <API key>(Plugin delegate) { super(delegate); } @Override public boolean isBundledPlugin() { return true; } @Override public boolean isDeleteable() { return false; } } /** * Delegate that overrides methods to enforce bundled plugin behavior for {@link <API key>} implementors * @since 2.9.3 */ private static class <API key> extends <API key> implements <API key> { private final <API key> delegate; private <API key>(final <API key> delegate) { super(delegate); this.delegate = delegate; } public PluginArtifact getPluginArtifact() { return delegate.getPluginArtifact(); } } }
/*! @file @brief Effectseer main @author (hira@rvf-rc45.net) */ #include "main.hpp" #include "utils/i_scene.hpp" #include "utils/director.hpp" #include "widgets/widget_filer.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_button.hpp" #include "widgets/widget_check.hpp" #include "widgets/widget_tree.hpp" #include "widgets/widget_terminal.hpp" #include "mdf/pmd_io.hpp" #include "mdf/pmx_io.hpp" #include "gl_fw/glcamera.hpp" #include "gl_fw/gllight.hpp" #include "effekseer/gl/Renderer.h" namespace app { class effv_main : public utils::i_scene { utils::director<core>& director_; gui::widget_filer* filer_; uint32_t filer_id_; gui::widget_frame* tools_; gui::widget_button* fopen_; gui::widget_check* grid_; gui::widget_button* play_; gui::widget_check* loop_; gl::camera camera_; ::Effekseer::Manager* manager_; ::EffekseerRenderer::Renderer* renderer_; ::Effekseer::Effect* effect_; ::Effekseer::Vector3D position_; ::Effekseer::Handle handle_; void init_effekseer_(const vtx::spos& size); void destroy_effekseer_(); public: /*! @brief */ effv_main(utils::director<core>& d) : director_(d), filer_(0), filer_id_(0), tools_(nullptr), fopen_(nullptr), grid_(nullptr), play_(nullptr), loop_(nullptr), camera_(), manager_(nullptr), renderer_(nullptr), effect_(nullptr), handle_(-1) { } /*! @brief */ virtual ~effv_main() { destroy_effekseer_(); } /*! @brief */ void initialize(); /*! @brief */ void update(); /*! @brief */ void render(); /*! @brief */ void destroy(); }; }
html,body{font-family: "Microsoft YaHei",arial,courier new,courier,"",monospace; letter-spacing: 0.5px;} html,body{height:100%; background-color: #f2f2f2;} li {float: left; list-style: none;} a, a:hover, a:active, a:focus {text-decoration: none; color: #666;} .clear:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clear {display: inline-block;} /* for IE/Mac */ /*<!-- main stylesheet ends, CC with new stylesheet below... -->*/ .clear { zoom: 1; /* triggers hasLayout */ display: block; /* resets display for IE/Win */ } .wrap{height:auto;margin:0 auto -60px;padding:0 0 0px} .container {width: 940px;} .banner {height: 370px; overflow: hidden; width: 100%;} .banner a {height: 370px; width: 100%;display: block;} .wrap>.container{padding:0px 0px 20px;} .footer{height:140px;background-color:#4e4e4e;border-top:1px solid #ddd;padding-top:20px} .jumbotron{text-align:center;background-color:transparent} .jumbotron .btn{font-size:21px;padding:14px 24px} .not-set{color:#c55;font-style:italic} a.asc:after,a.desc:after{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;padding-left:5px} a.asc:after{content:"\e151"} a.desc:after{content:"\e152"} .sort-numerical a.asc:after{content:"\e153"} .sort-numerical a.desc:after{content:"\e154"} .sort-ordinal a.asc:after{content:"\e155"} .sort-ordinal a.desc:after{content:"\e156"} .grid-view th{white-space:nowrap} .hint-block{display:block;margin-top:5px;color:#999} .error-summary{color:#a94442;background:#fdf7f7;border-left:3px solid #eed3d7;padding:10px 20px;margin:0 0 15px 0} .h10{ width: 100%; height: 10px;} ul.cms li{white-space: nowrap; text-align: center; padding: 0px;} ul.cms li a{ padding: 10px 0px; color: #2d393a; font-size: 18px;} ul.cms li.active > a {color: #02acbb; border-color: #eee #eee #eee;background-color: transparent;} ul.cms li.active > a:hover {color: #02acbb; border-color: #eee #eee #ddd;background-color: transparent; cursor: pointer;} .media .media-left img{ width: 150px; height: 110px;} .headimg{ width:100%; height: 180px; background: url(../images/headbg.jpg) no-repeat center center; position: relative; text-align: center;} .myimg{ width: 125px; height: 125px; margin:0 auto; overflow: hidden; border-radius: 75px; border:#fff 2px solid;} .myname{ font-size: 24px; color: #fff;} .myedit{display: inline-block;width: 30px;height: 30px;position: absolute; top: 20px; right: 20px;} .myedit a{color: #fff;} .usermenu i.fa,.user-center .list-group i.fa{ padding: 10px; color: #fff; display: inline-block; border-radius: 5px; margin-right: 10px;} .usermenu i.fa-bell{ background: #26cbab;} .usermenu i.fa-envelope{ background: #e95344;} .usermenu i.fa-star{ background: #edc70c;} .usermenu i.fa-list-alt{ background: #06adf3;} .usermenu i.fa-cog{ background: #fd9c03;} .badge{ background-color: #f40900;line-height: normal;} .usermenu span.fa{ float: right; line-height: 34px;} .user-center .list-group i.fa{float: left;} .user-center .list-group i.fa-warning{background-color: #e65447;} .user-center .list-group i.fa-volume-up{background-color: #26cbab;} .user-center .list-group i.fa-file-text{background-color: #a682c8;} .user-center .list-group i.fa-at{background-color: #2798f4;} .user-center .list-group i.fa-calendar{background-color: #ebc518;} .user-center .list-group h3{color: #222;} .user-center .list-group h3 span{ font-size: 14px; float: right; color: #888;} .user-center .list-group p{height: 36px; line-height: 18px; overflow: hidden; color: #999;} .user-center .list-group span.fa{float: right;} .user-center .list-group .list-group-item{ margin-bottom: 5px;} .mnav { background-color: #fafafa; border-color: #eeeeee; border-width: 0 0 1px; top: 0; border-radius: 0; border: 1px solid transparent; margin-bottom: 20px; position: relative; height: 35px; min-height: 35px; box-shadow: 1px 1px 0px rgba(220,220,220,0.25);; -moz-box-shadow:inset 1px 1px 0px rgba(220,220,220,0.25); -webkit-box-shadow: 1px 1px 0px rgba(220,220,220,0.25); text-align: center; } .mnav-fix{ left: 0; position: fixed; right: 0; z-index: 1030; border-radius: 4px; } .navbar-nav > li > a { padding: 0px 10px; color: #a3a19e; line-height: 35px; } .nav > li.navbar-user-info { padding-right: 20px; } .nav > li.navbar-user-info > a { color: #42b6c3; } .nav > li.navbar-user-info > a:hover, .nav > li.navbar-user-info > a:focus { background-color: transparent; text-decoration: none; } .wrap-top { height: 80px; margin-top: 35px; padding: 0px; background-color: #fff; } .wrap-top .container { position: relative; padding: 0px; } .wrap-top .logo { float: left; display: block; height: 54px; width: 210px; margin-top: 15px; background-image: url('../images/logo.png'); } .wrap-top .menu { float: left; margin-top: 30px; max-width: 400px; overflow: hidden; max-height: 100px; } .wrap-top .menu ul{margin-left: 40px;padding: 0px;} .wrap-top .menu li { margin-left: 30px; font-size: 20px; } .wrap-top .menu li a { color: #333; } .wrap-top .menu li.active a { color: #01adb9; } .wrap-top .search { float: right; height: 40px; margin-top: 20px; position: absolute; right: 0px; } .wrap-top .search .search-input { height: 30px; width: 200px; margin-left: 20px; border: 1px solid #ccc; border-radius: 2px; font-size: 12px; padding-left: 5px; } .wrap-top .search .search-submit { border: none; background-color: #797c80; width: 34px; height: 34px; padding: 7px; background-image: url('../images/search.png'); background-position: center; background-repeat: no-repeat; display: inline; border-radius: 3px; } .site-search .search, .site-search .empty { padding: 30px; text-align: center; } .site-search .search .search-input { height: 30px; width: 700px; margin-left: 20px; border: 1px solid #ccc; border-radius: 2px; font-size: 12px; padding-left: 5px; } .site-search .search .search-submit { border: none; background-color: #797c80; width: 34px; height: 34px; padding: 7px; background-image: url('../images/search.png'); background-position: center; background-repeat: no-repeat; display: inline; border-radius: 3px; } .site-tabs { background-color: #fff; } .mynav { padding: 0px; } .mynav li { border-bottom: 3px solid #fff; padding: 10px 0px; text-align: center; } .mynav li a { color: #333; text-decoration: none; font-size: 22px; cursor: pointer; } .mynav li.active { border-color: #02acbb; } .mynav li.active a { color: #02acbb; } .mynav li:hover { border-bottom: 3px solid #02acbb; background-color: transparent; } .ad {margin-top : 20px;} .ad .ad-left {float: left; width: 630px; height: 180px; background-color: #ccc;} .ad .ad-right {float: right; width: 300px; height: 180px; background-color: #ccc;} .content { margin-top: 20px; } .content .content-left { float:left; width: 630px; } .content .sidebar { float: right; width: 300px; } .section.awsome { margin-top: 20px; } .section .section-title { height: 40px; font-weight: bold; background-color:#fcfcfc; border: 1px solid #eee; box-shadow: 1px 1px 0px rgba(220,220,220,0.25);; -moz-box-shadow:inset 1px 1px 0px rgba(220,220,220,0.25); -webkit-box-shadow: 1px 1px 0px rgba(220,220,220,0.25);; } .section .section-title.section-title-mid { text-align: center; } .section .section-title .section-more, .section .section-title .section-title-text { font-size: 14px; display: inline-block; padding: 10px; } .section .section-title .section-more { float: right; } .section .section-content { background-color: #fff; padding: 0px 20px; min-height: 300px; } .section .section-content .media { padding: 25px 0px; border-bottom: 1px solid #eee; font-size: 12px; line-height:20px; color: #515151; } .section .section-content .media-info i { font-size: 18px; color: #999; } .section .section-content .media-info i.sp { width:100px; display: inline-block; } .section .section-content .media-info span { color: #404a54; font-size: 12px; } .section .section-content .media-heading { font-size: 18px; color: #333; padding-bottom: 10px; display: inline-block; line-height: 20px; } .section .section-content .media-date { float: right; } .section .section-content img { display: block; max-width: 798px; margin-left: auto; margin-right: auto; } .float-tip { position: fixed; display: none; } .float-tip .tip-item { margin-top: 15px; padding: 15px 15px 5px; background-color: #fff; border: 1px solid #ccc; } .float-tip .tip-item .tip-img { width: 100px; height: 100px; background-color: #ccc } .float-tip .tip-item .tip-text { text-align: center; margin-top: 5px; } .float-tip .tip-item.back-top { width: 130px; height: 130px; text-align: center; cursor: pointer; } .float-tip .tip-item.back-top:hover { color: #02acbb; } .float-tip .tip-item .tip-text-back-top { margin-top: 20px; font-size: 15px; line-height: 26px; } .float-tip.article .tip-item { background-color: #41b795; color: white; padding: 8px 8px 3px; height: 60px; width: 60px; } .float-tip.article .tip-item .tip-favor { text-align: center; margin-top: -3px; } .float-tip.article .tip-item .tip-text { text-align: center; margin-top: 0px; font-size: 11px; } .float-tip.article .tip-item .tip-favor i { font-size: 35px; } .float-tip.article .tip-item.back-top { width: 60px; height: 60px; text-align: center; cursor: pointer; } .float-tip.article .tip-item .tip-text-back-top { margin-top: 0px; font-size: 14px; line-height: 20px; } .float-tip.article .tip-item.back-top:hover { color: #000; } .float-tip.article .tip-item.tip-favor:hover { color: red; cursor: pointer; } .breadcrumb li { color: #333; height: 38px; font-size: 12px; font-weight: normal; } .breadcrumb > li + li:before { content: "> "; } .breadcrumb > li a { padding: 0 10px; } .breadcrumb > li.active { color: #02acbb; } .content.single { margin-bottom: 50px; border: 1px solid #eee; border-radius: 5px; } .content .meta .title { font-size: 26px; padding: 30px; text-align: center; } .content .meta .article { background-color: #fff; color: #515151; font-size: 16px; line-height: 28px; padding: 0 30px 30px; text-align: justify; } .content .meta .info { border-bottom: 1px solid #eee; color: #999; padding-bottom: 20px; text-align: center; } .content .meta .info .view, .content .meta .info .time { padding: 10px; }
using System; using System.Collections.Generic; using System.Linq; namespace Orchard.Layouts.ViewModels { public class <API key> { public string Label { get; set; } public string Model { get; set; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Forms | Slate Admin 2.0</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="<API key>" content="yes"> <!-- Styles --> <link href="./css/bootstrap.css" rel="stylesheet"> <link href="./css/<API key>.css" rel="stylesheet"> <link href="./css/bootstrap-overrides.css" rel="stylesheet"> <link href="./css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet"> <link href="./css/slate.css" rel="stylesheet"> <link href="./css/slate-responsive.css" rel="stylesheet"> <!-- Javascript --> <script src="./js/jquery-1.7.2.min.js"></script> <script src="./js/jquery-ui-1.8.21.custom.min.js"></script> <script src="./js/jquery.ui.touch-punch.min.js"></script> <script src="./js/bootstrap.js"></script> <script src="./js/plugins/validate/jquery.validate.js"></script> <script src="./js/Slate.js"></script> <script src="./js/demos/demo.validate.js"></script> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif] </head> <body> <div id="header"> <div class="container"> <h1><a href="./">Slate Admin 2.0</a></h1> <div id="info"> <a href="javascript:;" id="info-trigger"> <i class="icon-cog"></i> </a> <div id="info-menu"> <div class="info-details"> <h4>Welcome back, John D.</h4> <p> Logged in as Admin. <br> You have <a href="javascript:;">5 messages.</a> </p> </div> <!-- /.info-details --> <div class="info-avatar"> <img src="./img/avatar.jpg" alt="avatar"> </div> <!-- /.info-avatar --> </div> <!-- /#info-menu --> </div> <!-- /#info --> </div> <!-- /.container --> </div> <!-- /#header --> <div id="nav"> <div class="container"> <a href="javascript:;" class="btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <i class="icon-reorder"></i> </a> <div class="nav-collapse"> <ul class="nav"> <li class="nav-icon"> <a href="./"> <i class="icon-home"></i> <span>Home</span> </a> </li> <li class="dropdown active"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-th"></i> Components <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="./forms.html">Forms</a></li> <li><a href="./ui-elements.html">UI Elements</a></li> <li><a href="./grid.html">Grid Layout</a></li> <li><a href="./tables.html">Tables</a></li> <li><a href="./widgets.html">Widget Boxes</a></li> <li><a href="./charts.html">Charts</a></li> <li><a href="./tabs.html">Tabs & Accordion</a></li> <li><a href="./buttons.html">Buttons</a></li> </ul> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-copy"></i> Sample Pages <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="./invoice.html">Invoice</a></li> <li><a href="./faq.html">FAQ</a></li> <li><a href="./pricing.html">Pricing Plans</a></li> <li><a href="./gallery.html">Image Gallery</a></li> <li><a href="./wizard.html">Wizard</a></li> <li><a href="./reports.html">Reports</a></li> <li><a href="./calendar.html">Calendar</a></li> </ul> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-external-link"></i> Other Pages <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="./login.html">Login</a></li> <li><a href="./signup.html">Signup</a></li> <li><a href="./error.html">Error</a></li> <li class="dropdown"> <a href="javascript:;"> Dropdown Menu <i class="icon-chevron-right sub-menu-caret"></i> </a> <ul class="dropdown-menu sub-menu"> <li><a href="javascript:;">Dropdown #1</a></li> <li><a href="javascript:;">Dropdown #2</a></li> <li><a href="javascript:;">Dropdown #3</a></li> <li><a href="javascript:;">Dropdown #4</a></li> </ul> </li> </ul> </li> </ul> <ul class="nav pull-right"> <li class=""> <form class="navbar-search pull-left"> <input type="text" class="search-query" placeholder="Search"> <button class="search-btn"><i class="icon-search"></i></button> </form> </li> </ul> </div> <!-- /.nav-collapse --> </div> <!-- /.container --> </div> <!-- /#nav --> <div id="content"> <div class="container"> <div id="page-title" class="clearfix"> <ul class="breadcrumb"> <li> <a href="./">Home</a> <span class="divider">/</span> </li> <li> <a href="#">Components</a> <span class="divider">/</span> </li> <li class="active">Form Styles</li> </ul> </div> <!-- /.page-title --> <div class="row"> <div class="span8"> <div id="horizontal" class="widget widget-form"> <div class="widget-header"> <h3> <i class="icon-pencil"></i> Horizontal Layout </h3> </div> <!-- /widget-header --> <div class="widget-content"> <form class="form-horizontal"> <fieldset> <div class="control-group"> <label class="control-label" for="input01">Text input</label> <div class="controls"> <input type="text" class="input-large" id="input01"> <p class="help-block">In addition to freeform text, any HTML5 text-based input appears like so.</p> </div> </div> <div class="control-group"> <label class="control-label" for="select01">Select list</label> <div class="controls"> <select id="select01"> <option>something</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> </div> <div class="control-group"> <label class="control-label" for="multiSelect">Multicon-select</label> <div class="controls"> <select multiple="multiple" id="multiSelect"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> </div> <div class="control-group"> <label class="control-label" for="fileInput">File input</label> <div class="controls"> <input class="input-file" id="fileInput" type="file"> </div> </div> <div class="control-group"> <label class="control-label" for="textarea">Textarea</label> <div class="controls"> <textarea class="input-large" id="textarea" rows="3"></textarea> </div> </div> <div class="control-group"> <label class="control-label">Inline checkboxes</label> <div class="controls"> <label class="checkbox inline"> <input type="checkbox" id="inlineCheckbox1" value="option1"> 1 </label> <label class="checkbox inline"> <input type="checkbox" id="inlineCheckbox2" value="option2"> 2 </label> <label class="checkbox inline"> <input type="checkbox" id="inlineCheckbox3" value="option3"> 3 </label> </div> </div> <div class="control-group"> <label class="control-label">Checkboxes</label> <div class="controls"> <label class="checkbox"> <input type="checkbox" name="<API key>" value="option1"> Option one is this and that-be sure to include why it's great </label> <label class="checkbox"> <input type="checkbox" name="<API key>" value="option2"> Option two can also be checked and included in form results </label> </div> </div> <div class="control-group"> <label class="control-label">Radio buttons</label> <div class="controls"> <label class="radio"> <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked=""> Option one is this and that-be sure to include why it's great </label> <label class="radio"> <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2"> Option two can is something else and selecting it will deselect option one </label> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-large">Save changes</button> <button class="btn btn-large">Cancel</button> </div> </fieldset> </form> </div> <!-- /widget-content --> </div> <div id="validation" class="widget highlight widget-form"> <div class="widget-header"> <h3> <i class="icon-pencil"></i> Form Validation </h3> </div> <!-- /widget-header --> <div class="widget-content"> <div class="alert alert-block"> <a class="close" data-dismiss="alert" href="#">&times;</a> <h4 class="alert-heading">Validation Example!</h4> Submit the below form to view the live form validation with integrated Bootstrap error messages. </div> <form action="/" id="contact-form" class="form-horizontal" novalidate="novalidate"> <fieldset> <div class="control-group"> <label class="control-label" for="name">Your Name</label> <div class="controls"> <input type="text" class="input-large" name="name" id="name"> </div> </div> <div class="control-group"> <label class="control-label" for="email">Email Address</label> <div class="controls"> <input type="text" class="input-large" name="email" id="email"> </div> </div> <div class="control-group"> <label class="control-label" for="subject">Subject</label> <div class="controls"> <input type="text" class="input-large" name="subject" id="subject"> </div> </div> <div class="control-group"> <label class="control-label" for="message">Your Message</label> <div class="controls"> <textarea class="input-large" name="message" id="message" rows="3"></textarea> </div> </div> <div class="control-group"> <label class="control-label" for="validateSelect">Select list</label> <div class="controls"> <select id="validateSelect" name="validateSelect"> <option value="">Select...</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div> <div class="control-group"> <label class="control-label">Checkboxes</label> <div class="controls"> <label class="checkbox"> <input type="checkbox" name="validateCheckbox" value="option1"> Option one is this and that-be sure to include why it's great </label> <label class="checkbox"> <input type="checkbox" name="validateCheckbox" value="option2"> Option two can also be checked and included in form results </label> <label class="checkbox"> <input type="checkbox" name="validateCheckbox" value="option3"> Option three can-yes, you guessed it-also be checked and included in form results </label> <p class="help-block"><strong>Note:</strong> Labels surround all the options for much larger click areas and a more usable form.</p> </div> </div> <div class="control-group"> <label class="control-label">Radio buttons</label> <div class="controls"> <label class="radio"> <input type="radio" name="validateRadio" id="validateRadio1" value="option1"> Option one is this and that-be sure to include why it's great </label> <label class="radio"> <input type="radio" name="validateRadio" id="validateRadio2" value="option2"> Option two can is something else and selecting it will deselect option one </label> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-danger btn-large"><i class="icon-star"></i> Validate</button> <button type="reset" class="btn btn-large">Cancel</button> </div> </fieldset> </form> </div> <!-- /widget-content --> </div> <div id="appendprepend" class="widget widget-form"> <div class="widget-header"> <h3> <i class="icon-pencil"></i> Append/Prepend </h3> </div> <!-- /widget-header --> <div class="widget-content"> <form class="form-horizontal"> <fieldset> <div class="control-group"> <label class="control-label" for="prependedInput">Prepended text</label> <div class="controls"> <div class="input-prepend"> <span class="add-on">@</span><input class="span2" id="prependedInput" size="16" type="text"> </div> <p class="help-block">Here's some help text</p> </div> </div> <div class="control-group"> <label class="control-label" for="appendedInput">Appended text</label> <div class="controls"> <div class="input-append"> <input class="span2" id="appendedInput" size="16" type="text"><span class="add-on">.00</span> </div> <span class="help-inline">Here's more help text</span> </div> </div> <div class="control-group"> <label class="control-label" for="<API key>">Append and prepend</label> <div class="controls"> <div class="input-prepend input-append"> <span class="add-on">$</span><input class="span2" id="<API key>" size="16" type="text"><span class="add-on">.00</span> </div> </div> </div> <div class="control-group"> <label class="control-label" for="appendedInputButton">Append with button</label> <div class="controls"> <div class="input-append"> <input class="span2" id="appendedInputButton" size="16" type="text"><button class="btn" type="button">Go!</button> </div> </div> </div> <div class="control-group"> <label class="control-label" for="<API key>">Two-button append</label> <div class="controls"> <div class="input-append"> <input class="span2" id="<API key>" size="16" type="text"><button class="btn" type="button">Search</button><button class="btn" type="button">Options</button> </div> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-large">Save changes</button> <button class="btn btn-large">Cancel</button> </div> </fieldset> </form> </div> <!-- /widget-content --> </div> <!-- /.widget --> <div id="control" class="widget widget-form"> <div class="widget-header"> <h3> <i class="icon-pencil"></i> Control States </h3> </div> <!-- /widget-header --> <div class="widget-content"> <form class="form-horizontal"> <fieldset> <div class="control-group"> <label class="control-label" for="focusedInput">Focused input</label> <div class="controls"> <input class="input-large focused" id="focusedInput" type="text" value="This is focused..."> </div> </div> <div class="control-group"> <label class="control-label">Uneditable input</label> <div class="controls"> <span class="input-large uneditable-input">Some value here</span> </div> </div> <div class="control-group"> <label class="control-label" for="disabledInput">Disabled input</label> <div class="controls"> <input class="input-large disabled" id="disabledInput" type="text" placeholder="Disabled input here..." disabled=""> </div> </div> <div class="control-group"> <label class="control-label" for="optionsCheckbox2">Disabled checkbox</label> <div class="controls"> <label class="checkbox"> <input type="checkbox" id="optionsCheckbox2" value="option1" disabled=""> This is a disabled checkbox </label> </div> </div> <div class="control-group warning"> <label class="control-label" for="inputWarning">Input with warning</label> <div class="controls"> <input type="text" id="inputWarning"> <span class="help-inline">Something may have gone wrong</span> </div> </div> <div class="control-group error"> <label class="control-label" for="inputError">Input with error</label> <div class="controls"> <input type="text" id="inputError"> <span class="help-inline">Please correct the error</span> </div> </div> <div class="control-group success"> <label class="control-label" for="inputSuccess">Input with success</label> <div class="controls"> <input type="text" id="inputSuccess"> <span class="help-inline">Woohoo!</span> </div> </div> <div class="control-group success"> <label class="control-label" for="selectError">Select with success</label> <div class="controls"> <select id="selectError"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <span class="help-inline">Woohoo!</span> </div> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary btn-large">Save changes</button> <button class="btn btn-large">Cancel</button> </div> </fieldset> </form> </div> <!-- /widget-content --> </div> <!-- /.widget --> </div> <!-- /span8 --> <div class="span4"> <div id="formToc" class="widget highlight"> <div class="widget-header"> <h3>Flexible HTML and CSS</h3> </div> <!-- /widget-header --> <div class="widget-content"> <p>The best part about forms in Bootstrap is that all your inputs and controls look great no matter how you build them in your markup. No superfluous HTML is required, but we provide the patterns for those who require it.</p> <br> <p>Bootstrap's forms include styles for all the base form controls like input, textarea, and select you'd expect. But it also comes with a number of custom components like appended and prepended inputs and support for lists of checkboxes.</p> </div> <!-- /widget-content --> </div> <!-- /widget --> </div> <!-- /.span4 --> </div> <!-- /row --> </div> <!-- /.container --> </div> <!-- /#content --> <div id="footer"> <div class="container"> &copy; 2012 Propel UI, all rights reserved. </div> <!-- /.container --> </div> <!-- /#footer --> </body> </html>
define("ace/snippets/tconf",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = " # TConf snippets - for TConf, see below #\n\ \n\ snippet if\n\ if ${1:condition} then\n\ ${2}\n\ endif\n\ snippet if-else\n\ if ${1:condition} then\n\ ${2}\n\ else\n\ ${3}\n\ endif\n\ snippet if-elseif-else\n\ if ${1:condition} then\n\ ${2}\n\ elseif ${3:condition} then\n\ ${4}\n\ else\n\ ${5}\n\ endif\n\ #snippet ife\n\ # if ${1:condition} then\n\ # else\n\ # endif\n\ #snippet elsif\n\ # elsif ${1:condition} then\n\ snippet in\n\ in [${1:value1}, ${2:value2} ]\n\ snippet find\n\ find(${1:value1}, ${2:value2} )\n\ snippet copy\n\ copy(${1:pub.fid1}, [${2:pub.fid2}, ${3:pub.fid3}] )\n\ snippet exists\n\ exists(${1:src.FID}) == ${2:#true}\n\ snippet strtime\n\ strtime(${1:\"2116-12-20 22:00:00.000\"})\n\ snippet map\n\ map(${1:src.trd_prc_1}, {${2:key1}\\:${3:value1},${4:key2}\\:${5:value2}})\n\ snippet convert_date\n\ convert_date(time_service, ${1:#GMTDATE}, ${2:#GMTTIME}, ${3:\"MUT\\%DST\"})\n\ snippet <API key>\n\ <API key>(time_service, ${1:#GMTDATE}, ${2:#GMTTIME},${3:\"MUT\\%DST\"},${4:\"MUT\\%FD01\"}, ${5:\"MUT\\%HOL1\"})\n\ snippet rescale\n\ rescale(${1: veh.nav_netchn/ veh.navalue * 100}, ${2:-6} )\n\ #snippet pub\n\ # pub.FID // e.g. pub.trdprc_1\n\ #snippet pub.\n\ # FID // e.g. trdprc_1\n\ #snippet src\n\ # src.FID // e.g. src.trdc_1\n\ #snippet src.\n\ # FID // e.g. trdprc_1\n\ #snippet veh\n\ # veh.FID // e.g. veh.trdprc_1\n\ #snippet veh.\n\ # FID // e.g. trdprc_1\n\ "; exports.scope = "tconf"; });
using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Storage; namespace Mle.IO { public class StorageFileUtils { public StorageFolder Folder { get; private set; } public StorageFileUtils(StorageFolder folder) { Folder = folder; } public Task<IEnumerable<StorageFile>> ListFiles(string relativeFolder, bool recursive = false) { return Folder.ListFiles(relativeFolder, recursive); } public virtual Uri UriFor(IStorageFile file) { return new Uri(file.Path); } } }
<!DOCTYPE html> <html xmlns="http: <head> <meta charset="utf-8" /> <title>statsmodels.regression.mixed_linear_model.MixedLMResults.aic &#8212; statsmodels v0.10.2 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="<API key>" data-url_root="../" src="../_static/<API key>.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=<API key>"></script> <link rel="shortcut icon" href="../_static/<API key>.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.regression.mixed_linear_model.MixedLMResults.bic" href="statsmodels.regression.mixed_linear_model.MixedLMResults.bic.html" /> <link rel="prev" title="statsmodels.regression.mixed_linear_model.MixedLMResults" href="statsmodels.regression.mixed_linear_model.MixedLMResults.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/<API key>.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.regression.mixed_linear_model.MixedLMResults.bic.html" title="statsmodels.regression.mixed_linear_model.MixedLMResults.bic" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.regression.mixed_linear_model.MixedLMResults.html" title="statsmodels.regression.mixed_linear_model.MixedLMResults" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../mixed_linear.html" >Linear Mixed Effects Models</a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.regression.mixed_linear_model.MixedLMResults.html" accesskey="U">statsmodels.regression.mixed_linear_model.MixedLMResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="<API key>"> <h1>statsmodels.regression.mixed_linear_model.MixedLMResults.aic<a class="headerlink" href=" <p>method</p> <dl class="method"> <dt id="statsmodels.regression.mixed_linear_model.MixedLMResults.aic"> <code class="sig-prename descclassname">MixedLMResults.</code><code class="sig-name descname">aic</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/regression/mixed_linear_model.html <dd><p>Akaike information criterion</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="<API key>"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.regression.mixed_linear_model.MixedLMResults.html" title="previous chapter">statsmodels.regression.mixed_linear_model.MixedLMResults</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.regression.mixed_linear_model.MixedLMResults.bic.html" title="next chapter">statsmodels.regression.mixed_linear_model.MixedLMResults.bic</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.regression.mixed_linear_model.MixedLMResults.aic.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> & Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.2.1. </div> </body> </html>
from __future__ import print_function from __future__ import division import hoomd import pytest import numpy as np import hoomd.hpmc.pytest.conftest def <API key>(): xmax = 0.02 dx = 1e-4 sdf = hoomd.hpmc.compute.SDF(xmax=xmax, dx=dx) assert np.isclose(sdf.xmax, xmax) assert np.isclose(sdf.dx, dx) xmax = 0.04 dx = 2e-4 sdf.xmax = xmax sdf.dx = dx assert np.isclose(sdf.xmax, xmax) assert np.isclose(sdf.dx, dx) with pytest.raises(hoomd.error.DataAccessError): sdf.sdf with pytest.raises(hoomd.error.DataAccessError): sdf.betaP def <API key>(valid_args, simulation_factory, <API key>): integrator, args, n_dimensions = valid_args snap = <API key>(particle_types=['A'], dimensions=n_dimensions) sim = simulation_factory(snap) # Need to unpack union integrators if isinstance(integrator, tuple): inner_integrator = integrator[0] integrator = integrator[1] inner_mc = inner_integrator() for i in range(len(args["shapes"])): # This will fill in default values for the inner shape objects inner_mc.shape["A"] = args["shapes"][i] args["shapes"][i] = inner_mc.shape["A"] mc = integrator() mc.shape["A"] = args sim.operations.add(mc) xmax = 0.02 dx = 1e-4 sdf = hoomd.hpmc.compute.SDF(xmax=xmax, dx=dx) sim.operations.add(sdf) assert len(sim.operations.computes) == 1 sim.run(0) assert np.isclose(sdf.xmax, xmax) assert np.isclose(sdf.dx, dx) xmax = 0.04 dx = 2e-4 sdf.xmax = xmax sdf.dx = dx assert np.isclose(sdf.xmax, xmax) assert np.isclose(sdf.dx, dx) sim.run(10) if not np.isnan(sdf.sdf).all(): assert sim.device.communicator.rank == 0 assert isinstance(sdf.sdf, np.ndarray) assert len(sdf.sdf) > 0 assert isinstance(sdf.betaP, float) assert not np.isclose(sdf.betaP, 0) else: assert sim.device.communicator.rank > 0 assert sdf.betaP is None _avg = np.array([ 55.20126953, 54.89853516, 54.77910156, 54.56660156, 54.22255859, 53.83935547, 53.77617188, 53.42109375, 53.05546875, 52.86376953, 52.65576172, 52.21240234, 52.07402344, 51.88974609, 51.69990234, 51.32099609, 51.09775391, 51.06533203, 50.61923828, 50.35566406, 50.07197266, 49.92275391, 49.51914062, 49.39013672, 49.17597656, 48.91982422, 48.64580078, 48.30712891, 48.12207031, 47.815625, 47.57744141, 47.37099609, 47.14765625, 46.92382812, 46.6984375, 46.66943359, 46.18203125, 45.95615234, 45.66650391, 45.52714844, 45.39951172, 45.04599609, 44.90908203, 44.62197266, 44.37460937, 44.02998047, 43.84306641, 43.53310547, 43.55, 43.29589844, 43.06054688, 42.85097656, 42.58837891, 42.39326172, 42.21152344, 41.91777344, 41.71054687, 41.68232422, 41.42177734, 41.08085938, 40.91435547, 40.76123047, 40.45380859, 40.178125, 40.14853516, 39.81972656, 39.60585938, 39.44169922, 39.34179688, 39.09541016, 38.78105469, 38.60087891, 38.56572266, 38.27158203, 38.02011719, 37.865625, 37.77851562, 37.51113281, 37.25615234, 37.23857422, 36.91757812, 36.68486328, 36.57675781, 36.39140625, 36.06240234, 36.01962891, 35.8375, 35.51914062, 35.3640625, 35.29042969, 34.86337891, 34.72460938, 34.73964844, 34.57871094, 34.32685547, 34.02607422, 33.78271484, 33.82548828, 33.53808594, 33.40341797, 33.17861328, 33.05439453, 32.80361328, 32.55478516, 32.53759766, 32.28447266, 32.26513672, 32.05732422, 31.82294922, 31.83535156, 31.56376953, 31.46337891, 31.27431641, 30.88310547, 30.85107422, 30.63320313, 30.57822266, 30.28886719, 30.28183594, 30.05927734, 29.98896484, 29.690625, 29.51816406, 29.40742188, 29.2328125, 29.19853516, 28.94599609, 28.80449219, 28.47480469, 28.48476563, 28.31738281, 28.21455078, 28.00878906, 27.90458984, 27.84970703, 27.54052734, 27.43818359, 27.31064453, 27.12773437, 26.91464844, 26.84511719, 26.78701172, 26.53603516, 26.39853516, 26.13779297, 26.16269531, 25.92138672, 25.80244141, 25.75234375, 25.49384766, 25.37197266, 25.26962891, 25.14287109, 24.87558594, 24.778125, 24.68320312, 24.65957031, 24.44404297, 24.31621094, 24.203125, 24.12402344, 23.89628906, 23.76621094, 23.56923828, 23.38095703, 23.32724609, 23.25498047, 23.09697266, 23.04716797, 22.90712891, 22.68662109, 22.59970703, 22.54824219, 22.53632813, 22.29267578, 22.08613281, 21.98398437, 21.89169922, 21.74550781, 21.75878906, 21.45625, 21.37529297, 21.1890625, 21.18417969, 21.0671875, 20.95087891, 20.81650391, 20.60390625, 20.66953125, 20.4640625, 20.47021484, 20.12988281, 20.17099609, 20.05224609, 19.89619141, 19.80859375, 19.72558594, 19.64990234, 19.43525391, 19.38203125 ]) _err = np.array([ 1.21368492, 1.07520243, 1.22496485, 1.07203861, 1.31918198, 1.15482965, 1.11606943, 1.12342247, 1.1214123, 1.2033176, 1.14923442, 1.11741796, 1.08633901, 1.10809585, 1.13268611, 1.17159683, 1.12298656, 1.27754418, 1.09430177, 1.08989947, 1.051715, 1.13990382, 1.16086636, 1.19538929, 1.09450355, 1.10057404, 0.98204849, 1.02542969, 1.10736805, 1.18062055, 1.12365972, 1.12265463, 1.06131492, 1.15169701, 1.13772836, 1.03968987, 1.04348243, 1.00617502, 1.02450203, 1.08293272, 1.02187476, 1.00072731, 1.0267637, 1.08289546, 1.03696814, 1.01035732, 1.05730499, 1.07088231, 1.00528653, 0.9195167, 0.99235353, 1.00839744, 0.98700882, 0.87196929, 1.00124084, 0.96481759, 0.9412312, 1.04691734, 0.92419062, 0.89478269, 0.85106599, 1.0143535, 1.07011876, 0.88196475, 0.8708013, 0.91838154, 0.9309356, 0.97521482, 0.94277816, 0.86336248, 0.8845162, 1.00421706, 0.87940419, 0.85516477, 0.86071935, 0.96725404, 0.87175829, 0.86386878, 0.96833751, 0.87554994, 0.8449041, 0.77404494, 0.92879454, 0.95780868, 0.84341047, 0.88067771, 0.83393048, 0.94414754, 0.94671484, 0.84554255, 0.8906436, 0.84538732, 0.78517686, 0.89134056, 0.78446042, 0.8952503, 0.84624311, 0.79573064, 0.85422345, 0.88918562, 0.75531048, 0.82884413, 0.83369698, 0.77627999, 0.84187759, 0.87986859, 0.86356705, 0.90929237, 0.83017397, 0.86393341, 0.81426374, 0.80991068, 0.86676111, 0.75232448, 0.8021119, 0.68794232, 0.69039919, 0.71421068, 0.77667793, 0.82113389, 0.70256397, 0.83293526, 0.69512453, 0.75148262, 0.7407287, 0.74124134, 0.77846167, 0.7941425, 0.81125561, 0.73334183, 0.76452184, 0.71159507, 0.67302729, 0.66175046, 0.84778683, 0.66273563, 0.76777339, 0.71355888, 0.74460445, 0.76623613, 0.63883733, 0.6887326, 0.74616778, 0.65223179, 0.76358086, 0.68985286, 0.66273563, 0.72437662, 0.77382571, 0.66234322, 0.74757211, 0.62809942, 0.75606851, 0.65375498, 0.65920693, 0.64767863, 0.67683992, 0.63170556, 0.69891621, 0.70708048, 0.64583276, 0.73903135, 0.60068155, 0.66055863, 0.69614341, 0.61515868, 0.63001311, 0.68602529, 0.7014929, 0.61950453, 0.60049188, 0.6259654, 0.55819764, 0.65039367, 0.67079534, 0.60552195, 0.64864663, 0.59901689, 0.65517427, 0.55348699, 0.57578738, 0.6253923, 0.62679547, 0.61274744, 0.5681065, 0.6065114, 0.61170127, 0.60009145, 0.61583989, 0.63889728, 0.66477228, 0.60133457, 0.56484264, 0.5676353, 0.55359946, 0.59000379, 0.60483562, 0.57305916, 0.57591598, 0.66462928 ]) @pytest.mark.validate def test_values(simulation_factory, <API key>): <API key> = 32 phi = 0.8 # packing fraction poly_A = 1 # assumes squares N = <API key>**2 area = N * poly_A / phi L = np.sqrt(area) a = L / <API key> snap = <API key>(dimensions=2, n=<API key>, a=a) sim = simulation_factory(snap) sim.seed = 10 mc = hoomd.hpmc.integrate.ConvexPolygon(default_d=0.1) mc.shape["A"] = { 'vertices': [(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)] } sim.operations.add(mc) sdf = hoomd.hpmc.compute.SDF(xmax=0.02, dx=1e-4) sim.operations.add(sdf) sdf_log = hoomd.conftest.ListWriter(sdf, 'sdf') sim.operations.writers.append( hoomd.write.CustomWriter(action=sdf_log, trigger=hoomd.trigger.Periodic(10))) sim.run(6000) sdf_data = np.asarray(sdf_log.data) if sim.device.communicator.rank == 0: # skip the first frame in averaging, then check that all values are # within 3 error bars of the reference avg. This seems sufficient to get # good test results even with different seeds or GPU runs v = np.mean(sdf_data[1:, :], axis=0) invalid = np.abs(_avg - v) > (8 * _err) assert np.sum(invalid) == 0
<?php namespace app\components; class EmailEvent extends BasicEvent { const EVENT_TYPE_EMAIL = 'email'; /** * @param \app\models\Event $event * @param $object * @param \app\models\EventType $type * @return bool */ public static function generateEvents($event, $object, $type) { $res = parent::generateEvents($event, $object, $type); // TODO: Change the autogenerated stub if ($res) { self::sendMail(); } return $res; } public static function sendMail() { } }
#setup git git config --global user.email "s3562412@student.rmit.edu.au" git config --global user.name "Loy Larvin" #clone the docker repository git clone --quiet --branch=master https://larvinloy:$GITHUB_API_KEY@github.com/larvinloy/docker-dareon #go into directory and copy data we're interested rm -f docker-dareon/docker/DareonWebApp-0.0.1-SNAPSHOT.jar cp target/DareonWebApp-0.0.1-SNAPSHOT.jar docker-dareon/docker/ #add, commit and push files cd docker-dareon git add . git commit -m "Travis build $TRAVIS_BUILD_NUMBER pushed " git push -fq origin master echo -e "Done\n"
/** * @file testing/blas_l2/test_cgemv_offset.c * KBLAS is a high performance CUDA library for subset of BLAS * and LAPACK routines optimized for NVIDIA GPUs. * KBLAS is provided by KAUST. * * @version 3.0.0 * @author Ahmad Abdelfattah * @date 2018-11-14 **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/time.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_runtime_api.h> #include <cublas_v2.h> #include "kblas.h" #include "testing_utils.h" #define FMULS_GEMV(n) ((n) * (n) + 2. * (n)) #define FADDS_GEMV(n) ((n) * (n) ) #define PRECISION_c #if defined(PRECISION_z) || defined(PRECISION_c) #define FLOPS(n) ( 6. * FMULS_GEMV(n) + 2. * FADDS_GEMV(n)) #else #define FLOPS(n) ( FMULS_GEMV(n) + FADDS_GEMV(n)) #endif int main(int argc, char** argv) { if(argc < 7) { printf("USAGE: %s <device-id> <no-trans'n' or trans't' or conj-trans'c'> <matrix-dim> <start-offset> <stop-offset> <step-offset>\n", argv[0]); printf("==> <device-id>: GPU device id to use \n"); printf("==> <no-trans'n' or trans't' or conj-trans'c'>: Process the matrix in non-transposed,transposed, or conjugate transposed configuration \n"); printf("==> <matrix-dim>: The dimension of the matrix\n"); printf("==> <start-offset> <stop-offset> <step-offset>: Offset range. For every <offset> in the offset range, test is performed on a submatrix whose dimension is <matrix-dim>-<offset>\n"); exit(-1); } int dev = atoi(argv[1]); char trans = *argv[2]; int dim = atoi(argv[3]); int istart = atoi(argv[4]); int istop = atoi(argv[5]); int istep = atoi(argv[6]); const int nruns = NRUNS; cudaError_t ed = cudaSetDevice(dev); if(ed != cudaSuccess){printf("Error setting device : %s \n", cudaGetErrorString(ed) ); exit(-1);} cublasHandle_t cublas_handle; cublasAtomicsMode_t mode = <API key>; cublasCreate(&cublas_handle); <API key>(cublas_handle, mode); struct cudaDeviceProp deviceProp; <API key>(&deviceProp, dev); if(istop >= dim){printf("Error: maximum offset value causes zero or negative submatrix dimension\n"); exit(-1);} int M = dim; int N = M; int LDA = M; int LDA_ = ((M+31)/32)*32; int incx = 1; int incy = 1; int vecsize_x = N * abs(incx); int vecsize_y = M * abs(incy); cublasOperation_t trans_; if(trans == 'N' || trans == 'n') trans_ = CUBLAS_OP_N; else if (trans == 'T' || trans == 't') trans_ = CUBLAS_OP_T; else if (trans == 'C' || trans == 'c') trans_ = CUBLAS_OP_C; cuFloatComplex alpha = kblas_crand(); cuFloatComplex beta = kblas_crand(); cudaError_t err; cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); // point to host memory cuFloatComplex* A = NULL; cuFloatComplex* x = NULL; cuFloatComplex* ycuda = NULL; cuFloatComplex* ykblas = NULL; // point to device memory cuFloatComplex* dA = NULL; cuFloatComplex* dx = NULL; cuFloatComplex* dy = NULL; if(trans == 'N' || trans == 'n')printf("non-transposed test .. \n"); else if (trans == 'T' || trans == 't') printf("transposed test .. \n"); else if (trans == 'C' || trans == 'c') printf("Conjugate transposed test .. \n"); else { printf("transpose configuration is not properly specified\n"); exit(-1);} printf("Allocating Matrices\n"); A = (cuFloatComplex*)malloc(N*LDA*sizeof(cuFloatComplex)); x = (cuFloatComplex*)malloc(vecsize_x*sizeof(cuFloatComplex)); ycuda = (cuFloatComplex*)malloc(vecsize_y*sizeof(cuFloatComplex)); ykblas = (cuFloatComplex*)malloc(vecsize_y*sizeof(cuFloatComplex)); err = cudaMalloc((void**)&dA, N*LDA_*sizeof(cuFloatComplex)); if(err != cudaSuccess){printf("ERROR: %s \n", cudaGetErrorString(err)); exit(1);} err = cudaMalloc((void**)&dx, vecsize_x*sizeof(cuFloatComplex)); if(err != cudaSuccess){printf("ERROR: %s \n", cudaGetErrorString(err)); exit(1);} err = cudaMalloc((void**)&dy, vecsize_y*sizeof(cuFloatComplex)); if(err != cudaSuccess){printf("ERROR: %s \n", cudaGetErrorString(err)); exit(1);} // Initialize matrix and vector printf("Initializing on cpu .. \n"); int i, j, m; for(i = 0; i < M; i++) for(j = 0; j < N; j++) A[j*LDA+i] = kblas_crand(); for(i = 0; i < vecsize_x; i++) x[i] = kblas_crand(); cublasSetMatrix(dim, dim, sizeof(cuFloatComplex), A, LDA, dA, LDA_); cudaMemcpy(dx, x, vecsize_x*sizeof(cuFloatComplex), <API key>); printf(" printf(" Matrix CUBLAS KBLAS Max. \n"); printf(" Dimension (Gflop/s) (Gflop/s) Error \n"); printf(" int r; for(m = istart; m <= istop; m += istep) { float elapsedTime; int offset = m; int dim_ = dim-offset; float flops = FLOPS( (float)dim_ ) / 1e6; for(i = 0; i < vecsize_y; i++) { // init y for now until beta is supported in gemv2 ycuda[i] = kblas_crand(); ykblas[i].x = ycuda[i].x; ykblas[i].y = ycuda[i].y; } // handle the offset cuFloatComplex* dA_ = dA + offset * LDA_ + offset; cuFloatComplex* dx_ = dx + offset * incx; cuFloatComplex* dy_ = dy + offset * incy; int vecsize_y_ = vecsize_y - offset; int vecsize_x_ = vecsize_x - offset; elapsedTime = 0; for(r = 0; r < nruns; r++) { cudaMemcpy(dy_, ycuda, vecsize_y_ * sizeof(cuFloatComplex), <API key>); cudaEventRecord(start, 0); cublasCgemv(cublas_handle, trans_, dim_, dim_, &alpha, dA_, LDA_, dx_, incx, &beta, dy_, incy); cudaEventRecord(stop, 0); <API key>(stop); float time = 0; <API key>(&time, start, stop); elapsedTime += time; } elapsedTime /= nruns; float cuda_perf = flops / elapsedTime; cudaMemcpy(ycuda, dy_, vecsize_y_ * sizeof(cuFloatComplex), <API key>); // end of cuda test elapsedTime = 0; for(r = 0; r < nruns; r++) { cudaMemcpy(dy_, ykblas, vecsize_y_ * sizeof(cuFloatComplex), <API key>); cudaEventRecord(start, 0); kblas_cgemv_offset( trans, dim, dim, alpha, dA, LDA_, dx, incx, beta, dy, incy, offset, offset); cudaEventRecord(stop, 0); <API key>(stop); float time = 0; <API key>(&time, start, stop); elapsedTime += time; } elapsedTime /= nruns; float kblas_perf = flops / elapsedTime; cudaMemcpy(ykblas, dy_, vecsize_y_ * sizeof(cuFloatComplex), <API key>); // testing error -- specify ref. vector and result vector cuFloatComplex* yref = ycuda; cuFloatComplex* yres = ykblas; float error = cget_max_error(yref, yres, dim_, incy); //for(i = 0; i < m; i++) printf("[%d]: %-8.2f %-8.2f\n", i, ycuda[i], ykblas[i]); printf("%-11d %-10.2f %-10.2f %-10e;\n", dim_, cuda_perf, kblas_perf, error); } cudaEventDestroy(start); cudaEventDestroy(stop); if(dA)cudaFree(dA); if(dx)cudaFree(dx); if(dy)cudaFree(dy); if(A)free(A); if(x)free(x); if(ycuda)free(ycuda); if(ykblas)free(ykblas); cublasDestroy(cublas_handle); return EXIT_SUCCESS; }
<?php namespace yii\caching; /** * DummyCache * * DummyCache * 'cache' `\Yii::$app->cache` * DummyCache * * * Cache [guide article on caching](guide:caching-overview) * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class DummyCache extends Cache { /** * * * @param string $key * @return mixed|false false */ protected function getValue($key) { return false; } /** * * * * @param string $key * @param mixed $value * @param int $duration 0 * @return bool true false */ protected function setValue($key, $value, $duration) { return true; } /** * * * @param string $key * @param mixed $value * @param int $duration 0 * @return bool true false */ protected function addValue($key, $value, $duration) { return true; } /** * * * @param string $key * @return bool */ protected function deleteValue($key) { return true; } /** * * * @return bool */ protected function flushValues() { return true; } }
// This file has been generated by Py++. #include "boost/python.hpp" #include "indexing_suite/value_traits.hpp" #include "indexing_suite/container_suite.hpp" #include "indexing_suite/map.hpp" #include "wrap_osgfx.h" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/<API key>.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/anisotropiclighting.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/bumpmapping.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/cartoon.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/effect.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/effectmap.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/multitexturecontrol.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/outline.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/registry.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/scribe.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/specularhighlights.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/technique.pypp.hpp" #include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osgfx/generated_code/validator.pypp.hpp" namespace bp = boost::python; BOOST_PYTHON_MODULE(_osgFX){ <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); <API key>(); }
<?php namespace Krystal\Security; use <API key>; use <API key>; use Krystal\Text\TextUtils; class Filter implements Sanitizeable { /** * Sanitize a value * * @param string $value * @param string $filter * @throws \<API key> if invalid $value type supplied * @throws \<API key> If unknown filter type supplied * @return string */ public static function sanitize($value, $filter = self::FILTER_NONE) { if (!is_scalar($value) && !is_null($value)) { throw new <API key>(sprintf('Sanitizer can only handle scalar values. Received "%s"', gettype($value))); } switch ($filter) { case self::FILTER_NONE; return $value; case self::FILTER_BOOL: return (bool) $value; case self::FILTER_FLOAT: return (float) $value; case self::FILTER_INT: return (int) $value; case self::FILTER_HTML: return self::specialChars($value); case self::FILTER_TAGS: return self::stripTags($value); case self::FILTER_SAFE_TAGS: return self::safeTags($value); case self::FILTER_HTML_CHARS: return self::specialChars($value); default: throw new <API key>('Unknown filter type provided'); } } /** * Filters attribute value * * @param string $value Attribute value * @return string */ public static function filterAttribute($value) { return $value; // Check whether current string has already been encoded $decoded = html_entity_decode($value); // If has been decoded before if ($value != $decoded) { #$value = $decoded; } return $value; } /** * Decodes special HTML characters * * @param string $value * @return string */ public static function charsDecode($value) { return <API key>($value, \ENT_QUOTES); } /** * Convert special characters to HTML entities * * @param string $value * @return string */ public static function specialChars($value) { return htmlspecialchars($value, \ENT_QUOTES, 'UTF-8'); } /** * Removes all unwanted tags * * @param string $string * @return string */ public static function safeTags($string) { return $string; } /** * Determines whether a string has HTML tags * * @param string $target * @param array $exceptions Tags to be ignored * @return boolean */ public static function hasTags($target, array $exceptions = array()) { return self::stripTags($target, $exceptions) !== $target; } /** * Strip the tags, even malformed ones * * @param string $text Target HTML string * @param array $allowed An array of allowed tags * @return string */ public static function stripTags($text, array $allowed = array()) { // Based on [fernando at zauber dot es]'s solution $allowed = array_map('strtolower', $allowed); return <API key>('/<\/?([^>\s]+)[^>]*>/i', function ($matches) use (&$allowed) { return in_array(strtolower($matches[1]), $allowed) ? $matches[0] : ''; }, $text); } /** * Escapes special HTML values * * @param string $value * @return string */ public static function escape($value) { return htmlentities($value, \ENT_QUOTES, 'UTF-8'); } /** * Escapes HTML content * * @param string $content * @return string */ public static function escapeContent($content) { return $content; } }
package test.gov.nih.nci.cacoresdk; import junit.framework.TestCase; import gov.nih.nci.system.applicationservice.ApplicationService; import gov.nih.nci.system.client.<API key>; /** * @author Satish Patel * */ public abstract class SDKTestBase extends TestCase { private ApplicationService appService; private ApplicationService appServiceFromUrl; protected void setUp() throws Exception { super.setUp(); appService = <API key>.<API key>(); } protected void tearDown() throws Exception { appService = null; super.tearDown(); } protected ApplicationService <API key>() { return appService; } protected ApplicationService <API key>() throws Exception { String url = "http://localhost:8080/example"; appServiceFromUrl = <API key>.<API key>(url); return appServiceFromUrl; } protected ApplicationService <API key>() throws Exception { String url = "http://badhost:8080/badcontext"; appServiceFromUrl = <API key>.<API key>(url); return appServiceFromUrl; } public static String getTestCaseName() { return "SDK Base Test Case"; } }
#include "mod_cryptoapi.h" HMODULE mod_cryptoapi::hRsaEng = NULL; bool mod_cryptoapi::loadRsaEnh() { if(!hRsaEng) hRsaEng = LoadLibrary(L"rsaenh"); return (hRsaEng != NULL); } bool mod_cryptoapi::unloadRsaEnh() { if(hRsaEng) FreeLibrary(hRsaEng); return true; } bool mod_cryptoapi::getProviderString(wstring ProviderName, wstring * Provider) { map<wstring, wstring> mesProviders; mesProviders.insert(make_pair(L"MS_DEF_PROV", MS_DEF_PROV)); mesProviders.insert(make_pair(L"MS_ENHANCED_PROV", MS_ENHANCED_PROV)); mesProviders.insert(make_pair(L"MS_STRONG_PROV", MS_STRONG_PROV)); mesProviders.insert(make_pair(L"MS_DEF_RSA_SIG_PROV", MS_DEF_RSA_SIG_PROV)); mesProviders.insert(make_pair(L"<API key>", <API key>)); mesProviders.insert(make_pair(L"MS_DEF_DSS_PROV", MS_DEF_DSS_PROV)); mesProviders.insert(make_pair(L"MS_DEF_DSS_DH_PROV", MS_DEF_DSS_DH_PROV)); mesProviders.insert(make_pair(L"MS_ENH_DSS_DH_PROV", MS_ENH_DSS_DH_PROV)); mesProviders.insert(make_pair(L"<API key>", <API key>)); mesProviders.insert(make_pair(L"MS_SCARD_PROV", MS_SCARD_PROV)); mesProviders.insert(make_pair(L"MS_ENH_RSA_AES_PROV", MS_ENH_RSA_AES_PROV)); mesProviders.insert(make_pair(L"<API key>", <API key>)); map<wstring, wstring>::iterator monIterateur = mesProviders.find(ProviderName); *Provider = (monIterateur != mesProviders.end()) ? monIterateur->second : ProviderName; return true; } bool mod_cryptoapi::<API key>(wstring ProviderTypeName, DWORD * ProviderType) { map<wstring, DWORD> mesTypes; mesTypes.insert(make_pair(L"PROV_RSA_FULL", PROV_RSA_FULL)); mesTypes.insert(make_pair(L"PROV_RSA_SIG", PROV_RSA_SIG)); mesTypes.insert(make_pair(L"PROV_DSS", PROV_DSS)); mesTypes.insert(make_pair(L"PROV_FORTEZZA", PROV_FORTEZZA)); mesTypes.insert(make_pair(L"PROV_MS_EXCHANGE", PROV_MS_EXCHANGE)); mesTypes.insert(make_pair(L"PROV_SSL", PROV_SSL)); mesTypes.insert(make_pair(L"PROV_RSA_SCHANNEL", PROV_RSA_SCHANNEL)); mesTypes.insert(make_pair(L"PROV_DSS_DH", PROV_DSS_DH)); mesTypes.insert(make_pair(L"PROV_EC_ECDSA_SIG", PROV_EC_ECDSA_SIG)); mesTypes.insert(make_pair(L"PROV_EC_ECNRA_SIG", PROV_EC_ECNRA_SIG)); mesTypes.insert(make_pair(L"PROV_EC_ECDSA_FULL",PROV_EC_ECDSA_FULL)); mesTypes.insert(make_pair(L"PROV_EC_ECNRA_FULL",PROV_EC_ECNRA_FULL)); mesTypes.insert(make_pair(L"PROV_DH_SCHANNEL", PROV_DH_SCHANNEL)); mesTypes.insert(make_pair(L"PROV_SPYRUS_LYNKS", PROV_SPYRUS_LYNKS)); mesTypes.insert(make_pair(L"PROV_RNG", PROV_RNG)); mesTypes.insert(make_pair(L"PROV_INTEL_SEC", PROV_INTEL_SEC)); mesTypes.insert(make_pair(L"PROV_REPLACE_OWF", PROV_REPLACE_OWF)); mesTypes.insert(make_pair(L"PROV_RSA_AES", PROV_RSA_AES)); map<wstring, DWORD>::iterator monIterateur = mesTypes.find(ProviderTypeName); if(monIterateur != mesTypes.end()) { *ProviderType = monIterateur->second; return true; } else return false; } bool mod_cryptoapi::getVectorProviders(vector<wstring> * monVectorProviders) { DWORD index = 0; DWORD provType; DWORD tailleRequise; while(CryptEnumProviders(index, NULL, 0, &provType, NULL, &tailleRequise)) { wchar_t * monProvider = new wchar_t[tailleRequise]; if(CryptEnumProviders(index, NULL, 0, &provType, monProvider, &tailleRequise)) { monVectorProviders->push_back(monProvider); } delete[] monProvider; index++; } return (GetLastError() == ERROR_NO_MORE_ITEMS); } bool mod_cryptoapi::getVectorContainers(vector<wstring> * monVectorContainers, bool isMachine, wstring provider, DWORD providerType) { bool reussite = false; HCRYPTPROV hCryptProv = NULL; if(CryptAcquireContext(&hCryptProv, NULL, provider.c_str(), providerType, CRYPT_VERIFYCONTEXT | (isMachine ? <API key> : NULL))) { DWORD tailleRequise = 0; char * containerName = NULL; DWORD CRYPT_first_next = CRYPT_FIRST; bool success = false; success = (CryptGetProvParam(hCryptProv, PP_ENUMCONTAINERS, NULL, &tailleRequise, CRYPT_first_next) != 0); while(success) { containerName = new char[tailleRequise]; if(success = (CryptGetProvParam(hCryptProv, PP_ENUMCONTAINERS, reinterpret_cast<BYTE *>(containerName), &tailleRequise, CRYPT_first_next) != 0)) { wstringstream resultat; resultat << containerName; monVectorContainers->push_back(resultat.str()); } delete[] containerName; CRYPT_first_next = CRYPT_NEXT; } reussite = (GetLastError() == ERROR_NO_MORE_ITEMS); CryptReleaseContext(hCryptProv, 0); } return reussite; } bool mod_cryptoapi::getPrivateKey(HCRYPTKEY maCle, PBYTE * monExport, DWORD * tailleExport, DWORD dwBlobType) { bool reussite = false; if(CryptExportKey(maCle, NULL, dwBlobType, NULL, NULL, tailleExport)) { *monExport = new BYTE[*tailleExport]; if(!(reussite = (CryptExportKey(maCle, NULL, dwBlobType, NULL, *monExport, tailleExport) != 0))) delete[] monExport; } return reussite; }
'use strict'; var serviceBase = 'http://localhost:81/yii/BongoERP/web/' var app = angular.module('app', ['ngRoute','SiteControllers','AppServices']); app.config(['$routeProvider',function($routeProvider){ $routeProvider. when("/home",{controller:"SiteController",templateUrl:"pages/site/home.html"}). when("/",{controller:"SiteController",templateUrl:"pages/site/home.html"}). when("/form",{controller:"SiteController",templateUrl:"pages/template/partials/form.html"}). when("/page",{controller:"SiteController",templateUrl:"pages/template/partials/blankpage.html"}). when("/input_form",{controller:"SiteController",templateUrl:"pages/template/partials/input_form.html"}). when("/about",{controller:"SiteController",templateUrl:"pages/site/about.html"}). when("/books",{controller:"SiteController",templateUrl:"pages/users/index.html"}). when("/book/create",{controller:"SiteController",templateUrl:"pages/users/create.html"}). when("/companySetup",{controller:"SiteController",templateUrl:"pages/companySetup/partials/company-setup.html"}). otherwise({RedirectTo:"pages/site/home.html"}); }]);
#include "cmdsys.h" #include <sl/sl_flat_set.h> #include <sl/sl_hash_table.h> #include <sl/sl_string.h> #include <snlsys/list.h> #include <snlsys/math.h> #include <snlsys/mem_allocator.h> #include <snlsys/ref_count.h> #include <snlsys/snlsys.h> #include <argtable2.h> #include <limits.h> #include <stdarg.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define IS_END_REACHED(desc) \ (memcmp(&desc, &CMDARG_END, sizeof(struct cmdarg_desc)) == 0) #define ERRBUF_LEN 1024 #define SCRATCH_LEN 1024 struct errbuf { char buffer[ERRBUF_LEN]; size_t buffer_id; }; struct cmdsys { char scratch[SCRATCH_LEN]; FILE* stream; struct mem_allocator* allocator; struct sl_hash_table* htbl; /* hash table [cmd name, struct cmd*] */ struct sl_flat_set* name_set; /* set of const char*. Used by completion.*/ struct errbuf errbuf; struct ref ref; }; struct cmd { struct list_node node; size_t argc; void(*func)(struct cmdsys*, size_t, const struct cmdarg**, void* data); void* data; void (*completion) (struct cmdsys*, const char*, size_t, size_t*, const char**[]); struct sl_string* description; union cmdarg_domain* arg_domain; struct cmdarg** argv; void** arg_table; }; static void errbuf_print(struct errbuf* buf, const char* fmt, ...) FORMAT_PRINTF(2, 3); void errbuf_print(struct errbuf* buf, const char* fmt, ...) { ASSERT(buf); va_list vargs_list; const size_t buf_size = sizeof(buf->buffer); const size_t buf_size_remaining = buf_size - buf->buffer_id - 1; int i = 0; if(buf->buffer_id >= buf_size - 1) return; va_start(vargs_list, fmt); i = vsnprintf (buf->buffer + buf->buffer_id, buf_size_remaining, fmt, vargs_list); ASSERT(i > 0); if((size_t)i >= buf_size) { buf->buffer_id = buf_size; buf->buffer[buf_size - 1] = '\0'; } else { buf->buffer_id += (size_t)i; } va_end(vargs_list); } static FINLINE void errbuf_flush(struct errbuf* buf) { ASSERT(buf); buf->buffer_id = 0; buf->buffer[0] = '\0'; } static enum cmdsys_error sl_to_cmdsys_error(enum sl_error sl_err) { enum cmdsys_error err = CMDSYS_NO_ERROR; switch(sl_err) { case SL_INVALID_ARGUMENT: err = <API key>; break; case SL_MEMORY_ERROR: err = CMDSYS_MEMORY_ERROR; break; case SL_NO_ERROR: err = CMDSYS_NO_ERROR; break; default: err = <API key>; break; } return err; } static size_t hash_str(const void* key) { const char* str = *(const char**)key; return sl_hash(str, strlen(str)); } static bool eqstr(const void* key0, const void* key1) { const char* str0 = *(const char**)key0; const char* str1 = *(const char**)key1; return strcmp(str0, str1) == 0; } static int cmpstr(const void* a, const void* b) { const char* str0 = *(const char**)a; const char* str1 = *(const char**)b; return strcmp(str0, str1); } static enum cmdsys_error <API key>(struct cmd* cmd, const struct cmdarg_desc argv_desc[]) { size_t i = 0; enum cmdsys_error err = CMDSYS_NO_ERROR; ASSERT(cmd); if(argv_desc) { void* arg = NULL; #define ARG(suffix, a) \ CONCAT(arg_, suffix) \ ((a).short_options, (a).long_options, (a).data_type, (a).glossary) #define LIT(suffix, a) \ CONCAT(arg_, suffix) \ ((a).short_options, (a).long_options, (a).glossary) #define ARGN(suffix, a) \ CONCAT(CONCAT(arg_, suffix), n) \ ((a).short_options, (a).long_options, (a).data_type, \ (int)(a).min_count, (int)(a).max_count, (a).glossary) #define LITN(suffix, a) \ CONCAT(CONCAT(arg_, suffix), n) \ ((a).short_options, (a).long_options, (int)(a).min_count, \ (int)(a).max_count, (a).glossary) for(i = 0; !IS_END_REACHED(argv_desc[i]); ++i) { if(argv_desc[i].min_count == 0 && argv_desc[i].max_count == 1) { switch(argv_desc[i].type) { case CMDARG_INT: arg = ARG(int0, argv_desc[i]); break; case CMDARG_FILE: arg = ARG(file0, argv_desc[i]); break; case CMDARG_FLOAT: arg = ARG(dbl0, argv_desc[i]); break; case CMDARG_STRING: arg = ARG(str0, argv_desc[i]); break; case CMDARG_LITERAL: arg = LIT(lit0, argv_desc[i]); break; default: ASSERT(0); break; } } else if(argv_desc[i].max_count == 1) { switch(argv_desc[i].type) { case CMDARG_INT: arg = ARG(int1, argv_desc[i]); break; case CMDARG_FILE: arg = ARG(file1, argv_desc[i]); break; case CMDARG_FLOAT: arg = ARG(dbl1, argv_desc[i]); break; case CMDARG_STRING: arg = ARG(str1, argv_desc[i]); break; case CMDARG_LITERAL: arg = LIT(lit1, argv_desc[i]); break; default: ASSERT(0); break; } } else { switch(argv_desc[i].type) { case CMDARG_INT: arg = ARGN(int, argv_desc[i]); break; case CMDARG_FILE: arg = ARGN(file, argv_desc[i]); break; case CMDARG_FLOAT: arg = ARGN(dbl, argv_desc[i]); break; case CMDARG_STRING: arg = ARGN(str, argv_desc[i]); break; case CMDARG_LITERAL: arg = LITN(lit, argv_desc[i]); break; default: ASSERT(0); break; } } cmd->arg_table[i] = arg; cmd->arg_domain[i + 1] = argv_desc[i].domain; /* +1 <=> command name. */ } } cmd->arg_table[i] = arg_end(16); if(arg_nullcheck(cmd->arg_table)) { err = CMDSYS_MEMORY_ERROR; goto error; } #undef ARG #undef LIT #undef ARGN #undef LITN exit: return err; error: goto exit; } static FINLINE void set_optvalue_flag(struct cmd* cmd, const bool val) { size_t argv_id = 0; size_t tbl_id = 0; ASSERT(cmd); #define SET_OPTVAL(arg, val) \ do { \ if(val) \ (arg)->hdr.flag |= ARG_HASOPTVALUE; \ else \ (arg)->hdr.flag &= ~ARG_HASOPTVALUE; \ } while(0) for(argv_id = 1, tbl_id = 0; argv_id < cmd->argc; ++argv_id, ++tbl_id) { switch(cmd->argv[argv_id]->type) { case CMDARG_INT: SET_OPTVAL((struct arg_int*)cmd->arg_table[tbl_id], val); break; case CMDARG_FILE: SET_OPTVAL((struct arg_file*)cmd->arg_table[tbl_id], val); break; case CMDARG_FLOAT: SET_OPTVAL((struct arg_dbl*)cmd->arg_table[tbl_id], val); break; case CMDARG_STRING: SET_OPTVAL((struct arg_str*)cmd->arg_table[tbl_id], val); break; case CMDARG_LITERAL: SET_OPTVAL((struct arg_lit*)cmd->arg_table[tbl_id], val); break; default: ASSERT(0); /* Unreachable code */ break; } } #undef SET_OPTVAL } static int defined_args_count(struct cmd* cmd) { int count = 0; size_t argv_id = 0; size_t tbl_id = 0; ASSERT(cmd); for(argv_id = 1, tbl_id = 0; argv_id < cmd->argc; ++argv_id, ++tbl_id) { switch(cmd->argv[argv_id]->type) { case CMDARG_INT: count += ((struct arg_int*)cmd->arg_table[tbl_id])->count; break; case CMDARG_FILE: count += ((struct arg_file*)cmd->arg_table[tbl_id])->count; break; case CMDARG_FLOAT: count += ((struct arg_dbl*)cmd->arg_table[tbl_id])->count; break; case CMDARG_STRING: count += ((struct arg_str*)cmd->arg_table[tbl_id])->count; break; case CMDARG_LITERAL: count += ((struct arg_lit*)cmd->arg_table[tbl_id])->count; break; default: ASSERT(0); break; } } return count; } static enum cmdsys_error setup_cmd_arg(struct cmdsys* sys, struct cmd* cmd, const char* name) { size_t arg_id = 0; enum cmdsys_error err = CMDSYS_NO_ERROR; ASSERT(cmd && cmd->argc && cmd->argv[0]->type == CMDARG_STRING); cmd->argv[0]->value_list[0].is_defined = true; cmd->argv[0]->value_list[0].data.string = name; for(arg_id = 1; arg_id < cmd->argc; ++arg_id) { const char** value_list = NULL; const char* str = NULL; const size_t arg_tbl_id = arg_id - 1; /* -1 <=> arg name. */ int val_id = 0; bool isdef = true; for(val_id=0; isdef && (size_t)val_id<cmd->argv[arg_id]->count; ++val_id) { switch(cmd->argv[arg_id]->type) { case CMDARG_STRING: isdef = val_id < ((struct arg_str*)cmd->arg_table[arg_tbl_id])->count; if(isdef) { str = ((struct arg_str*)(cmd->arg_table[arg_tbl_id]))->sval[val_id]; /* Check the string domain. */ value_list = cmd->arg_domain[arg_id].string.value_list; if(value_list == NULL) { cmd->argv[arg_id]->value_list[val_id].data.string = str; } else { size_t i = 0; for(i = 0; value_list[i] != NULL; ++i) { if(strcmp(str, value_list[i]) == 0) break; } if(value_list[i] != NULL) { cmd->argv[arg_id]->value_list[val_id].data.string = str; } else { errbuf_print (&sys->errbuf, "%s: unexpected option value `%s'\n", name, str); err = <API key>; goto error; } } } break; case CMDARG_FILE: isdef = val_id< ((struct arg_file*)cmd->arg_table[arg_tbl_id])->count; if(isdef) { cmd->argv[arg_id]->value_list[val_id].data.string = ((struct arg_file*)(cmd->arg_table[arg_tbl_id]))->filename[val_id]; } break; case CMDARG_INT: isdef = val_id < ((struct arg_int*)cmd->arg_table[arg_tbl_id])->count; if(isdef) { cmd->argv[arg_id]->value_list[val_id].data.integer = MAX(MIN( ((struct arg_int*)(cmd->arg_table[arg_tbl_id]))->ival[val_id], cmd->arg_domain[arg_id].integer.max), cmd->arg_domain[arg_id].integer.min); } break; case CMDARG_FLOAT: isdef = val_id < ((struct arg_dbl*)cmd->arg_table[arg_tbl_id])->count; if(isdef) { cmd->argv[arg_id]->value_list[val_id].data.real = MAX(MIN((float) ((struct arg_dbl*)(cmd->arg_table[arg_tbl_id]))->dval[val_id], cmd->arg_domain[arg_id].real.max), cmd->arg_domain[arg_id].real.min); } break; case CMDARG_LITERAL: isdef = val_id < ((struct arg_lit*)cmd->arg_table[arg_tbl_id])->count; break; default: ASSERT(0); break; } cmd->argv[arg_id]->value_list[val_id].is_defined = isdef; } } exit: return err; error: goto exit; } static enum cmdsys_error register_command (struct cmdsys* sys, struct cmd* cmd, const char* name) { struct list_node* list = NULL; char* cmd_name = NULL; enum cmdsys_error err = CMDSYS_NO_ERROR; enum sl_error sl_err = SL_NO_ERROR; bool is_inserted_in_htbl = false; bool is_inserted_in_fset = false; ASSERT(sys && cmd && name); SL(hash_table_find(sys->htbl, &name, (void**)&list)); /* Register the command against the command system if it does not exist. */ if(list == NULL) { cmd_name = MEM_CALLOC(sys->allocator, strlen(name) + 1, sizeof(char)); if(NULL == cmd_name) { err = CMDSYS_MEMORY_ERROR; goto error; } strcpy(cmd_name, name); sl_err = <API key> (sys->htbl, &cmd_name, (struct list_node[]){{NULL, NULL}}); if(SL_NO_ERROR != sl_err) { err = sl_to_cmdsys_error(sl_err); goto error; } is_inserted_in_htbl = true; SL(hash_table_find(sys->htbl, &cmd_name, (void**)&list)); ASSERT(list != NULL); list_init(list); sl_err = sl_flat_set_insert(sys->name_set, &cmd_name, NULL); if(SL_NO_ERROR != sl_err) { err = sl_to_cmdsys_error(sl_err); goto error; } is_inserted_in_fset = true; } list_add(list, &cmd->node); exit: return err; error: if(cmd_name) { size_t i = 0; if(is_inserted_in_htbl) { SL(hash_table_erase(sys->htbl, &cmd_name, &i)); ASSERT(1 == i); } if(is_inserted_in_fset) { SL(flat_set_erase(sys->name_set, &cmd_name, NULL)); } MEM_FREE(sys->allocator, cmd_name); } goto exit; } static void del_all_commands(struct cmdsys* sys) { struct sl_hash_table_it it; bool b = false; ASSERT(sys && sys->htbl); SL(hash_table_begin(sys->htbl, &it, &b)); while(!b) { struct list_node* list = (struct list_node*)it.pair.data; struct list_node* pos = NULL; struct list_node* tmp = NULL; size_t i = 0; ASSERT(is_list_empty(list) == false); LIST_FOR_EACH_SAFE(pos, tmp, list) { struct cmd* cmd = CONTAINER_OF(pos, struct cmd, node); list_del(pos); if(cmd->description) SL(free_string(cmd->description)); for(i = 0; i < cmd->argc; ++i) { MEM_FREE(sys->allocator, cmd->argv[i]); } MEM_FREE(sys->allocator, cmd->argv); MEM_FREE(sys->allocator, cmd->arg_domain); arg_freetable(cmd->arg_table, cmd->argc + 1); /* +1 <=> arg_end. */ MEM_FREE(sys->allocator, cmd->arg_table); MEM_FREE(sys->allocator, cmd); } MEM_FREE(sys->allocator, (*(char**)it.pair.key)); SL(hash_table_it_next(&it, &b)); } SL(hash_table_clear(sys->htbl)); } static void release_cmdsys(struct ref* ref) { struct cmdsys* sys = NULL; ASSERT(ref != NULL); sys = CONTAINER_OF(ref, struct cmdsys, ref); if(sys->htbl) { del_all_commands(sys); SL(free_hash_table(sys->htbl)); } if(sys->name_set) SL(free_flat_set(sys->name_set)); if(sys->stream) fclose(sys->stream); MEM_FREE(sys->allocator, sys); } enum cmdsys_error cmdsys_create(struct mem_allocator* allocator, struct cmdsys** out_sys) { struct mem_allocator* alloc = allocator ? allocator : &<API key>; struct cmdsys* sys = NULL; enum cmdsys_error err = CMDSYS_NO_ERROR; enum sl_error sl_err = SL_NO_ERROR; if(!out_sys) { err = <API key>; goto error; } sys = MEM_CALLOC(alloc, 1, sizeof(struct cmdsys)); if(!sys) { err = CMDSYS_MEMORY_ERROR; goto error; } sys->allocator = alloc; ref_init(&sys->ref); sl_err = <API key> (sizeof(const char*), ALIGNOF(const char*), sizeof(struct list_node), ALIGNOF(struct list_node), hash_str, eqstr, sys->allocator, &sys->htbl); if(SL_NO_ERROR != sl_err) { err = sl_to_cmdsys_error(sl_err); goto error; } sl_err = sl_create_flat_set (sizeof(const char*), ALIGNOF(const char*), cmpstr, sys->allocator, &sys->name_set); if(SL_NO_ERROR != sl_err) { err = sl_to_cmdsys_error(sl_err); goto error; } sys->stream = tmpfile(); if(!sys->stream) { err = CMDSYS_IO_ERROR; goto error; } exit: if(out_sys) *out_sys = sys; return err; error: if(sys) { CMDSYS(ref_put(sys)); sys = NULL; } goto exit; } enum cmdsys_error cmdsys_ref_get(struct cmdsys* sys) { if(!sys) return <API key>; ref_get(&sys->ref); return CMDSYS_NO_ERROR; } enum cmdsys_error cmdsys_ref_put(struct cmdsys* sys) { if(!sys) return <API key>; ref_put(&sys->ref, release_cmdsys); return CMDSYS_NO_ERROR; } enum cmdsys_error cmdsys_add_command (struct cmdsys* sys, const char* name, void (*func)(struct cmdsys*, size_t, const struct cmdarg**, void*), void* data, void (*completion) (struct cmdsys*, const char*, size_t, size_t*, const char**[]), const struct cmdarg_desc argv_desc[], const char* description) { struct cmd* cmd = NULL; size_t argc = 0; size_t buffer_len = 0; size_t arg_id = 0; size_t desc_id = 0; size_t i = 0; enum cmdsys_error err = CMDSYS_NO_ERROR; enum sl_error sl_err = SL_NO_ERROR; if(!sys || !name || !func) { err = <API key>; goto error; } cmd = MEM_CALLOC(sys->allocator, 1, sizeof(struct cmd)); if(NULL == cmd) { err = CMDSYS_MEMORY_ERROR; goto error; } list_init(&cmd->node); cmd->func = func; cmd->data = data; /* Check arg desc list */ if(argv_desc != NULL) { for(argc = 0; !IS_END_REACHED(argv_desc[argc]); ++argc) { if(argv_desc[argc].min_count > argv_desc[argc].max_count || argv_desc[argc].max_count == 0 || argv_desc[argc].type == CMDARG_TYPES_COUNT) { err = <API key>; goto error; } buffer_len += (size_t)argv_desc[argc].max_count; } } ++argc; /* +1 <=> command name. */ /* Create the command arg table, arg domain, and argv container. */ cmd->arg_table = MEM_CALLOC (sys->allocator, argc + 1 /* +1 <=> arg_end */, sizeof(void*)); if(NULL == cmd->arg_table) { err = CMDSYS_MEMORY_ERROR; goto error; } cmd->arg_domain = MEM_CALLOC (sys->allocator, argc, sizeof(union cmdarg_domain)); if(NULL == cmd->arg_domain) { err = CMDSYS_MEMORY_ERROR; goto error; } cmd->argv = MEM_CALLOC(sys->allocator, argc, sizeof(struct cmdarg*)); if(NULL == cmd->argv) { err = CMDSYS_MEMORY_ERROR; goto error; } /* Setup the arg domain and table. */ err = <API key>(cmd, argv_desc); if(err != CMDSYS_NO_ERROR) goto error; /* Setup the command name arg. */ cmd->argv[0] = MEM_CALLOC (sys->allocator, 1, sizeof(struct cmdarg) + sizeof(struct cmdarg_value)); if(NULL == cmd->argv[0]) { err = CMDSYS_MEMORY_ERROR; goto error; } cmd->argv[0]->type = CMDARG_STRING; cmd->argv[0]->count = 1; /* Setup the remaining args. */ for(arg_id = 1, desc_id = 0; arg_id < argc; ++arg_id, ++desc_id) { cmd->argv[arg_id] = MEM_CALLOC (sys->allocator, 1, sizeof(struct cmdarg) + (size_t)argv_desc[desc_id].max_count * sizeof(struct cmdarg_value)); if(NULL == cmd->argv[arg_id]) { err = CMDSYS_MEMORY_ERROR; goto error; } cmd->argv[arg_id]->type = argv_desc[desc_id].type; cmd->argv[arg_id]->count = (size_t)argv_desc[desc_id].max_count; } cmd->argc = argc; /* Setup the command description. */ if(NULL == description) { cmd->description = NULL; } else { sl_err = sl_create_string(description, sys->allocator, &cmd->description); if(sl_err != SL_NO_ERROR) { err = sl_to_cmdsys_error(sl_err); goto error; } } cmd->completion = completion; /* Register the command against the command system. */ err = register_command(sys, cmd, name); if(err != CMDSYS_NO_ERROR) goto error; exit: return err; error: /* The command registration is the last action, i.e. the command is * registered only if no error occurs. It is thus useless to handle command * registration in the error management. */ if(cmd) { if(cmd->description) SL(free_string(cmd->description)); if(cmd->arg_table) { for(i = 0; i < argc + 1 /* +1 <=> arg_end */ ; ++i) { if(cmd->arg_table[i]) free(cmd->arg_table[i]); } MEM_FREE(sys->allocator, cmd->arg_table); } if(cmd->argv) { for(i = 0; i < argc; ++i) { if(cmd->argv[i]) free(cmd->argv[i]); } MEM_FREE(sys->allocator, cmd->argv); } MEM_FREE(sys->allocator, cmd); cmd = NULL; } goto exit; } enum cmdsys_error cmdsys_del_command(struct cmdsys* sys, const char* name) { struct sl_pair pair; struct list_node* list = NULL; struct list_node* pos = NULL; struct list_node* tmp = NULL; char* cmd_name = NULL; size_t i = 0; enum cmdsys_error err = CMDSYS_NO_ERROR; if(!sys || !name) { err = <API key>; goto error; } /* Unregister the command. */ SL(<API key>(sys->htbl, &name, &pair)); if(!SL_IS_PAIR_VALID(&pair)) { err = <API key>; goto error; } /* Free the command syntaxes. */ list = (struct list_node*)pair.data; LIST_FOR_EACH_SAFE(pos, tmp, list) { struct cmd* cmd = CONTAINER_OF(pos, struct cmd, node); list_del(pos); if(cmd->description) SL(free_string(cmd->description)); for(i = 0; i < cmd->argc; ++i) { MEM_FREE(sys->allocator, cmd->argv[i]); } MEM_FREE(sys->allocator, cmd->argv); MEM_FREE(sys->allocator, cmd->arg_domain); arg_freetable(cmd->arg_table, cmd->argc + 1); /* +1 <=> arg_end. */ MEM_FREE(sys->allocator, cmd->arg_table); MEM_FREE(sys->allocator, cmd); } /* Free the command name. */ cmd_name = *(char**)pair.key; SL(flat_set_erase(sys->name_set, &cmd_name, NULL)); SL(hash_table_erase(sys->htbl, &cmd_name, &i)); ASSERT(1 == i); MEM_FREE(sys->allocator, cmd_name); exit: return err; error: goto exit; } enum cmdsys_error cmdsys_has_command(struct cmdsys* sys, const char* name, bool* has_command) { void* ptr = NULL; if(!sys || !name || !has_command) return <API key>; SL(hash_table_find(sys->htbl, &name, &ptr)); *has_command = (ptr != NULL); return CMDSYS_NO_ERROR; } enum cmdsys_error <API key> (struct cmdsys* sys, const char* command, const char* inverse) { (void)inverse; #define MAX_ARG_COUNT 128 char* argv[MAX_ARG_COUNT]; struct list_node* command_list = NULL; struct list_node* node = NULL; struct cmd* valid_cmd = NULL; char* name = NULL; char* ptr = NULL; int argc = 0; enum cmdsys_error err = CMDSYS_NO_ERROR; int min_nerror = 0; if(!sys || !command) { err = <API key>; goto error; } if(strlen(command) + 1 > sizeof(sys->scratch) / sizeof(char)) { err = CMDSYS_MEMORY_ERROR; goto error; } /* Copy the command into the mutable scratch buffer of the command system. */ strcpy(sys->scratch, command); /* Retrieve the first token <=> command name. */ name = strtok(sys->scratch, " \t"); SL(hash_table_find(sys->htbl, &name, (void**)&command_list)); if(!command_list) { errbuf_print(&sys->errbuf, "%s: command not found\n", name); err = <API key>; goto error; } argv[0] = name; for(argc = 1; NULL != (ptr = strtok(NULL, " \t")); ++argc) { if(argc >= MAX_ARG_COUNT) { err = CMDSYS_MEMORY_ERROR; goto error; } argv[argc] = ptr; } min_nerror = INT_MAX; LIST_FOR_EACH(node, command_list) { struct cmd* cmd = CONTAINER_OF(node, struct cmd, node); int nerror = 0; ASSERT(cmd->argc > 0); nerror = arg_parse(argc, argv, cmd->arg_table); if(nerror <= min_nerror) { if(nerror < min_nerror) { min_nerror = nerror; rewind(sys->stream); } fprintf(sys->stream, "\n%s", name); arg_print_syntaxv(sys->stream, cmd->arg_table, "\n"); arg_print_errors (sys->stream, (struct arg_end*)cmd->arg_table[cmd->argc - 1], name); } if(nerror == 0) { valid_cmd = cmd; break; } } if(min_nerror != 0) { long fpos = 0; size_t size =0; size_t nb = 0; (void)nb; fpos = ftell(sys->stream); size = MIN((size_t)fpos, sizeof(sys->scratch)/sizeof(char) - 1); rewind(sys->stream); nb = fread(sys->scratch, size, 1, sys->stream); ASSERT(nb == 1); sys->scratch[size] = '\0'; errbuf_print(&sys->errbuf, "%s", sys->scratch); err = <API key>; goto error; } /* Setup the args and invoke the commands. */ err = setup_cmd_arg(sys, valid_cmd, name); if(err != CMDSYS_NO_ERROR) goto error; valid_cmd->func (sys, valid_cmd->argc, (const struct cmdarg**)valid_cmd->argv, valid_cmd->data); #undef MAX_ARG_COUNT exit: return err; error: goto exit; } enum cmdsys_error cmdsys_man_command (struct cmdsys* sys, const char* name, size_t* len, size_t max_buf_len, char* buffer) { struct list_node* cmd_list = NULL; struct list_node* node = NULL; enum cmdsys_error err = CMDSYS_NO_ERROR; long fpos = 0; if(!sys || !name || (max_buf_len && !buffer)) { err = <API key>; goto error; } SL(hash_table_find(sys->htbl, &name, (void**)&cmd_list)); if(!cmd_list) { errbuf_print(&sys->errbuf, "%s: command not found\n", name); err = <API key>; goto error; } ASSERT(is_list_empty(cmd_list) == false); rewind(sys->stream); LIST_FOR_EACH(node, cmd_list) { struct cmd* cmd = CONTAINER_OF(node, struct cmd, node); if(node != list_head(cmd_list)) fprintf(sys->stream, "\n"); fprintf(sys->stream, "%s", name); arg_print_syntaxv(sys->stream, cmd->arg_table, "\n"); if(cmd->description) { const char* cstr = NULL; SL(string_get(cmd->description, &cstr)); fprintf(sys->stream, "%s\n", cstr); } arg_print_glossary(sys->stream, cmd->arg_table, NULL); fpos = ftell(sys->stream); ASSERT(fpos > 0); } if(len) *len = (size_t)fpos / sizeof(char); if(buffer && max_buf_len) { const size_t size = MIN((max_buf_len - 1) * sizeof(char), (size_t)fpos); size_t nb = 0; (void)nb; fflush(sys->stream); rewind(sys->stream); nb = fread(buffer, size, 1, sys->stream); ASSERT(nb == 1); buffer[size/sizeof(char)] = '\0'; } exit: return err; error: goto exit; } enum cmdsys_error <API key> (struct cmdsys* sys, const char* cmd_name, const char* arg_str, size_t arg_str_len, size_t hint_argc, char* hint_argv[], size_t* completion_list_len, const char** completion_list[]) { struct list_node* cmd_list = NULL; enum cmdsys_error err = CMDSYS_NO_ERROR; if(!sys || !cmd_name || (arg_str_len && !arg_str) || (hint_argc && !hint_argv) || !completion_list_len || !completion_list) { err = <API key>; goto error; } /* Default completion list value. */ *completion_list_len = 0; *completion_list = NULL; SL(hash_table_find(sys->htbl, &cmd_name, (void**)&cmd_list)); if(cmd_list != NULL) { struct cmd* cmd = NULL; ASSERT(is_list_empty(cmd_list) == false); /* No multi syntax. */ if(list_head(cmd_list) == list_tail(cmd_list)) { cmd = CONTAINER_OF(list_head(cmd_list), struct cmd, node); if(cmd->completion) { cmd->completion (sys, arg_str, arg_str_len, completion_list_len, completion_list); } /* Multi syntax. */ } else { struct cmd* valid_cmd = NULL; struct list_node* node = NULL; int nb_valid_cmd = 0; int min_nerror = INT_MAX; int max_ndefargs = INT_MIN; LIST_FOR_EACH(node, cmd_list) { int nerror = 0; int ndefargs = 0; cmd = CONTAINER_OF(node, struct cmd, node); set_optvalue_flag(cmd, true); nerror = arg_parse((int)hint_argc, hint_argv, cmd->arg_table); ndefargs = defined_args_count(cmd); /* Define as the completion function the one defined by the command * syntax which match the best the hint arguments. If the minimal * number of parsing error is obtained by several syntaxes, we select * the syntax which have the maximum of its argument defined by the * hint command. */ if(nerror < min_nerror || (nerror == min_nerror && ndefargs > max_ndefargs)) { valid_cmd = cmd; nb_valid_cmd = 0; } min_nerror = MIN(nerror, min_nerror); max_ndefargs = MAX(ndefargs, max_ndefargs); nb_valid_cmd += ((ndefargs == max_ndefargs) & (nerror == min_nerror)); set_optvalue_flag(cmd, false); } /* Perform the completion only if an unique syntax match the previous * completion heuristic and and if its completion process is defined. */ if(nb_valid_cmd == 1 && valid_cmd->completion) { valid_cmd->completion (sys, arg_str, arg_str_len, completion_list_len, completion_list); } } } if(*completion_list_len == 0) *completion_list = NULL; exit: return err; error: if(completion_list_len) *completion_list_len = 0; if(completion_list) *completion_list = NULL; goto exit; } enum cmdsys_error <API key> (struct cmdsys* sys, const char* cmd_name, size_t cmd_name_len, size_t* completion_list_len, const char** completion_list[]) { const char** name_list = NULL; size_t len = 0; enum cmdsys_error err = CMDSYS_NO_ERROR; if(!sys || (cmd_name_len && !cmd_name) || !completion_list_len || !completion_list) { err = <API key>; goto error; } SL(flat_set_buffer(sys->name_set, &len, NULL, NULL, (void**)&name_list)); if(0 == cmd_name_len) { *completion_list_len = len; *completion_list = name_list; } else { #define CHARBUF_SIZE 32 char buf[CHARBUF_SIZE]; const char* ptr = buf; size_t begin = 0; size_t end = 0; if(cmd_name_len > CHARBUF_SIZE - 1) { err = CMDSYS_MEMORY_ERROR; goto error; } strncpy(buf, cmd_name, cmd_name_len); buf[cmd_name_len] = '\0'; SL(<API key>(sys->name_set, &ptr, &begin)); buf[cmd_name_len] = 127; buf[cmd_name_len + 1] = '\0'; SL(<API key>(sys->name_set, &ptr, &end)); *completion_list = name_list + begin; *completion_list_len = (size_t)((name_list + end) - (*completion_list)); if(0 == *completion_list_len) *completion_list = NULL; #undef CHARBUF_SIZE } exit: return err; error: goto exit; } enum cmdsys_error <API key>(const struct cmdsys* sys, const char** error) { if(!sys || !error) return <API key>; *error = sys->errbuf.buffer_id == 0 ? NULL : sys->errbuf.buffer; return CMDSYS_NO_ERROR; } enum cmdsys_error cmdsys_flush_error(struct cmdsys* sys) { if(!sys) return <API key>; sys->errbuf.buffer_id = 0; sys->errbuf.buffer[0] = '\0'; return CMDSYS_NO_ERROR; }
#include "main.h" #include "Statistics.h" #include "Calculus.h" #include "Arithmetic.h" #include "eigenvectors.h" #include <algorithm> #include <iostream> #include "header.h" void Dimensions::help() { pprintf("-dimensions prints the size of the current image.\n\n" "Usage: ImageStack -load a.tga -dimensions\n"); } void Dimensions::parse(vector<string> args) { assert(args.size() == 0, "-dimensions takes no arguments\n"); printf("Width x Height x Frames x Channels: %d x %d x %d x %d\n", stack(0).width, stack(0).height, stack(0).frames, stack(0).channels); } Stats::Stats(Window im) : im_(im) { sum_ = mean_ = variance_ = skew_ = kurtosis_ = 0; channels = im.channels; min_ = max_ = im.data[0]; for (int c = 0; c < im.channels; c++) { means.push_back(0); sums.push_back(0); variances.push_back(0); kurtoses.push_back(0); skews.push_back(0); mins.push_back(im.data[c]); maxs.push_back(im.data[c]); spatialvariances.push_back(0); spatialvariances.push_back(0); barycenters.push_back(0); barycenters.push_back(0); for (int c2 = 0; c2 < im.channels; c2++) { covarianceMatrix.push_back(0); } } basicStatsComputed = false; momentsComputed = false; } void Stats::computeBasicStats() { vector<int> counts(im_.channels, 0); nans_ = posinfs_ = neginfs_ = 0; int count = 0; for (int t = 0; t < im_.frames; t++) { for (int y = 0; y < im_.height; y++) { for (int x = 0; x < im_.width; x++) { for (int c = 0; c < im_.channels; c++) { float val = im_(x, y, t)[c]; if (!isfinite(val)) { if (isnan(val)) { nans_++; } else if (val > 0) { posinfs_++; } else { neginfs_++; } continue; }; counts[c]++; count++; sum_ += val; sums[c] += val; // printf("%.5lf |",val); if (val < min_) { min_ = val; } if (val < mins[c]) { mins[c] = val; } if (val > max_) { max_ = val; } if (val > maxs[c]) { maxs[c] = val; } } } } } mean_ = sum_ / count; for (int c = 0; c < im_.channels; c++) { means[c] = sums[c] / counts[c]; } basicStatsComputed = true; } void Stats::computeMoments() { // figure out variance, skew, and kurtosis vector<int> counts(im_.channels, 0); int count = 0; vector<int> covarianceCounts(channels * channels, 0); for (int t = 0; t < im_.frames; t++) { for (int y = 0; y < im_.height; y++) { for (int x = 0; x < im_.width; x++) { for (int c = 0; c < im_.channels; c++) { float val = im_(x, y, t)[c]; if (!isfinite(val)) { continue; } counts[c]++; count++; float diff = (float)(val - means[c]); for (int c2 = 0; c2 < im_.channels; c2++) { float val2 = im_(x, y, t)[c2]; if (!isfinite(val2)) { continue; } float diff2 = (float)(val2 - means[c2]); covarianceMatrix[c *channels + c2] += diff * diff2; covarianceCounts[c * channels + c2]++; } float power = diff * diff; barycenters[c*2] += x*val; barycenters[c*2+1] += y*val; spatialvariances[c*2] += x*x*val; spatialvariances[c*2+1] += y*y*val; variances[c] += power; variance_ += power; power *= diff; skews[c] += power; skew_ += power; power *= diff; kurtosis_ += power * diff; kurtoses[c] += power * diff; } } } } variance_ /= (count - 1); skew_ /= (count - 1) * variance_ * ::sqrt(variance_); kurtosis_ /= (count - 1) * variance_ * variance_; for (int c = 0; c < im_.channels; c++) { for (int c2 = 0; c2 < im_.channels; c2++) { covarianceMatrix[c *channels + c2] /= covarianceCounts[c * channels + c2] - 1; } variances[c] /= (counts[c] - 1); skews[c] /= (counts[c] - 1) * variances[c] * ::sqrt(variances[c]); kurtoses[c] /= (counts[c] - 1) * variances[c] * variances[c]; } for (int c = 0; c < im_.channels; c++) { barycenters[c*2] /= sums[c]; barycenters[c*2+1] /= sums[c]; spatialvariances[c*2] /= sums[c]; spatialvariances[c*2] -= barycenters[c*2] * barycenters[c*2]; spatialvariances[c*2+1] /= sums[c]; spatialvariances[c*2+1] -= barycenters[c*2+1] * barycenters[c*2+1]; } momentsComputed = true; } void Statistics::help() { pprintf("-statistics provides per channel statistical information about the current image.\n\n" "Usage: ImageStack -load a.tga -statistics\n"); } void Statistics::parse(vector<string> args) { assert(args.size() == 0, "-statistics takes no arguments"); apply(stack(0)); } void Statistics::apply(Window im) { Stats stats(im); printf("Frames x Width x Height x Channels: %i %i %i %i\n", im.frames, im.width, im.height, im.channels); printf("Minima: \t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.minimum(i)); } printf("\n"); printf("Maxima: \t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.maximum(i)); } printf("\n"); printf("Sums: \t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.sum(i)); } printf("\n"); printf("Means: \t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.mean(i)); } printf("\n"); printf("Variance:\t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.variance(i)); } printf("\n"); printf("Covariance Matrix:\n"); for (int i = 0; i < im.channels; i++) { printf("\t\t\t"); for (int j = 0; j < im.channels; j++) { printf("%3.6f\t", stats.covariance(i, j)); } printf("\n"); } printf("\n"); printf("Skewness:\t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.skew(i)); } printf("\n"); printf("Kurtosis:\t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.kurtosis(i)); } printf("\n"); printf("\n"); printf("Barycenter (X):\t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.barycenterX(i)); } printf("\n"); printf("Barycenter (Y):\t\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.barycenterX(i)); } printf("\n"); printf("Spatial variance (X):\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.spatialvarianceX(i)); } printf("\n"); printf("Spatial variance (Y):\t"); for (int i = 0; i < im.channels; i++) { printf("%3.6f\t", stats.spatialvarianceY(i)); } printf("\n"); printf("\n"); printf("NaN count: %i\n", stats.nans()); printf("+Inf count: %i\n", stats.posinfs()); printf("-Inf count: %i\n", stats.neginfs()); printf("\n"); } void Noise::help() { pprintf("-noise adds uniform noise to the current image, uncorrelated across the" " channels, in the range between the two arguments. With one argument, the" " lower value is assumed to be zero. With no arguments, the range is assumed" " to be [0, 1]\n\n" "Usage: ImageStack -load a.tga -push -noise -add -save anoisy.tga\n\n"); } void Noise::parse(vector<string> args) { assert(args.size() < 3, "-noise takes zero, one, or two arguments\n"); float maxVal = 1; float minVal = 0; if (args.size() == 1) { maxVal = readFloat(args[0]); } else if (args.size() == 2) { minVal = readFloat(args[0]); maxVal = readFloat(args[1]); } apply(stack(0), minVal, maxVal); } void Noise::apply(Window im, float minVal, float maxVal) { for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { im(x, y, t)[c] += randomFloat(minVal, maxVal); } } } } } void Histogram::help() { pprintf("-histogram computes a per-channel histogram of the current image." " The first optional argument specifies the number of buckets in the" " histogram. If this is not given it defaults to 256. The second and" " third arguments indicate the range of data to expect. These default" " to 0 and 1." "Usage: ImageStack -load a.tga -histogram -normalize -plot 256 256 3 -display\n"); } void Histogram::parse(vector<string> args) { assert(args.size() < 4, "-histogram takes three or fewer arguments\n"); int buckets = 256; float minVal = 0.0f; float maxVal = 1.0f; if (args.size() > 0) { buckets = readInt(args[0]); } if (args.size() > 1) { minVal = readFloat(args[1]); } if (args.size() > 2) { maxVal = readFloat(args[2]); } push(apply(stack(0), buckets, minVal, maxVal)); } Image Histogram::apply(Window im, int buckets, float minVal, float maxVal) { float invBucketWidth = buckets / (maxVal - minVal); float inc = 1.0f / (im.width * im.height * im.frames); Image hg(buckets, 1, 1, im.channels); for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { double value = im(x, y, t)[c]; int bucket; if (isnan((float)value)) { continue; } else if (isinf((float)value)) { continue; } else { bucket = (int)((value - minVal) * invBucketWidth); if (bucket >= buckets) { bucket = buckets-1; } if (bucket < 0) { bucket = 0; } } hg(bucket, 0, 0)[c] += inc; } } } } return hg; } void Equalize::help() { pprintf("-equalize flattens out the histogram of an image, while preserving ordering" " between pixel brightnesses. It does this independently in each channel. When" " given no arguments, it produces an image with values between zero and one. With" " one argument, it produces values between zero and that argument. With two" " arguments, it produces values between the two arguments. The brightest pixel(s)" " will always map to the upper bound and the dimmest to the lower bound.\n\n" "Usage: ImageStack -load a.tga -equalize 0.2 0.8 -save out.tga\n\n"); } void Equalize::parse(vector<string> args) { assert(args.size() < 3, "-equalize takes zero, one, or two arguments\n"); float lower = 0, upper = 1; if (args.size() == 1) { upper = readFloat(args[0]); } else if (args.size() == 2) { lower = readFloat(args[0]); upper = readFloat(args[1]); } apply(stack(0), lower, upper); } void Equalize::apply(Window im, float lower, float upper) { Stats stats(im); // STEP 1) Normalize the image to the 0-1 range Normalize::apply(im); // STEP 2) Calculate a CDF of the image int buckets = 4096; Image cdf = Histogram::apply(im, buckets); Integrate::apply(cdf, 'x'); // STEP 3) For each pixel, find out how many things are in the same bucket or smaller, and use that to set the value for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { float alpha = im(x, y, t)[c] * buckets; int bucket = (int)alpha; // which bucket am I in? if (bucket < 0) { bucket = 0; } if (bucket >= buckets) { bucket = buckets-1; } alpha -= bucket; // how far along am I in this bucket? // how many pixels are probably less than me? float lesser = 0; if (bucket > 0) { lesser = cdf(bucket-1, 0)[c]; } float equal = cdf(bucket, 0)[c] - lesser; // use the estimate to set the value im(x, y, t)[c] = (lesser + alpha * equal) * (upper - lower) + lower; } } } } } void HistogramMatch::help() { pprintf("-histogrammatch alters the histogram of the current image to match" " that of the second image, while preserving ordering. Performing any" " monotonic operation to an image, and then histogram matching it to" " its original should revert it to its original.\n\n" "Usage: ImageStack -load a.tga -load b.tga -histogrammatch -save ba.tga\n\n"); } void HistogramMatch::parse(vector<string> args) { assert(args.size() == 0, "-histogrammatch takes no arguments\n"); apply(stack(0), stack(1)); } void HistogramMatch::apply(Window im, Window model) { assert(im.channels == model.channels, "Images must have the same number of channels\n"); // Compute cdfs of the two images Stats s1(im), s2(model); int buckets = 4096; Image cdf1 = Histogram::apply(im, buckets, s1.minimum(), s1.maximum()); Image cdf2 = Histogram::apply(model, buckets, s2.minimum(), s2.maximum()); Integrate::apply(cdf1, 'x'); Integrate::apply(cdf2, 'x'); // Invert cdf2 Image inverseCDF2(cdf2.width, 1, 1, cdf2.channels); for (int c = 0; c < inverseCDF2.channels; c++) { int xi = 0; float invWidth = 1.0f / cdf2.width; for (int x = 0; x < inverseCDF2.width; x++) { while (cdf2(xi, 0)[c] < x * invWidth && xi < cdf2.width) { xi++; } // cdf2(xi, 0)[c] is now just greater than x / inverseCDF2.width float lower = xi > 0 ? cdf2(xi-1, 0)[c] : 0; float upper = xi < cdf2.width ? cdf2(xi, 0)[c] : lower; // where is x*invWidth between lower and upper? float alpha = 0; if (upper > lower && x *invWidth >= lower && x *invWidth <= upper) { alpha = (x*invWidth - lower)/(upper - lower); } inverseCDF2(x, 0)[c] = xi + alpha; } } // Now apply the cdf of image 1 followed by the inverse cdf of image 2 float invBucketWidth = buckets / (s1.maximum() - s1.minimum()); for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { float alpha = (im(x, y, t)[c] - s1.minimum()) * invBucketWidth; int bucket = (int)alpha; // which bucket am I in? if (bucket < 0) { bucket = 0; } if (bucket >= buckets) { bucket = buckets-1; } alpha -= bucket; // how far along am I in this bucket? // how many pixels are probably less than me? float lesser = 0; if (bucket > 0) { lesser = cdf1(bucket-1, 0)[c]; } float equal = cdf1(bucket, 0)[c] - lesser; // use the estimate to get the percentile float percentile = lesser + alpha * equal; //im(x, y, t)[c] = percentile; // look up the percentile in inverseCDF2 in the same way alpha = percentile * buckets; bucket = (int)alpha; if (bucket < 0) { bucket = 0; } if (bucket >= buckets) { bucket = buckets-1; } alpha -= bucket; lesser = 0; if (bucket > 0) { lesser = inverseCDF2(bucket-1, 0)[c]; } equal = inverseCDF2(bucket, 0)[c] - lesser; im(x, y, t)[c] = (lesser + alpha * equal) * (s2.maximum() - s2.minimum()) / buckets + s2.minimum(); } } } } } void Shuffle::help() { pprintf("-shuffle takes every pixel in the current image and swaps it to a" " random new location creating a new noise image with exactly the same" " histogram.\n\n" "Usage: ImageStack -load a.tga -shuffle -save shuffled.tga\n\n"); } void Shuffle::parse(vector<string> args) { assert(args.size() == 0, "-shuffle takes no arguments\n"); apply(stack(0)); } void Shuffle::apply(Window im) { for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { float *ptr1 = im(x, y, t); // pick a random new location after this one int ot, ox, oy; ot = randomInt(t, im.frames-1); if (ot > t) { oy = randomInt(0, im.height-1); } else { oy = randomInt(y, im.height-1); } if (oy > y || ot > t) { ox = randomInt(0, im.width-1); } else { ox = randomInt(x+1, im.width-1); } float *ptr2 = im(ox, oy, ot); for (int c = 0; c < im.channels; c++) { float tmp = ptr1[c]; ptr1[c] = ptr2[c]; ptr2[c] = tmp; } } } } } void KMeans::help() { printf("-kmeans clusters the image into a number of clusters given by the" " single integer argument.\n\n" "Usage: ImageStack -load in.jpg -kmeans 3 -save out.jpg\n\n"); } void KMeans::parse(vector<string> args) { assert(args.size() == 1, "-kmeans takes one argument\n"); apply(stack(0), readInt(args[0])); } void KMeans::apply(Window im, int clusters) { assert(clusters > 1, "must have at least one cluster\n"); vector< vector<float> > cluster, newCluster; vector<int> newClusterMembers(clusters); for (int c = 0; c < im.channels; c++) { cluster.push_back(vector<float>(clusters, 0)); newCluster.push_back(vector<float>(clusters, 0)); } // initialize the clusters to randomly selected pixels for (int i = 0; i < clusters; i++) { float *pixel = im(randomInt(0, im.width-1), randomInt(0, im.height-1), randomInt(0, im.frames-1)); for (int c = 0; c < im.channels; c++) { cluster[c][i] = pixel[c] + randomFloat(-0.0001f, 0.0001f); } } while (1) { // wipe the newCluster for (int i = 0; i < clusters; i++) { newClusterMembers[i] = 0; for (int c = 0; c < im.channels; c++) { newCluster[c][i] = 0; } } for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { float *pixel = im(x, y, t); // assign this pixel to a cluster int bestCluster = 0; float bestDistance = 1e10; for (int i = 0; i < clusters; i++) { float distance = 0; for (int c = 0; c < im.channels; c++) { float d = cluster[c][i] - pixel[c]; distance += d*d; } if (distance < bestDistance) { bestCluster = i; bestDistance = distance; } } for (int c = 0; c < im.channels; c++) { newCluster[c][bestCluster] += pixel[c]; } newClusterMembers[bestCluster]++; } } } // normalize the new clusters (reset any zero ones to random) for (int i = 0; i < clusters; i++) { if (newClusterMembers[i] == 0) { float *pixel = im(randomInt(0, im.width-1), randomInt(0, im.height-1), randomInt(0, im.frames-1)); for (int c = 0; c < im.channels; c++) { newCluster[c][i] = pixel[c] + randomFloat(-0.0001f, 0.0001f); } } else { for (int c = 0; c < im.channels; c++) { newCluster[c][i] /= newClusterMembers[i]; } } } // break if the clusters are unchanged if (cluster == newCluster) { break; } // swap over the pointers cluster.swap(newCluster); } // now color each pixel according to the closest cluster for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { float *pixel = im(x, y, t); // assign this pixel to a cluster int bestCluster = 0; float bestDistance = 1e10; for (int i = 0; i < clusters; i++) { float distance = 0; for (int c = 0; c < im.channels; c++) { float d = cluster[c][i] - pixel[c]; distance += d*d; } if (distance < bestDistance) { bestCluster = i; bestDistance = distance; } } for (int c = 0; c < im.channels; c++) { pixel[c] = cluster[c][bestCluster]; } } } } } void Sort::help() { pprintf("-sort sorts the data along the given dimension for every value of the" " other dimensions. For example, the following command computes the" " median frame of a video.\n\n" "ImageStack -loadframes frame*.jpg -sort t -crop frames/2 1 -save median.jpg\n\n"); } void Sort::parse(vector<string> args) { assert(args.size() == 1, "-sort takes one argument\n"); apply(stack(0), readChar(args[0])); } void Sort::apply(Window im, char dimension) { assert(dimension == 'x' || dimension == 'y' || dimension == 't' || dimension == 'c', "Dimension must be x, y, t, or c\n"); if (dimension == 'c') { for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { ::std::sort(im(x, y, t), im(x, y, t)+im.channels); } } } } else if (dimension == 'x') { vector<float> tmp(im.width); for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int c = 0; c < im.channels; c++) { for (int x = 0; x < im.width; x++) { tmp[x] = im(x, y, t)[c]; } sort(tmp.begin(), tmp.end()); for (int x = 0; x < im.width; x++) { im(x, y, t)[c] = tmp[x]; } } } } } else if (dimension == 'y') { vector<float> tmp(im.height); for (int t = 0; t < im.frames; t++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { for (int y = 0; y < im.height; y++) { tmp[y] = im(x, y, t)[c]; } sort(tmp.begin(), tmp.end()); for (int y = 0; y < im.height; y++) { im(x, y, t)[c] = tmp[y]; } } } } } else if (dimension == 't') { vector<float> tmp(im.frames); for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { for (int t = 0; t < im.frames; t++) { tmp[t] = im(x, y, t)[c]; } sort(tmp.begin(), tmp.end()); for (int t = 0; t < im.frames; t++) { im(x, y, t)[c] = tmp[t]; } } } } } } void DimensionReduction::help() { pprintf("-dimensionreduction takes a dimensionality and projects all points on" " the image onto a linear subspace of best fit with that number of" " dimensions. It is useful if you know an image should be low" " dimensional (eg a sunset is mostly shades or red), and components" " orthogonal to that dimension are unwanted (eg chromatic" " abberation).\n\n" "Usage: ImageStack -load sunset.jpg -dimensionreduction 2 -save fixed.jpg\n\n"); } void DimensionReduction::parse(vector<string> args) { assert(args.size() == 1, "-dimensionreduction takes no argument\n"); apply(stack(0), readInt(args[0])); } void DimensionReduction::apply(Window im, int dimensions) { assert(dimensions < im.channels && dimensions > 0, "dimensions must be greater than zero and less than the current number of channels\n"); // get some statistics (mostly for the covariance matrix) Stats stats(im); // we're going to find the leading eigenvectors of the covariance matrix and // use them as the basis for our subspace vector<float> subspace(dimensions * im.channels), newsubspace(dimensions * im.channels); for (int i = 0; i < dimensions * im.channels; i++) { subspace[i] = randomFloat(0, 1); } float delta = 1; while (delta > 0.00001) { // multiply the subspace by the covariance matrix for (int d = 0; d < dimensions; d++) { for (int c1 = 0; c1 < im.channels; c1++) { newsubspace[d *im.channels + c1] = 0; for (int c2 = 0; c2 < im.channels; c2++) { newsubspace[d *im.channels + c1] += (float)(subspace[d * im.channels + c2] * stats.covariance(c1, c2)); } } } // orthonormalize it with gram-schmidt for (int d = 0; d < dimensions; d++) { // first subtract it's component in the direction of all earlier vectors for (int d2 = 0; d2 < d; d2++) { float dot = 0; for (int c = 0; c < im.channels; c++) { dot += newsubspace[d * im.channels + c] * newsubspace[d2 * im.channels + c]; } for (int c = 0; c < im.channels; c++) { newsubspace[d *im.channels + c] -= dot * newsubspace[d2 * im.channels + c]; } } // then normalize it float sum = 0; for (int c = 0; c < im.channels; c++) { float val = newsubspace[d * im.channels + c]; sum += val * val; } float factor = 1.0f / sqrt(sum); for (int c = 0; c < im.channels; c++) { newsubspace[d *im.channels + c] *= factor; } // if the sum is negative, flip it sum = 0; for (int c = 0; c < im.channels; c++) { sum += newsubspace[d * im.channels + c]; } if (sum < -0.01) { for (int c = 0; c < im.channels; c++) { newsubspace[d *im.channels + c] *= -1; } } } // check to see how much changed delta = 0; for (int d = 0; d < dimensions; d++) { for (int c = 0; c < im.channels; c++) { float diff = newsubspace[d * im.channels + c] - subspace[d * im.channels + c]; delta += diff * diff; } } newsubspace.swap(subspace); } // now project the image onto the subspace vector<float> output(im.channels); for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { output[c] = 0; } // project this pixel onto each vector, and add the results for (int d = 0; d < dimensions; d++) { float dot = 0; for (int c = 0; c < im.channels; c++) { dot += im(x, y, t)[c] * subspace[d * im.channels + c]; } for (int c = 0; c < im.channels; c++) { output[c] += dot * subspace[d * im.channels + c]; } } for (int c = 0; c < im.channels; c++) { im(x, y, t)[c] = output[c]; } } } } // display the subspace for debugging printf("Basis chosen:\n"); for (int c = 0; c < im.channels; c++) { for (int d = 0; d < dimensions; d++) { printf("%f \t", newsubspace[d * im.channels + c]); } printf("\n"); } } void LocalMaxima::help() { pprintf("-localmaxima finds local maxima in the image and outputs their" " locations to a text file. Each line in the text file consists of four" " comma-delimited floating point values, corresponding to the t, x and y" " coordinates, and the strength of the local maxima (its value minus the" " maximum neighbor). -localmaxima will only operate on the first" " channel of an image. There are three arguments. The first is some" " string containing the characters x, y, and t. It specifies the" " dimensions over which a pixel must be greater than its neighbors. The" " second is the minimum value by which a pixel must exceed its" " neighbors to count as a local maximum. The third is the minimum" " distance which must separate adjacent local maxima.\n" "\n" "Usage: ImageStack -load stack.tmp -localmaxima txy 0.01 5 output.txt\n"); } void LocalMaxima::parse(vector<string> args) { assert(args.size() == 4, "-localmaxima takes 4 arguments\n"); bool tCheck = false, xCheck = false, yCheck = false; // first make sure file can be opened FILE *f = fopen(args[3].c_str(), "w"); assert(f, "Could not open file %s\n", args[2].c_str()); for (unsigned int i=0; i < args[0].size(); i++) { switch (args[0][i]) { case 't': tCheck=true; break; case 'x': xCheck=true; break; case 'y': yCheck=true; break; default: panic("Unknown -localmaxima flag: %c\n",args[0][i]); } } assert(tCheck || xCheck || yCheck, "-localmaxima requires at least one active dimension to find local maxima\n"); vector<LocalMaxima::Maximum> maxima = apply(stack(0), xCheck, yCheck, tCheck, readFloat(args[1]), readFloat(args[2])); for (unsigned int i = 0; i < maxima.size(); i++) { fprintf(f, "%f,%f,%f,%f\n", maxima[i].t, maxima[i].x, maxima[i].y, maxima[i].value); } fclose(f); } struct <API key> { // a is the index of stronger of the two unsigned a, b; float disparity; // define an operator so that std::sort will sort them from // maximum strength disparity to minimum strength disparity bool operator<(const <API key> &other) const { return disparity > other.disparity; } }; vector<LocalMaxima::Maximum> LocalMaxima::apply(Window im, bool tCheck, bool xCheck, bool yCheck, float threshold, float minDistance) { vector<LocalMaxima::Maximum> results; // float values for locations float ft, fx, fy; float value; // the actual image value // select bounds for search int tStart, tEnd, yStart, yEnd, xStart, xEnd; if (tCheck) { tStart = 1; tEnd = im.frames-1; } else { tStart = 0; tEnd = im.frames; } if (xCheck) { xStart = 1; xEnd = im.width-1; } else { xStart = 0; xEnd = im.width; } if (yCheck) { yStart = 1; yEnd = im.height-1; } else { yStart = 0; yEnd = im.height; } // now do a search for (int t = tStart; t<tEnd; t++) { for (int y = yStart; y<yEnd; y++) { for (int x = xStart; x<xEnd; x++) { fx = x; fy = y; ft = t; value = im(x, y, t)[0]; // eliminate if not a x maximum if (xCheck && (im(x, y, t)[0] <= im(x-1, y, t)[0] || im(x, y, t)[0] <= im(x+1, y, t)[0])) { continue; } else if (xCheck) { // fine tune x coordinate by taking local centroid fx += (im(x+1, y, t)[0]-im(x-1, y, t)[0])/(im(x, y, t)[0]+im(x-1, y, t)[0]+im(x+1, y, t)[0]); } // eliminate if not a y maximum if (yCheck && (im(x, y, t)[0] <= im(x, y-1, t)[0] || im(x, y, t)[0] <= im(x, y+1, t)[0])) { continue; } else if (yCheck) { // fine tune y coordinate by taking local centroid fy += (im(x, y+1, t)[0]-im(x, y-1, t)[0])/(im(x, y, t)[0]+im(x, y-1, t)[0]+im(x, y+1, t)[0]); } // eliminate if not a t maximum if (tCheck && (im(x, y, t)[0] <= im(x, y, t-1)[0] || im(x, y, t)[0] <= im(x, y, t+1)[0])) { continue; } else if (tCheck) { // fine tune t coordinate by taking local centroid ft += (im(x, y, t+1)[0]-im(x, y, t-1)[0])/(im(x, y, t)[0]+im(x, y, t-1)[0]+im(x, y, t+1)[0]); } // eliminate if not high enough float strength = threshold+1; if (xCheck) { strength = min(strength, value - im(x-1, y, t)[0]); strength = min(strength, value - im(x+1, y, t)[0]); } if (yCheck) { strength = min(strength, value - im(x, y+1, t)[0]); strength = min(strength, value - im(x, y-1, t)[0]); } if (tCheck) { strength = min(strength, value - im(x, y, t+1)[0]); strength = min(strength, value - im(x, y, t-1)[0]); } if (strength < threshold) { continue; } // output if it is a candidate Maximum m; m.t = ft; m.x = fx; m.y = fy; m.value = value; results.push_back(m); } } } if (minDistance < 1) { return results; } vector<<API key>> collisions; // Now search for collisions. This is made somewhat easier because // the results are already sorted by their t, then y, then x // coordinate. for (unsigned i = 0; i < results.size(); i++) { for (unsigned j = i+1; j < results.size(); j++) { float dist = 0, d; if (xCheck) { d = results[i].x - results[j].x; dist += d*d; } if (yCheck) { d = results[i].y - results[j].y; dist += d*d; } if (tCheck) { d = results[i].t - results[j].t; dist += d*d; } if (dist < minDistance*minDistance) { <API key> c; if (results[i].value > results[j].value) { c.disparity = results[i].value - results[j].value; c.a = i; c.b = j; } else { c.disparity = results[j].value - results[i].value; c.a = j; c.b = i; } collisions.push_back(c); } // Early bailout. The +2 is because results may have // shifted by up to 1 each from their original sorted // locations due to the centroid finding above. if ((results[j].t - results[i].t) > (minDistance+2)) { break; } if (!tCheck && (results[j].y - results[i].y) > (minDistance+2)) { break; } if (!yCheck && !tCheck && (results[j].x - results[i].x) > (minDistance+2)) { break; } } } // Order the collisions from maximum strength disparity to minimum (i.e from easy decisions to hard ones) ::std::sort(collisions.begin(), collisions.end()); // Start by accepting them all, and knock some out greedily using // the collisions. This is a heurstic. To do this perfectly is a // multi-dimensional knapsack problem, and is NP-complete. vector<bool> accepted(results.size(), true); for (unsigned i = 0; i < collisions.size(); i++) { if (accepted[collisions[i].a] && accepted[collisions[i].b]) { accepted[collisions[i].b] = false; } } // return only the accepted points vector<LocalMaxima::Maximum> goodResults; for (unsigned i = 0; i < results.size(); i++) { if (accepted[i]) { goodResults.push_back(results[i]); } } /* // draw the results on an image for debugging for (unsigned i = 0; i < results.size(); i++) { int t = (int)(results[i].t+0.5); int y = (int)(results[i].y+0.5); int x = (int)(results[i].x+0.5); if (x < 0) x = 0; if (x >= im.width) x = im.width-1; if (y < 0) y = 0; if (y >= im.height) y = im.height-1; if (t < 0) t = 0; if (t >= im.frames) t = im.frames-1; if (accepted[i]) im(x, y, t)[0] = 100; else im(x, y, t)[0] = -100; } */ return goodResults; } void Printf::help() { pprintf("-printf evaluates and prints its arguments, using the first argument" " as a format string. The remaining arguments are all evaluated as" " floats, so use %%d, %%i, and other non-float formats with caution.\n" "\n" "Usage: ImageStack -load foo.jpg -printf \"Mean = %%f\" \"mean()\"\n\n"); } void Printf::parse(vector<string> args) { assert(args.size() > 0, "-printf requires at least one argument\n"); vector<float> fargs; for (unsigned i = 1; i < args.size(); i++) { fargs.push_back(readFloat(args[args.size()-i])); } apply(stack(0), args[0], fargs); } void Printf::apply(Window im, string fmt, vector<float> a) { float args[16]; assert(a.size() < 16, "-printf can't handle that many arguments\n"); for (unsigned i = 0; i < a.size(); i++) { args[i] = a[i]; } printf(fmt.c_str(), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15]); printf("\n"); } void FPrintf::help() { pprintf("-fprintf evaluates and prints its arguments, appending them to the" " file specified by the first argument, using the second argument as a" " format string. The remaining arguments are all evaluated as floats," " so use %%d, %%i, and other non-float formats with caution.\n\n" "Usage: ImageStack -load foo.jpg -fprintf results.txt \"Mean = %%f\" \"mean()\""); } void FPrintf::parse(vector<string> args) { assert(args.size() > 1, "-fprintf requires at least two arguments\n"); vector<float> fargs; for (unsigned i = 2; i < args.size(); i++) { fargs.push_back(readFloat(args[args.size()-i+1])); } apply(stack(0), args[0], args[1], fargs); } void FPrintf::apply(Window im, string filename, string fmt, vector<float> a) { FILE *f = fopen(filename.c_str(), "a"); assert(f, "Could not open %s\n", filename.c_str()); float args[16]; assert(a.size() < 16, "-printf can't handle that many arguments\n"); for (unsigned i = 0; i < a.size(); i++) { args[i] = a[i]; } fprintf(f, fmt.c_str(), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15]); fprintf(f, "\n"); fclose(f); } void PCA::help() { pprintf("-pca reduces the number of channels in the image to the given" " parameter, using principal components analysis (PCA).\n\n" "Usage: ImageStack -load a.jpg -pca 1 -save gray.png\n"); } void PCA::parse(vector<string> args) { assert(args.size() == 1, "-pca takes one argument\n"); Image im = apply(stack(0), readInt(args[0])); pop(); push(im); } Image PCA::apply(Window im, int newChannels) { assert(newChannels <= im.channels, "-pca can only reduce dimensionality, not expand it\n"); Image out(im.width, im.height, im.frames, newChannels); Eigenvectors e(im.channels, out.channels); float *imPtr = im(0, 0); for (int iter = 0; iter < min(10000, im.width*im.height*im.frames); iter++) { int t = randomInt(0, im.frames-1); int x = randomInt(0, im.width-1); int y = randomInt(0, im.height-1); e.add(im(x, y, t)); } float *outPtr = out(0, 0); imPtr = im(0, 0); for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { e.apply(imPtr, outPtr); imPtr += im.channels; outPtr += out.channels; } } } return out; } void PatchPCA::help() { pprintf("-patchpca treats local Gaussian neighbourhoods of pixel values as vectors" " and computes a stack of filters that can be used to reduce" " dimensionality and decorrelate the color channels. The two arguments" " are the standard deviation of the Gaussian, and the desired number of" " output dimensions. Patches near the edge of the image are not" " included in the covariance computation.\n" "Usage: ImageStack -load a.jpg -patchpca 2 8 -save filters.tmp\n" " -pull 1 -convolve zero inner -save reduced.tmp\n"); } void PatchPCA::parse(vector<string> args) { assert(args.size() == 2, "-patchpca takes two arguments\n"); Image im = apply(stack(0), readFloat(args[0]), readInt(args[1])); push(im); } Image PatchPCA::apply(Window im, float sigma, int newChannels) { int patchSize = ((int)(sigma*6+1)) | 1; printf("Using %dx%d patches\n", patchSize, patchSize); vector<float> mask(patchSize); float sum = 0; printf("Gaussian mask: "); for (int i = 0; i < patchSize; i++) { mask[i] = expf(-(i-patchSize/2)*(i - patchSize/2)/(2*sigma*sigma)); sum += mask[i]; printf("%f ", mask[i]); } for (int i = 0; i < patchSize; i++) { mask[i] /= sum; } printf("\n"); vector<float> vec(patchSize*patchSize*im.channels); Eigenvectors e(patchSize*patchSize*im.channels, newChannels); for (int iter = 0; iter < min(10000, im.width*im.height*im.frames); iter++) { int t = randomInt(0, im.frames-1); int x = randomInt(patchSize/2, im.width-1-patchSize/2); int y = randomInt(patchSize/2, im.height-1-patchSize/2); float *imPtr = im(x, y, t); int j = 0; for (int dy = -patchSize/2; dy <= patchSize/2; dy++) { for (int dx = -patchSize/2; dx <= patchSize/2; dx++) { for (int c = 0; c < im.channels; c++) { vec[j] = (mask[dx+patchSize/2]* mask[dy+patchSize/2]* imPtr[dy*im.ystride + dx*im.xstride + c]); j++; } } } e.add(&vec[0]); } e.compute(); Image filters(patchSize, patchSize, 1, im.channels * newChannels); for (int i = 0; i < newChannels; i++) { e.getEigenvector(i, &vec[0]); int j = 0; for (int y = 0; y < patchSize; y++) { for (int x = 0; x < patchSize; x++) { for (int c = 0; c < im.channels; c++) { filters(x, y)[i *im.channels+c] = vec[j]; j++; } } } } return filters; } void PatchPCA3D::help() { pprintf("-patchpca3d treats local 3D Gaussian neighbourhoods of pixel values as vectors" " and computes a stack of filters that can be used to reduce" " dimensionality and decorrelate the color channels. The two arguments" " are the standard deviation of the Gaussian, and the desired number of" " output dimensions. Patches near the edge of the image are not" " included in the covariance computation.\n" "Usage: ImageStack -load volume.tmp -patchpca3d 2 8 -save filters.tmp\n" " -pull 1 -convolve zero inner -save reduced.tmp\n"); } void PatchPCA3D::parse(vector<string> args) { assert(args.size() == 2, "-patchpca3d takes two arguments\n"); Image im = apply(stack(0), readFloat(args[0]), readInt(args[1])); push(im); } Image PatchPCA3D::apply(Window im, float sigma, int newChannels) { int patchSize = ((int)(sigma*6+1)) | 1; printf("Using %dx%d patches\n", patchSize, patchSize); vector<float> mask(patchSize); float sum = 0; printf("Gaussian mask: "); for (int i = 0; i < patchSize; i++) { mask[i] = expf(-(i-patchSize/2)*(i - patchSize/2)/(2*sigma*sigma)); sum += mask[i]; printf("%f ", mask[i]); } for (int i = 0; i < patchSize; i++) { mask[i] /= sum; } printf("\n"); vector<float> vec(patchSize*patchSize*patchSize*im.channels); Eigenvectors e(patchSize*patchSize*patchSize*im.channels, newChannels); for (int iter = 0; iter < min(1000, im.width*im.height*im.frames); iter++) { int t = randomInt(patchSize/2, im.frames-1-patchSize/2); int x = randomInt(patchSize/2, im.width-1-patchSize/2); int y = randomInt(patchSize/2, im.height-1-patchSize/2); float *imPtr = im(x, y, t); int j = 0; for (int dt = -patchSize/2; dt <= patchSize/2; dt++) { for (int dy = -patchSize/2; dy <= patchSize/2; dy++) { for (int dx = -patchSize/2; dx <= patchSize/2; dx++) { for (int c = 0; c < im.channels; c++) { vec[j] = (mask[dx+patchSize/2]* mask[dy+patchSize/2]* mask[dt+patchSize/2]* imPtr[dt*im.tstride + dy*im.ystride + dx*im.xstride + c]); j++; } } } } e.add(&vec[0]); } e.compute(); Image filters(patchSize, patchSize, patchSize, im.channels * newChannels); for (int i = 0; i < newChannels; i++) { e.getEigenvector(i, &vec[0]); int j = 0; for (int t = 0; t < patchSize; t++) { for (int y = 0; y < patchSize; y++) { for (int x = 0; x < patchSize; x++) { for (int c = 0; c < im.channels; c++) { filters(x, y, t)[i*im.channels+c] = vec[j]; j++; } } } } } return filters; } #include "footer.h"
package org.mafagafogigante.dungeon.entity.creatures; import org.mafagafogigante.dungeon.entity.Luminosity; import org.mafagafogigante.dungeon.entity.Preset; import org.mafagafogigante.dungeon.entity.TagSet; import org.mafagafogigante.dungeon.entity.Weight; import org.mafagafogigante.dungeon.entity.creatures.Creature.Tag; import org.mafagafogigante.dungeon.game.Id; import org.mafagafogigante.dungeon.game.Name; import org.mafagafogigante.dungeon.logging.DungeonLogger; import org.mafagafogigante.dungeon.util.Percentage; import java.io.Serializable; import java.util.List; /** * CreaturePreset class that stores the information that the CreatureFactory uses to produce creatures. */ public final class CreaturePreset implements Preset, Serializable { private TagSet<Tag> tagSet = TagSet.makeEmptyTagSet(Creature.Tag.class); private Id id; private String type; private Name name; private Weight weight; private int health; private int attack; private AttackAlgorithmId attackAlgorithmId; private List<Id> items; private List<Drop> dropList; private Percentage visibility; private Luminosity luminosity = Luminosity.ZERO; private Id weaponId; private int inventoryItemLimit; private double <API key>; private int damageReduction; /** * Ensures that an integer value is greater than or equal to a provided minimum. If it is not, returns the minimum and * logs a warning. * * @param value the original value * @param minimum the minimum acceptable value * @param attributeName the name of the attribute this value represents (used for logging) * @return an integer i such that i >= minimum */ private static int validate(int value, int minimum, String attributeName) { if (value >= minimum) { return value; } else { String format = "Attempted to set %d to %s in CreaturePreset. Using %d."; DungeonLogger.warning(String.format(format, value, attributeName, minimum)); return minimum; } } TagSet<Creature.Tag> getTagSet() { return tagSet; } public void setTagSet(TagSet<Creature.Tag> tagSet) { this.tagSet = tagSet; } public boolean hasTag(Creature.Tag tag) { return tagSet.hasTag(tag); } public Id getId() { return id; } public void setId(Id id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } public void setDamageReduction(int damageReduction) { this.damageReduction = damageReduction; } public int getDamageReduction() { return damageReduction; } public Weight getWeight() { return weight; } public void setWeight(Weight weight) { this.weight = weight; } public int getHealth() { return health; } public void setHealth(int health) { health = validate(health, 1, "health"); this.health = health; } public int getAttack() { return attack; } public void setAttack(int attack) { attack = validate(attack, 0, "attack"); this.attack = attack; } public AttackAlgorithmId <API key>() { return attackAlgorithmId; } public void <API key>(AttackAlgorithmId attackAlgorithmId) { this.attackAlgorithmId = attackAlgorithmId; } public List<Id> getItems() { return items; } public void setItems(List<Id> items) { this.items = items; } public List<Drop> getDropList() { return dropList; } public void setDropList(List<Drop> dropList) { this.dropList = dropList; } public Percentage getVisibility() { return visibility; } public void setVisibility(Percentage visibility) { this.visibility = visibility; } public Luminosity getLuminosity() { return luminosity; } public void setLuminosity(Luminosity luminosity) { this.luminosity = luminosity; } public Id getWeaponId() { return weaponId; } public void setWeaponId(Id weaponId) { this.weaponId = weaponId; } public int <API key>() { return inventoryItemLimit; } public void <API key>(int inventoryItemLimit) { this.inventoryItemLimit = inventoryItemLimit; } public double <API key>() { return <API key>; } public void <API key>(double <API key>) { this.<API key> = <API key>; } }
// Authors: Radu Serban // Torsion chassis connector model constructed with data from file (JSON format). #include "chrono/utils/ChCompositeInertia.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/chassis/<API key>.h" #include "chrono_vehicle/utils/ChUtilsJSON.h" using namespace rapidjson; namespace chrono { namespace vehicle { <API key>::<API key>(const std::string& filename) : <API key>("") { Document d = ReadFileJSON(filename); if (d.IsNull()) return; Create(d); GetLog() << "Loaded JSON: " << filename.c_str() << "\n"; } <API key>::<API key>(const rapidjson::Document& d) : <API key>("") { Create(d); } void <API key>::Create(const rapidjson::Document& d) { // Invoke base class method. ChPart::Create(d); // Read torsional stiffness m_torsion_stiffness = d["Torsional Stiffness"].GetDouble(); } } // end namespace vehicle } // end namespace chrono
{% extends "lbforum/base_site.html" %} {% load i18n %} {% load lbforum_filters %} {% load lbforum_tags %} {% block title %}{{ block.super }}{% endblock %} {% block content_right_bar %} {% include 'lbforum/widgets/cur_user_profile.html' %} {% endblock %} {% block content_content %} <div class="box"> <div class="cell"> <span class="bigger"> <a href="{% url 'lbforum_index' %}">{% trans "Home" %}</a> <span class="chevron">&raquo;</span> {% trans "Register" %} </span> </div> <div class="inner"> <form action="{% url 'account_signup' %}" accept-charset="utf-8" method="post" class="frm-form" id="afocus"> {% csrf_token %} {% if <API key> %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ <API key> }}" /> {% endif %} {% if form.errors %} <div class="ct-box error-box"> <p class="errornote"> {% trans "Please correct the errors below." %} </p> {{ form|form_all_error }} </div> {% endif %} <div class="sep10"></div> <table cellspacing="0" cellpadding="5" border="0"> <tbody> <tr> <td width="120" align="right"> {% trans "Username" %} </td> <td width="200" align="left"> {{ form.username }} </td> </tr> <tr> <td width="120" align="right"> {% trans "Password" %} </td> <td width="200" align="left"> {{ form.password1 }} </td> </tr> <tr> <td width="120" align="right"> {% trans "Password (again)" %} </td> <td width="200" align="left"> {{ form.password2 }} </td> </tr> <tr> <td width="120" align="right"> {% trans "e-mail" %} </td> <td width="200" align="left"> {{ form.email }} </td> </tr> <tr> <td width="120" align="right"> {% trans "captcha" %} </td> <td width="200" align="left"> {{ form.captcha }} </td> </tr> <tr> <td width="120" align="right"> </td> <td width="200" align="left"> <input type="submit" class="super normal button" value="{% trans "Sign Up" %}"> </td> </tr> </tbody> </table> </form> </div> </div> {% endblock %}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>lib/draft-js/ContentState.js - itsa-react-editor</title> <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css"> <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css"> <link rel="stylesheet" href="../assets/css/main.css" id="site_styles"> <link rel="icon" href="../assets/favicon.ico"> <script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script> </head> <body class="yui3-skin-sam"> <div id="doc"> <div id="hd" class="yui3-g header"> <div class="yui3-u-3-4"> <h1><img src="https://avatars0.githubusercontent.com/u/8314644?v=3&amp;s=84" title="itsa-react-editor"></h1> </div> <div class="yui3-u-1-4 version"> <em>API Docs for: 0.0.1</em> </div> </div> <div id="bd" class="yui3-g"> <div class="yui3-u-1-4"> <div id="docs-sidebar" class="sidebar apidocs"> <div id="api-list"> <h2 class="off-left">APIs</h2> <div id="api-tabview" class="tabview"> <ul class="tabs"> <li><a href="#api-classes">Classes</a></li> <li><a href="#api-modules">Modules</a></li> </ul> <div id="api-tabview-filter"> <input type="search" id="api-filter" placeholder="Type to filter APIs"> </div> <div id="api-tabview-panel"> <ul id="api-classes" class="apis classes"> <li><a href="../classes/Editor.html">Editor</a></li> </ul> <ul id="api-modules" class="apis modules"> <li><a href="../modules/component.jsx.html">component.jsx</a></li> </ul> </div> </div> </div> </div> </div> <div class="yui3-u-3-4"> <div id="api-options"> Show: <label for="api-show-inherited"> <input type="checkbox" id="api-show-inherited" checked> Inherited </label> <label for="api-show-protected"> <input type="checkbox" id="api-show-protected"> Protected </label> <label for="api-show-private"> <input type="checkbox" id="api-show-private"> Private </label> <label for="api-show-deprecated"> <input type="checkbox" id="api-show-deprecated"> Deprecated </label> </div> <div class="apidocs"> <div id="docs-main"> <div class="content"> <h1 class="file-heading">File: lib/draft-js/ContentState.js</h1> <div class="file"> <pre class="code prettyprint linenums"> &#x27;use strict&#x27;; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i &lt; props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (&#x27;value&#x27; in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; _again = false; if (object === null) object = Function.prototype; var desc = Object.<API key>(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if (& function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(&#x27;Cannot call a class as a function&#x27;); } } function _inherits(subClass, superClass) { if (typeof superClass !== &#x27;function&#x27; &amp;&amp; superClass !== null) { throw new TypeError(&#x27;Super expression must either be null or a function, not &#x27; + typeof superClass); } subClass.prototype = Object.create(superClass &amp;&amp; superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var BlockMapBuilder = require(&#x27;./BlockMapBuilder&#x27;); var CharacterMetadata = require(&#x27;./CharacterMetadata&#x27;); var ContentBlock = require(&#x27;./ContentBlock&#x27;); var Immutable = require(&#x27;immutable&#x27;); var SelectionState = require(&#x27;./SelectionState&#x27;); var generateRandomKey = require(&#x27;./generateRandomKey&#x27;); var sanitizeDraftText = require(&#x27;./sanitizeDraftText&#x27;); var List = Immutable.List; var Record = Immutable.Record; var Repeat = Immutable.Repeat; var defaultRecord = { blockMap: null, selectionBefore: null, selectionAfter: null }; var ContentStateRecord = Record(defaultRecord); var ContentState = (function (_ContentStateRecord) { _inherits(ContentState, _ContentStateRecord); function ContentState() { _classCallCheck(this, ContentState); _get(Object.getPrototypeOf(ContentState.prototype), &#x27;constructor&#x27;, this).apply(this, arguments); } _createClass(ContentState, [{ key: &#x27;getBlockMap&#x27;, value: function getBlockMap() { return this.get(&#x27;blockMap&#x27;); } }, { key: &#x27;getSelectionBefore&#x27;, value: function getSelectionBefore() { return this.get(&#x27;selectionBefore&#x27;); } }, { key: &#x27;getSelectionAfter&#x27;, value: function getSelectionAfter() { return this.get(&#x27;selectionAfter&#x27;); } }, { key: &#x27;getBlockForKey&#x27;, value: function getBlockForKey(key) { var block = this.getBlockMap().get(key); return block; } }, { key: &#x27;getKeyBefore&#x27;, value: function getKeyBefore(key) { return this.getBlockMap().reverse().keySeq().skipUntil(function (v) { return v === key; }).skip(1).first(); } }, { key: &#x27;getKeyAfter&#x27;, value: function getKeyAfter(key) { return this.getBlockMap().keySeq().skipUntil(function (v) { return v === key; }).skip(1).first(); } }, { key: &#x27;getBlockAfter&#x27;, value: function getBlockAfter(key) { return this.getBlockMap().skipUntil(function (_, k) { return k === key; }).skip(1).first(); } }, { key: &#x27;getBlockBefore&#x27;, value: function getBlockBefore(key) { return this.getBlockMap().reverse().skipUntil(function (_, k) { return k === key; }).skip(1).first(); } }, { key: &#x27;getBlocksAsArray&#x27;, value: function getBlocksAsArray() { return this.getBlockMap().toArray(); } }, { key: &#x27;getFirstBlock&#x27;, value: function getFirstBlock() { return this.getBlockMap().first(); } }, { key: &#x27;getLastBlock&#x27;, value: function getLastBlock() { return this.getBlockMap().last(); } }, { key: &#x27;getPlainText&#x27;, value: function getPlainText(delimiter) { return this.getBlockMap().map(function (block) { return block ? block.getText() : &#x27;&#x27;; }).join(delimiter || &#x27;\n&#x27;); } }, { key: &#x27;hasText&#x27;, value: function hasText() { var blockMap = this.getBlockMap(); return blockMap.size &gt; 1 || blockMap.first().getLength() &gt; 0; } }], [{ key: &#x27;<API key>&#x27;, value: function <API key>(blocks) { var blockMap = BlockMapBuilder.createFromArray(blocks); var selectionState = SelectionState.createEmpty(blockMap.first().getKey()); return new ContentState({ blockMap: blockMap, selectionBefore: selectionState, selectionAfter: selectionState }); } }, { key: &#x27;createFromText&#x27;, value: function createFromText(text) { var delimiter = arguments.length &lt;= 1 || arguments[1] === undefined ? /\r\n?|\n/g : arguments[1]; var strings = text.split(delimiter); var blocks = strings.map(function (block) { block = sanitizeDraftText(block); return new ContentBlock({ key: generateRandomKey(), text: block, type: &#x27;unstyled&#x27;, characterList: List(Repeat(CharacterMetadata.EMPTY, block.length)) }); }); return ContentState.<API key>(blocks); } }]); return ContentState; })(ContentStateRecord); module.exports = ContentState; </pre> </div> </div> </div> </div> </div> </div> </div> <script src="../assets/vendor/prettify/prettify-min.js"></script> <script>prettyPrint();</script> <script src="../assets/js/yui-prettify.js"></script> <script src="../assets/../api.js"></script> <script src="../assets/js/api-filter.js"></script> <script src="../assets/js/api-list.js"></script> <script src="../assets/js/api-search.js"></script> <script src="../assets/js/apidocs.js"></script> </body> </html>
#!/usr/bin/python3 import sys if len(sys.argv)!=4: print("Usage: %s infile outfile num"%sys.argv[0]) sys.exit(0) infile = open(sys.argv[1], "r") outfile = open(sys.argv[2], "w") num = float(sys.argv[3]) cont = True while cont: curnum = "" c = infile.read(1) while c!=" " and c!="": curnum+=c c = infile.read(1) if c=="": cont = False try: outnum = num*float(curnum) outfile.write("%f "%outnum) except: pass infile.close() outfile.close()