repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jordivila/Net_MVC_NLayer_Result
VsixMvcAppResult/VsixMvcAppResult.UI.Web/Scripts/jquery-globalize/lib/cultures/globalize.culture.es-CL.js
1942
/* * Globalize Culture es-CL * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "es-CL", "default", { name: "es-CL", englishName: "Spanish (Chile)", nativeName: "Español (Chile)", language: "es", numberFormat: { ",": ".", ".": ",", NaN: "NeuN", negativeInfinity: "-Infinito", positiveInfinity: "Infinito", percent: { ",": ".", ".": "," }, currency: { pattern: ["-$ n","$ n"], ",": ".", ".": "," } }, calendars: { standard: { "/": "-", days: { names: ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"], namesAbbr: ["dom","lun","mar","mié","jue","vie","sáb"], namesShort: ["do","lu","ma","mi","ju","vi","sá"] }, months: { names: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre",""], namesAbbr: ["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic",""] }, AM: null, PM: null, eras: [{"name":"d.C.","start":null,"offset":0}], patterns: { d: "dd-MM-yyyy", D: "dddd, dd' de 'MMMM' de 'yyyy", t: "H:mm", T: "H:mm:ss", f: "dddd, dd' de 'MMMM' de 'yyyy H:mm", F: "dddd, dd' de 'MMMM' de 'yyyy H:mm:ss", M: "dd MMMM", Y: "MMMM' de 'yyyy" } } } }); }( this ));
mit
aspnetboilerplate/module-zero-core-template
angular/src/typings.d.ts
641
///<reference path="../node_modules/abp-web-resources/Abp/Framework/scripts/abp.d.ts"/> ///<reference path="../node_modules/abp-web-resources/Abp/Framework/scripts/libs/abp.signalr.d.ts"/> ///<reference path="../node_modules/moment/moment.d.ts"/> // Typings reference file, see links for more information // https://github.com/typings/typings // https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html declare var System: any; declare var Push: any; declare namespace abp { namespace ui { function setBusy(elm?: any, text?: any, delay?: any): void; function clearBusy(elm?: any, delay?: any): void; } }
mit
icoach/bootstrap-starter
src/javascripts/main.js
164
// // Main // Initializes main behavior // ------------------------- $(function(){ console.log("Life is good") // Document is ready, put your scripts here });
mit
SymfonyId/AdminBundle
Twig/Functions/GenerateUserAvatarFunction.php
1404
<?php /* * This file is part of the AdminBundle package. * * (c) Muhammad Surya Ihsanuddin <surya.kejawen@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfonian\Indonesia\AdminBundle\Twig\Functions; use Symfonian\Indonesia\AdminBundle\Model\User; use Twig_Extension; use Twig_SimpleFunction; /** * @author Muhammad Surya Ihsanuddin <surya.kejawen@gmail.com> */ class GenerateUserAvatarFunction extends Twig_Extension { /** * @var string */ private $uploadDir; /** * @param string $uploadDir */ public function __construct($uploadDir) { $this->uploadDir = $uploadDir; } /** * @return array */ public function getFunctions() { return array( new Twig_SimpleFunction('generate_avatar', array($this, 'generateAvatar')), ); } /** * @param User $user * * @return string */ public function generateAvatar(User $user) { if ($user->getAvatar()) { return $this->uploadDir['web_path'].$user->getAvatar(); } else { return 'bundles/symfonianindonesiaadmin/img/apple-icon-114x114.png'; } } /** * @return string */ public function getName() { return 'generate_avatar'; } }
mit
gtforge/beego-assets
less/init.go
1560
package less import ( "bytes" "crypto/md5" "fmt" "os" "os/exec" "path/filepath" "github.com/gtforge/beego-assets" ) const lessExtension = ".less" const lessExtensionLen = len(lessExtension) var lessBuiltFilesDir = filepath.Join(beegoAssets.Config.TempDir, "less") func init() { _, err := exec.LookPath("lessc") if err != nil { beegoAssets.Error("Please, install Node.js less compiler: npm install less -g") return } beegoAssets.SetAssetFileExtension(lessExtension, beegoAssets.AssetStylesheet) beegoAssets.SetPreLoadCallback(beegoAssets.AssetStylesheet, BuildLessAsset) err = os.MkdirAll(lessBuiltFilesDir, 0766) if err != nil { beegoAssets.Error(err.Error()) return } } // BuildLessAsset - build less file from beegoAssets.Asset func BuildLessAsset(asset *beegoAssets.Asset) error { for i, src := range asset.IncludeFiles { ext := filepath.Ext(src) if ext == lessExtension { stat, err := os.Stat(src) if err != nil { beegoAssets.Error("Can't get stat of file %s. %v", src, err) continue } md5 := fmt.Sprintf("%x", md5.Sum([]byte(stat.ModTime().String()+src))) file := filepath.Base(src) fileName := file[:len(file)-lessExtensionLen] newFilePath := filepath.Join(lessBuiltFilesDir, fileName+"-"+md5+"_build.css") ex := exec.Command("lessc", src, newFilePath) var out bytes.Buffer ex.Stderr = &out err = ex.Run() if err != nil { fmt.Println("Error building LESS file:") fmt.Println(out.String()) continue } asset.IncludeFiles[i] = newFilePath } } return nil }
mit
infinitered/solidarity
__tests__/command_helpers/skipRule.ts
1708
import skipRule from '../../src/extensions/functions/skipRule' const currentPlatform = process.platform const makeMockRulePlatform = platform => ({ platform }) const mockRuleBasic = makeMockRulePlatform(currentPlatform) const mockRuleUppercase = makeMockRulePlatform(currentPlatform.toUpperCase()) test('skipRule takes a string', () => { expect(skipRule(mockRuleBasic)).toBe(false) expect(skipRule(mockRuleUppercase)).toBe(false) if (currentPlatform === 'darwin') { expect(skipRule(makeMockRulePlatform('macos'))).toBe(false) } else if (currentPlatform === 'win32') { expect(skipRule(makeMockRulePlatform('windows'))).toBe(false) } }) test('skipRule takes an array', () => { const arrayOfOne = [currentPlatform] expect(skipRule(makeMockRulePlatform(arrayOfOne))).toBe(false) const arrayOfMore = [currentPlatform, 'nachos', 'tacos'] expect(skipRule(makeMockRulePlatform(arrayOfMore))).toBe(false) if (currentPlatform === 'darwin') { expect(skipRule(makeMockRulePlatform(['macos', 'nachos', 'tacos']))).toBe(false) } else if (currentPlatform === 'win32') { expect(skipRule(makeMockRulePlatform(['windows', 'nachos', 'tacos']))).toBe(false) } }) test('skipRule false on unknown', () => { expect(skipRule({})).toBe(false) }) test('skips on platform miss', () => { expect(skipRule(makeMockRulePlatform('nachos'))).toBe(true) expect(skipRule(makeMockRulePlatform(['nachos']))).toBe(true) expect(skipRule(makeMockRulePlatform(['nachos', 'tacos']))).toBe(true) }) test('skips CI when flagged', () => { const onCI = !!process.env.CI expect(skipRule({ ci: true })).toBe(false) expect(skipRule({})).toBe(false) expect(skipRule({ ci: false })).toBe(onCI) })
mit
bloy/fuzzyclock
lib/fuzzyclock.rb
1246
require "fuzzyclock/version" module Fuzzyclock def self.time(t) hour = t.hour minute = t.min minute_text = RANGES. select{|range, text| range.include?(minute)}. map{|range, text| text}.first hour = hour + 1 if (33..59).include?(minute) hour = ((hour - 1) % 12) + 1 hour_text = HOURS[hour] if hour == 12 hour_text = (t.hour == 11 || t.hour == 12) ? 'noon' : 'midnight' end if (0..3).include?(minute) || (58..59).include?(minute) hour == 12 ? hour_text : "#{hour_text} #{minute_text}" else "#{minute_text} #{hour_text}" end end private RANGES = { (0..3) => %(o'clock), (4..7) => 'five past', (8..12) => 'ten past', (13..17) => 'quarter past', (18..22) => 'twenty past', (23..27) => 'twenty five past', (28..32) => 'half past', (33..37) => 'twenty five to', (38..42) => 'twenty to', (43..47) => 'quarter to', (48..52) => 'ten to', (53..57) => 'five to', (58..59) => %(o'clock) } HOURS = { 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve' } end
mit
BitBalloon/bitballoon-go
sites.go
3636
package bitballoon import ( "errors" "path" "time" ) var ( defaultTimeout time.Duration = 5 * 60 // 5 minutes ) // SitesService is used to access all Site related API methods type SitesService struct { client *Client } // Site represents a BitBalloon Site type Site struct { Id string `json:"id"` UserId string `json:"user_id"` // These fields can be updated through the API Name string `json:"name"` CustomDomain string `json:"custom_domain"` Password string `json:"password"` NotificationEmail string `json:"notification_email"` State string `json:"state"` Premium bool `json:"premium"` Claimed bool `json:"claimed"` Url string `json:"url"` AdminUrl string `json:"admin_url"` DeployUrl string `json:"deploy_url"` ScreenshotUrl string `json:"screenshot_url"` CreatedAt Timestamp `json:"created_at"` UpdatedAt Timestamp `json:"updated_at"` // Access deploys for this site Deploys *DeploysService client *Client } // Info returned when creating a new deploy type DeployInfo struct { Id string `json:"id"` DeployId string `json:"deploy_id"` Required []string `json:"required"` } // Attributes for Sites.Create type SiteAttributes struct { Name string `json:"name"` CustomDomain string `json:"custom_domain"` Password string `json:"password"` NotificationEmail string `json:"notification_email"` } // Get a single Site from the API. The id can be either a site Id or the domain // of a site (ie. site.Get("mysite.bitballoon.com")) func (s *SitesService) Get(id string) (*Site, *Response, error) { site := &Site{Id: id, client: s.client} site.Deploys = &DeploysService{client: s.client, site: site} resp, err := site.Reload() return site, resp, err } // Create a new empty site. func (s *SitesService) Create(attributes *SiteAttributes) (*Site, *Response, error) { site := &Site{client: s.client} site.Deploys = &DeploysService{client: s.client, site: site} reqOptions := &RequestOptions{JsonBody: attributes} resp, err := s.client.Request("POST", "/sites", reqOptions, site) return site, resp, err } // List all sites you have access to. Takes ListOptions to control pagination. func (s *SitesService) List(options *ListOptions) ([]Site, *Response, error) { sites := new([]Site) reqOptions := &RequestOptions{QueryParams: options.toQueryParamsMap()} resp, err := s.client.Request("GET", "/sites", reqOptions, sites) for _, site := range *sites { site.client = s.client site.Deploys = &DeploysService{client: s.client, site: &site} } return *sites, resp, err } func (site *Site) apiPath() string { return path.Join("/sites", site.Id) } func (site *Site) Reload() (*Response, error) { if site.Id == "" { return nil, errors.New("Cannot fetch site without an ID") } return site.client.Request("GET", site.apiPath(), nil, site) } // Update will update the fields that can be updated through the API func (site *Site) Update() (*Response, error) { options := &RequestOptions{JsonBody: site.mutableParams()} return site.client.Request("PUT", site.apiPath(), options, site) } // Destroy deletes a site permanently func (site *Site) Destroy() (*Response, error) { resp, err := site.client.Request("DELETE", site.apiPath(), nil, nil) if resp != nil && resp.Body != nil { resp.Body.Close() } return resp, err } func (site *Site) mutableParams() *map[string]string { return &map[string]string{ "name": site.Name, "custom_domain": site.CustomDomain, "password": site.Password, "notification_email": site.NotificationEmail, } }
mit
facebook/redex
libredex/SourceBlocks.cpp
22330
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "SourceBlocks.h" #include <limits> #include <optional> #include <sstream> #include <string> #include "ControlFlow.h" #include "Debug.h" #include "DexClass.h" #include "Dominators.h" #include "IROpcode.h" #include "Macros.h" #include "S_Expression.h" #include "ScopedMetrics.h" #include "Show.h" #include "SourceBlockConsistencyCheck.h" #include "Timer.h" #include "Trace.h" #include "Walkers.h" namespace source_blocks { using namespace cfg; using namespace sparta; namespace { constexpr SourceBlock::Val kFailVal = SourceBlock::Val::none(); constexpr SourceBlock::Val kXVal = SourceBlock::Val::none(); static SourceBlockConsistencyCheck s_sbcc; struct InsertHelper { DexMethod* method; uint32_t id{0}; std::ostringstream oss; bool serialize; bool insert_after_excs; struct ProfileParserState { s_expr root_expr; std::vector<s_expr> expr_stack; bool had_profile_failure{false}; boost::optional<SourceBlock::Val> default_val; boost::optional<SourceBlock::Val> error_val; ProfileParserState(s_expr root_expr, std::vector<s_expr> expr_stack, bool had_profile_failure, const boost::optional<SourceBlock::Val>& default_val, const boost::optional<SourceBlock::Val>& error_val) : root_expr(std::move(root_expr)), expr_stack(std::move(expr_stack)), had_profile_failure(had_profile_failure), default_val(default_val), error_val(error_val) {} }; std::vector<ProfileParserState> parser_state; InsertHelper(DexMethod* method, const std::vector<ProfileData>& profiles, bool serialize, bool insert_after_excs) : method(method), serialize(serialize), insert_after_excs(insert_after_excs) { for (const auto& p : profiles) { switch (p.index()) { case 0: // Nothing. parser_state.emplace_back(s_expr(), std::vector<s_expr>(), false, boost::none, boost::none); break; case 1: // Profile string. { const auto& pair = std::get<1>(p); const std::string& profile = pair.first; std::istringstream iss{profile}; s_expr_istream s_expr_input(iss); s_expr root_expr; s_expr_input >> root_expr; always_assert_log(!s_expr_input.fail(), "Failed parsing profile %s for %s: %s", profile.c_str(), SHOW(method), s_expr_input.what().c_str()); std::vector<s_expr> expr_stack; expr_stack.push_back(s_expr({root_expr})); parser_state.emplace_back(std::move(root_expr), std::move(expr_stack), false, boost::none, pair.second); break; } case 2: // A default Val. parser_state.emplace_back(s_expr(), std::vector<s_expr>(), false, std::get<2>(p), boost::none); break; default: not_reached(); } } } static SourceBlock::Val parse_val(const std::string& val_str) { if (val_str == "x") { return kXVal; } size_t after_idx; float nested_val = std::stof(val_str, &after_idx); // May throw. always_assert_log(after_idx > 0, "Could not parse first part of %s as float", val_str.c_str()); always_assert_log(after_idx + 1 < val_str.size(), "Could not find separator of %s", val_str.c_str()); always_assert_log(val_str[after_idx] == ':', "Did not find separating ':' in %s", val_str.c_str()); // This isn't efficient, but let's not play with low-level char* view. // Small-string optimization is likely enough. auto appear_part = val_str.substr(after_idx + 1); float appear100 = std::stof(appear_part, &after_idx); always_assert_log(after_idx == appear_part.size(), "Could not parse second part of %s as float", val_str.c_str()); return SourceBlock::Val{nested_val, appear100}; } void start(Block* cur) { if (serialize) { oss << "(" << id; } auto val = start_profile(cur); source_blocks::impl::BlockAccessor::push_source_block( cur, std::make_unique<SourceBlock>(method, id, val)); ++id; if (insert_after_excs) { if (cur->cfg().get_succ_edge_of_type(cur, EdgeType::EDGE_THROW) != nullptr) { // Nothing to do. return; } for (auto it = cur->begin(); it != cur->end(); ++it) { if (it->type != MFLOW_OPCODE) { continue; } if (!opcode::can_throw(it->insn->opcode())) { continue; } // Exclude throws (explicitly). if (it->insn->opcode() == OPCODE_THROW) { continue; } // Get to the next instruction. auto next_it = std::next(it); while (next_it != cur->end() && next_it->type != MFLOW_OPCODE) { ++next_it; } if (next_it == cur->end()) { break; } auto insert_after = opcode::is_move_result_any(next_it->insn->opcode()) ? next_it : it; // This is not really what the structure looks like, but easy to // parse and write. Otherwise, we would need to remember that // we had a nesting. if (serialize) { oss << "(" << id << ")"; } auto nested_val = start_profile(cur, /*empty_inner_tail=*/true); it = source_blocks::impl::BlockAccessor::insert_source_block_after( cur, insert_after, std::make_unique<SourceBlock>(method, id, nested_val)); ++id; } } } std::vector<SourceBlock::Val> start_profile(Block* cur, bool empty_inner_tail = false) { std::vector<SourceBlock::Val> ret; for (auto& p_state : parser_state) { ret.emplace_back(start_profile_one(cur, empty_inner_tail, p_state)); } return ret; } SourceBlock::Val start_profile_one(Block* cur, bool empty_inner_tail, ProfileParserState& p_state) { if (p_state.had_profile_failure) { return kFailVal; } if (p_state.root_expr.is_nil()) { if (p_state.default_val) { return *p_state.default_val; } return kFailVal; } if (p_state.expr_stack.empty()) { p_state.had_profile_failure = true; TRACE(MMINL, 3, "Failed profile matching for %s: missing element for block %zu", SHOW(method), cur->id()); return kFailVal; } std::string val_str; const s_expr& e = p_state.expr_stack.back(); s_expr tail, inner_tail; if (!s_patn({s_patn({s_patn(&val_str)}, inner_tail)}, tail).match_with(e)) { p_state.had_profile_failure = true; TRACE(MMINL, 3, "Failed profile matching for %s: cannot match string for %s", SHOW(method), e.str().c_str()); return kFailVal; } if (empty_inner_tail) { redex_assert(inner_tail.is_nil()); } auto val = parse_val(val_str); TRACE(MMINL, 5, "Started block with val=%f/%f. Popping %s, pushing %s + %s", val ? val->val : std::numeric_limits<float>::quiet_NaN(), val ? val->appear100 : std::numeric_limits<float>::quiet_NaN(), e.str().c_str(), tail.str().c_str(), inner_tail.str().c_str()); p_state.expr_stack.pop_back(); p_state.expr_stack.push_back(tail); if (!empty_inner_tail) { p_state.expr_stack.push_back(inner_tail); } return val; } static char get_edge_char(const Edge* e) { switch (e->type()) { case EDGE_BRANCH: return 'b'; case EDGE_GOTO: return 'g'; case EDGE_THROW: return 't'; case EDGE_GHOST: case EDGE_TYPE_SIZE: not_reached(); } not_reached(); // For GCC. } void edge(Block* cur, const Edge* e) { if (serialize) { oss << " " << get_edge_char(e); } edge_profile(cur, e); } void edge_profile(Block* cur, const Edge* e) { for (auto& p_state : parser_state) { edge_profile_one(cur, e, p_state); } } void edge_profile_one(Block* /*cur*/, const Edge* e, ProfileParserState& p_state) { // If running with profile, there should be at least a nil on. if (p_state.had_profile_failure || p_state.expr_stack.empty()) { return; } std::string val; s_expr& expr = p_state.expr_stack.back(); s_expr tail; if (!s_patn({s_patn(&val)}, tail).match_with(expr)) { p_state.had_profile_failure = true; TRACE(MMINL, 3, "Failed profile matching for %s: cannot match string for %s", SHOW(method), expr.str().c_str()); return; } std::string expected(1, get_edge_char(e)); if (expected != val) { p_state.had_profile_failure = true; TRACE(MMINL, 3, "Failed profile matching for %s: edge type \"%s\" did not match " "expectation \"%s\"", SHOW(method), val.c_str(), expected.c_str()); return; } TRACE(MMINL, 5, "Matched edge %s. Popping %s, pushing %s", val.c_str(), expr.str().c_str(), tail.str().c_str()); p_state.expr_stack.pop_back(); p_state.expr_stack.push_back(tail); } void end(Block* cur) { if (serialize) { oss << ")"; } end_profile(cur); } void end_profile(Block* cur) { for (auto& p_state : parser_state) { end_profile_one(cur, p_state); } } void end_profile_one(Block* /*cur*/, ProfileParserState& p_state) { if (p_state.had_profile_failure) { return; } if (p_state.root_expr.is_nil()) { return; } if (p_state.expr_stack.empty()) { TRACE(MMINL, 3, "Failed profile matching for %s: empty stack on close", SHOW(method)); p_state.had_profile_failure = true; return; } if (!p_state.expr_stack.back().is_nil()) { TRACE(MMINL, 3, "Failed profile matching for %s: edge sentinel not NIL", SHOW(method)); p_state.had_profile_failure = true; return; } TRACE(MMINL, 5, "Popping %s", p_state.expr_stack.back().str().c_str()); p_state.expr_stack.pop_back(); // Remove sentinel nil. } bool wipe_profile_failures(ControlFlowGraph& cfg) { bool ret = false; for (size_t i = 0; i != parser_state.size(); ++i) { auto& p_state = parser_state[i]; if (p_state.root_expr.is_nil()) { continue; } if (!p_state.had_profile_failure) { continue; } ret = true; if (traceEnabled(MMINL, 3) && serialize) { TRACE(MMINL, 3, "For %s, expected profile of the form %s", SHOW(method), oss.str().c_str()); } auto val = p_state.error_val ? *p_state.error_val : SourceBlock::Val::none(); for (auto* b : cfg.blocks()) { auto vec = gather_source_blocks(b); for (auto* sb : vec) { const_cast<SourceBlock*>(sb)->vals[i] = val; } } } return ret; } }; } // namespace SourceBlockConsistencyCheck& get_sbcc() { return s_sbcc; } InsertResult insert_source_blocks(DexMethod* method, ControlFlowGraph* cfg, const std::vector<ProfileData>& profiles, bool serialize, bool insert_after_excs) { InsertHelper helper(method, profiles, serialize, insert_after_excs); impl::visit_in_order( cfg, [&](Block* cur) { helper.start(cur); }, [&](Block* cur, const Edge* e) { helper.edge(cur, e); }, [&](Block* cur) { helper.end(cur); }); bool had_failures = helper.wipe_profile_failures(*cfg); return {helper.id, helper.oss.str(), !had_failures}; } bool has_source_block_positive_val(const SourceBlock* sb) { bool any_positive_val = false; if (sb != nullptr) { sb->foreach_val_early([&any_positive_val](const auto& val) { any_positive_val = val && val->val > 0.0f; return any_positive_val; }); } return any_positive_val; } namespace { size_t count_blocks( Block*, const dominators::SimpleFastDominators<cfg::GraphInterface>&) { return 1; } size_t count_block_has_sbs( Block* b, const dominators::SimpleFastDominators<cfg::GraphInterface>&) { return source_blocks::has_source_blocks(b) ? 1 : 0; } size_t count_all_sbs( Block* b, const dominators::SimpleFastDominators<cfg::GraphInterface>&) { size_t ret{0}; source_blocks::foreach_source_block( b, [&](auto* sb ATTRIBUTE_UNUSED) { ++ret; }); return ret; } // TODO: Per-interaction stats. size_t hot_immediate_dom_not_hot( Block* block, const dominators::SimpleFastDominators<cfg::GraphInterface>& dominators) { auto* first_sb_current_b = source_blocks::get_first_source_block(block); if (!has_source_block_positive_val(first_sb_current_b)) { return 0; } auto immediate_dominator = dominators.get_idom(block); if (!immediate_dominator) { return 0; } auto* first_sb_immediate_dominator = source_blocks::get_first_source_block(immediate_dominator); bool is_idom_hot = has_source_block_positive_val(first_sb_immediate_dominator); return is_idom_hot ? 0 : 1; } // TODO: This needs to be adapted to sum up the predecessors. size_t hot_no_hot_pred( Block* block, const dominators::SimpleFastDominators<cfg::GraphInterface>&) { auto* first_sb_current_b = source_blocks::get_first_source_block(block); if (!has_source_block_positive_val(first_sb_current_b)) { return 0; } for (auto predecessor : block->preds()) { auto* first_sb_pred = source_blocks::get_first_source_block(predecessor->src()); if (has_source_block_positive_val(first_sb_pred)) { return 0; } } return 1; } // TODO: Isn't that the same as before, just this time correct w/ counting? size_t hot_all_pred_cold( Block* block, const dominators::SimpleFastDominators<cfg::GraphInterface>&) { auto* first_sb_current_b = source_blocks::get_first_source_block(block); if (!has_source_block_positive_val(first_sb_current_b)) { return 0; } for (auto predecessor : block->preds()) { auto* first_sb_pred = source_blocks::get_first_source_block(predecessor->src()); if (has_source_block_positive_val(first_sb_pred)) { return 0; } } return 1; } template <typename Fn> size_t chain_hot_violations_tmpl(Block* block, const Fn& fn) { size_t sum{0}; for (auto& mie : *block) { if (mie.type != MFLOW_SOURCE_BLOCK) { continue; } for (auto* sb = mie.src_block.get(); sb->next != nullptr; sb = sb->next.get()) { // Check that each interaction has at least as high a hit value as the // next SourceBlock. auto* next = sb->next.get(); size_t local_sum{0}; for (size_t i = 0; i != sb->vals.size(); ++i) { auto sb_val = sb->get_val(i); auto next_val = next->get_val(i); if (sb_val) { if (next_val && *sb_val < *next_val) { ++local_sum; } } else if (next_val) { ++local_sum; } } sum += fn(local_sum); } } return sum; } size_t chain_hot_violations( Block* block, const dominators::SimpleFastDominators<cfg::GraphInterface>&) { return chain_hot_violations_tmpl(block, [](auto val) { return val; }); } size_t chain_hot_one_violations( Block* block, const dominators::SimpleFastDominators<cfg::GraphInterface>&) { return chain_hot_violations_tmpl(block, [](auto val) { return val > 0 ? 1 : 0; }); } // Ugly but necessary for constexpr below. using CounterFnPtr = size_t (*)( Block*, const dominators::SimpleFastDominators<cfg::GraphInterface>&); constexpr std::array<std::pair<std::string_view, CounterFnPtr>, 5> gCounters = { { {"~blocks~count", &count_blocks}, {"~blocks~with~source~blocks", &count_block_has_sbs}, {"~assessment~source~blocks~total", &count_all_sbs}, {"~flow~violation~in~chain", &chain_hot_violations}, {"~flow~violation~in~chain~one", &chain_hot_one_violations}, }}; constexpr std::array<std::pair<std::string_view, CounterFnPtr>, 3> gCountersNonEntry = {{ {"~flow~violation~idom", &hot_immediate_dom_not_hot}, {"~flow~violation~direct~predecessors", &hot_no_hot_pred}, {"~flow~violation~cold~direct~predecessors", &hot_all_pred_cold}, }}; struct SourceBlocksStats { size_t methods_with_sbs{0}; std::array<size_t, gCounters.size()> global{}; std::array<size_t, gCountersNonEntry.size()> non_entry{}; std::array<size_t, gCountersNonEntry.size()> non_entry_methods{}; std::array<std::pair<size_t, size_t>, gCountersNonEntry.size()> non_entry_min_max{}; std::array<std::pair<const DexMethod*, const DexMethod*>, gCountersNonEntry.size()> non_entry_min_max_methods{}; SourceBlocksStats& operator+=(const SourceBlocksStats& that) { methods_with_sbs += that.methods_with_sbs; for (size_t i = 0; i != global.size(); ++i) { global[i] += that.global[i]; } for (size_t i = 0; i != non_entry.size(); ++i) { non_entry[i] += that.non_entry[i]; } for (size_t i = 0; i != non_entry_methods.size(); ++i) { non_entry_methods[i] += that.non_entry_methods[i]; } for (size_t i = 0; i != non_entry_min_max.size(); ++i) { non_entry_min_max[i].first = std::min(non_entry_min_max[i].first, that.non_entry_min_max[i].first); non_entry_min_max[i].second = std::max(non_entry_min_max[i].second, that.non_entry_min_max[i].second); } for (size_t i = 0; i != non_entry_min_max_methods.size(); ++i) { auto set_min_max = [](auto& lhs, auto& rhs, auto fn) { if (rhs == nullptr) { return; } if (lhs == nullptr) { lhs = rhs; return; } auto lhs_count = lhs->get_code()->count_opcodes(); auto rhs_count = rhs->get_code()->count_opcodes(); auto op = fn(lhs_count, rhs_count); if (op == rhs_count && (op != lhs_count || compare_dexmethods(rhs, lhs))) { lhs = rhs; } }; set_min_max(non_entry_min_max_methods[i].first, that.non_entry_min_max_methods[i].first, [](auto lhs, auto rhs) { return std::min(lhs, rhs); }); set_min_max(non_entry_min_max_methods[i].second, that.non_entry_min_max_methods[i].second, [](auto lhs, auto rhs) { return std::max(lhs, rhs); }); } return *this; } void fill_derived(const DexMethod* m) { static_assert(gCounters[1].first == "~blocks~with~source~blocks"); methods_with_sbs = global[1] > 0 ? 1 : 0; for (size_t i = 0; i != non_entry.size(); ++i) { non_entry_methods[i] = non_entry[i] > 0 ? 1 : 0; non_entry_min_max[i].first = non_entry[i]; non_entry_min_max[i].second = non_entry[i]; if (non_entry[i] != 0) { non_entry_min_max_methods[i].first = m; non_entry_min_max_methods[i].second = m; } } } }; } // namespace void track_source_block_coverage(ScopedMetrics& sm, const DexStoresVector& stores) { Timer opt_timer("Calculate SourceBlock Coverage"); auto stats = walk::parallel::methods<SourceBlocksStats>( build_class_scope(stores), [](DexMethod* m) -> SourceBlocksStats { SourceBlocksStats ret; auto code = m->get_code(); if (!code) { return ret; } code->build_cfg(/* editable */ true); auto& cfg = code->cfg(); auto dominators = dominators::SimpleFastDominators<cfg::GraphInterface>(cfg); bool seen_dir_cold_dir_pred = false; bool seen_idom_viol = false; bool seen_direct_pred_viol = false; bool seen_sb = false; for (auto block : cfg.blocks()) { for (size_t i = 0; i != gCounters.size(); ++i) { ret.global[i] += (*gCounters[i].second)(block, dominators); } if (block != cfg.entry_block()) { for (size_t i = 0; i != gCountersNonEntry.size(); ++i) { ret.non_entry[i] += (*gCountersNonEntry[i].second)(block, dominators); } } } ret.fill_derived(m); code->clear_cfg(); return ret; }); size_t consistency_check_violations = s_sbcc.is_initialized() ? s_sbcc.run(build_class_scope(stores)) : 0; sm.set_metric("~consistency~check~violations", consistency_check_violations); sm.set_metric("~assessment~methods~with~sbs", stats.methods_with_sbs); for (size_t i = 0; i != gCounters.size(); ++i) { sm.set_metric(gCounters[i].first, stats.global[i]); } for (size_t i = 0; i != gCountersNonEntry.size(); ++i) { sm.set_metric(gCountersNonEntry[i].first, stats.non_entry[i]); auto scope = sm.scope(std::string(gCountersNonEntry[i].first)); sm.set_metric("methods", stats.non_entry_methods[i]); sm.set_metric("min", stats.non_entry_min_max[i].first); sm.set_metric("max", stats.non_entry_min_max[i].second); auto min_max = [&](const DexMethod* m, const char* name) { if (m != nullptr) { auto min_max_scope = sm.scope(name); sm.set_metric(show_deobfuscated(m), m->get_code()->count_opcodes()); } }; min_max(stats.non_entry_min_max_methods[i].first, "min_method"); min_max(stats.non_entry_min_max_methods[i].second, "max_method"); } } } // namespace source_blocks
mit
kinkinweb/lhvb
vendor/sonata-project/ecommerce/src/Component/Order/OrderInterface.php
12273
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\Component\Order; use Sonata\Component\Currency\CurrencyInterface; use Sonata\Component\Customer\CustomerInterface; interface OrderInterface { const STATUS_OPEN = 0; // created but not validated const STATUS_PENDING = 1; // waiting from action from the user const STATUS_VALIDATED = 2; // the order is validated does not mean the payment is ok const STATUS_CANCELLED = 3; // the order is cancelled const STATUS_ERROR = 4; // the order has an error const STATUS_STOPPED = 5; // use if the subscription has been cancelled/stopped /** * @return int the order id */ public function getId(); /** * Set reference. * * @param string $reference */ public function setReference($reference); /** * Get reference. * * @return string $reference */ public function getReference(); /** * Set payment method. * * @param string $paymentMethod */ public function setPaymentMethod($paymentMethod); /** * Get payment method. * * @return string */ public function getPaymentMethod(); /** * Set delivery method. * * @param string $deliveryMethod */ public function setDeliveryMethod($deliveryMethod); /** * Get delivery method. * * @return string $deliveryMethod */ public function getDeliveryMethod(); /** * Set currency. * * @param CurrencyInterface $currency */ public function setCurrency(CurrencyInterface $currency); /** * Get currency. * * @return CurrencyInterface $currency */ public function getCurrency(); /** * @return string */ public function getLocale(); /** * @param string $locale */ public function setLocale($locale); /** * Set status. * * @param int $status */ public function setStatus($status); /** * Get status. * * @return int $status */ public function getStatus(); /** * Set payment status. * * @param int $paymentStatus */ public function setPaymentStatus($paymentStatus); /** * Get payment status. * * @return int $paymentStatus */ public function getPaymentStatus(); /** * Set delivery status. * * @param int $deliveryStatus */ public function setDeliveryStatus($deliveryStatus); /** * Get delivery status. * * @return int $deliveryStatus */ public function getDeliveryStatus(); /** * Set validated at. * * @param \Datetime $validatedAt */ public function setValidatedAt(\DateTime $validatedAt = null); /** * Get validated at. * * @return \Datetime $validatedAt */ public function getValidatedAt(); /** * Set username. * * @param string $username */ public function setUsername($username); /** * Get username. * * @return string $username */ public function getUsername(); /** * Set totalInc. * * @param float $totalInc */ public function setTotalInc($totalInc); /** * Get totalInc. * * @return float $totalInc */ public function getTotalInc(); /** * Set totalExcl. * * @param float $totalExcl */ public function setTotalExcl($totalExcl); /** * Get totalExcl. * * @return float $totalExcl */ public function getTotalExcl(); /** * Set delivery cost (VAT included). * * @param float $deliveryCost */ public function setDeliveryCost($deliveryCost); /** * Get delivery cost. * * @return float $deliveryCost */ public function getDeliveryCost(); /** * Set delivery VAT. * * @param float $deliveryVat */ public function setDeliveryVat($deliveryVat); /** * Get delivery VAT. * * @return float $deliveryVat */ public function getDeliveryVat(); /** * Set billing name. * * @param string $billingName */ public function setBillingName($billingName); /** * Get billing name. * * @return string $billingName */ public function getBillingName(); /** * Set billing phone. * * @param string $billingPhone */ public function setBillingPhone($billingPhone); /** * Get billing phone. * * @return string $billingPhone */ public function getBillingPhone(); /** * Set billing address1. * * @param string $billingAddress1 */ public function setBillingAddress1($billingAddress1); /** * Get billing address1. * * @return string $billingAddress1 */ public function getBillingAddress1(); /** * Set billing address2. * * @param string $billingAddress2 */ public function setBillingAddress2($billingAddress2); /** * Get billing address2. * * @return string $billingAddress2 */ public function getBillingAddress2(); /** * Set billing address3. * * @param string $billingAddress3 */ public function setBillingAddress3($billingAddress3); /** * Get billing address3. * * @return string $billingAddress3 */ public function getBillingAddress3(); /** * Set billing city. * * @param string $billingCity */ public function setBillingCity($billingCity); /** * Get billing city. * * @return string $billingCity */ public function getBillingCity(); /** * Set billing postcode. * * @param string $billingPostcode */ public function setBillingPostcode($billingPostcode); /** * Get billing postcode. * * @return string $billingPostcode */ public function getBillingPostcode(); /** * Set billing country code. * * @param string $billingCountryCode */ public function setBillingCountryCode($billingCountryCode); /** * Get billing country. * * @return string $billingCountryCode */ public function getBillingCountryCode(); /** * Set billing fax. * * @param string $billingFax */ public function setBillingFax($billingFax); /** * Get billing fax. * * @return string $billingFax */ public function getBillingFax(); /** * Set billing email. * * @param string $billingEmail */ public function setBillingEmail($billingEmail); /** * Get billing email. * * @return string $billingEmail */ public function getBillingEmail(); /** * Set billing mobile. * * @param string $billingMobile */ public function setBillingMobile($billingMobile); /** * Get billing mobile. * * @return string $billingMobile */ public function getBillingMobile(); /** * Set shipping name. * * @param string $shippingName */ public function setShippingName($shippingName); /** * Get shipping name. * * @return string $shippingName */ public function getShippingName(); /** * Set shipping phone. * * @param string $shippingPhone */ public function setShippingPhone($shippingPhone); /** * Get shipping phone. * * @return string $shippingPhone */ public function getShippingPhone(); /** * Set shipping address1. * * @param string $shippingAddress1 */ public function setShippingAddress1($shippingAddress1); /** * Get shipping address1. * * @return string $shippingAddress1 */ public function getShippingAddress1(); /** * Set shipping address2. * * @param string $shippingAddress2 */ public function setShippingAddress2($shippingAddress2); /** * Get shipping address2. * * @return string $shippingAddress2 */ public function getShippingAddress2(); /** * Set shipping address3. * * @param string $shippingAddress3 */ public function setShippingAddress3($shippingAddress3); /** * Get shipping address3. * * @return string $shippingAddress3 */ public function getShippingAddress3(); /** * Set shipping city. * * @param string $shippingCity */ public function setShippingCity($shippingCity); /** * Get shipping city. * * @return string $shippingCity */ public function getShippingCity(); /** * Set shipping postcode. * * @param string $shippingPostcode */ public function setShippingPostcode($shippingPostcode); /** * Get shipping postcode. * * @return string $shippingPostcode */ public function getShippingPostcode(); /** * Set shipping country. * * @param string $shippingCountryCode */ public function setShippingCountryCode($shippingCountryCode); /** * Get shipping country. * * @return string $shippingCountry */ public function getShippingCountryCode(); /** * Set shipping fax. * * @param string $shippingFax */ public function setShippingFax($shippingFax); /** * Get shipping fax. * * @return string $shippingFax */ public function getShippingFax(); /** * Set shipping email. * * @param string $shippingEmail */ public function setShippingEmail($shippingEmail); /** * Get shipping email. * * @return string $shippingEmail */ public function getShippingEmail(); /** * Set shipping mobile. * * @param string $shippingMobile */ public function setShippingMobile($shippingMobile); /** * Get shipping mobile. * * @return string $shippingMobile */ public function getShippingMobile(); /** * @return array */ public function getOrderElements(); /** * @param OrderElementInterface $orderElement */ public function addOrderElement(OrderElementInterface $orderElement); /** * return true if the order is validated. * * @return bool */ public function isValidated(); /** * @return bool true if cancelled, else false */ public function isCancelled(); /** * @return bool true if the order can be cancelled */ public function isCancellable(); /** * @return bool true if pending, else false */ public function isPending(); /** * Return true if the order is open. * * @return bool */ public function isOpen(); /** * Return true if the order has an error. * * @return bool */ public function isError(); /** * @param \DateTime|null $createdAt */ public function setCreatedAt(\DateTime $createdAt = null); /** * @return \DateTime */ public function getCreatedAt(); /** * @param \DateTime|null $updatedAt */ public function setUpdatedAt(\DateTime $updatedAt = null); /** * @return \DateTime */ public function getUpdatedAt(); /** * Add order elements. * * @param OrderElementInterface $orderElements */ public function addOrderElements(OrderElementInterface $orderElements); /** * @param array $orderElements * * @return array */ public function setOrderElements($orderElements); /** * @param CustomerInterface $customer */ public function setCustomer(CustomerInterface $customer); /** * @return CustomerInterface */ public function getCustomer(); /** * @return float */ public function getVat(); }
mit
ailyenko/JavaRush
src/com/javarush/test/level25/lesson02/home01/Columnable.java
719
package com.javarush.test.level25.lesson02.home01; interface Columnable { /** * @return полное имя колонки */ String getColumnName(); /** * Возвращает true, если колонка видимая, иначе false */ boolean isShown(); /** * Скрывает колонку - маркирует колонку -1 в массиве realOrder. * Сдвигает индексы отображаемых колонок, которые идут после скрытой */ void hide(); /** * Возвращает порядок константы в энуме. * * @return порядок константы в энуме */ int ordinal(); }
mit
Innmind/rest-server
tests/Definition/IdentityTest.php
405
<?php declare(strict_types = 1); namespace Tests\Innmind\Rest\Server\Definition; use Innmind\Rest\Server\Definition\Identity; use PHPUnit\Framework\TestCase; class IdentityTest extends TestCase { public function testInterface() { $identity = new Identity('foo'); $this->assertSame('foo', $identity->property()); $this->assertSame('foo', $identity->toString()); } }
mit
Jainteto/itp
itp-core/src/main/java/org/jainteto/itp/core/transport/Message.java
1434
package org.jainteto.itp.core.transport; import java.io.Serializable; public class Message implements Serializable { public static final int STATUS_NO = 0; public static final int STATUS_MESSAGE = 1; public static final int STATUS_ERROR = 2; private static final Message NO_MESSAGE_Object = new Message("", STATUS_NO); private final String message; private final int status; public static Message noMessage() { return NO_MESSAGE_Object; } public static Message message(String message) { return new Message(message, STATUS_MESSAGE); } public static Message error(String message) { return new Message(message, STATUS_ERROR); } private Message(String message, int status) { this.message = message == null ? "" : message; this.status = status; } public String getMessage() { return message; } public int getMessageStatus() { return status; } public String toString() { return message; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Message)) return false; Message message = (Message)obj; return this.status == message.getMessageStatus() && this.message.equals(message.getMessage()); } @Override public int hashCode() { return 31 * message.hashCode() + status; } }
mit
cmlaidlaw/hoipost
private/conf/LocationNodes.php
78132
<?php $nodes = array( 0 => array('city' => 'Aba', 'lat' => 5.10, 'lng' => 7.35, 'country' => 'Nigeria'), 1 => array('city' => 'Abeokuta', 'lat' => 7.16, 'lng' => 3.35, 'country' => 'Nigeria'), 2 => array('city' => 'Abidjan', 'lat' => 5.33, 'lng' => -4.03, 'country' => 'Ivory Coast'), 3 => array('city' => 'Abu Dhabi', 'lat' => 24.48, 'lng' => 54.37, 'country' => 'United Arab Emirates'), 4 => array('city' => 'Abuja', 'lat' => 9.06, 'lng' => 7.49, 'country' => 'Nigeria'), 5 => array('city' => 'Acapulco de Juárez', 'lat' => 16.86, 'lng' => -99.89, 'country' => 'Mexico'), 6 => array('city' => 'Accra', 'lat' => 5.56, 'lng' => -0.20, 'country' => 'Ghana'), 7 => array('city' => '\'Adan', 'lat' => 12.79, 'lng' => 45.03, 'country' => 'Yemen'), 8 => array('city' => 'Adana', 'lat' => 37.00, 'lng' => 35.32, 'country' => 'Turkey'), 9 => array('city' => 'ad-Dammām', 'lat' => 26.43, 'lng' => 50.10, 'country' => 'Saudi Arabia'), 10 => array('city' => 'Āddīs Ābebā', 'lat' => 9.03, 'lng' => 38.74, 'country' => 'Ethiopia'), 11 => array('city' => 'Adelaide', 'lat' => -34.93, 'lng' => 138.60, 'country' => 'Australia'), 12 => array('city' => 'Agadir', 'lat' => 30.42, 'lng' => -9.61, 'country' => 'Morocco'), 13 => array('city' => 'Āgra', 'lat' => 27.19, 'lng' => 78.01, 'country' => 'India'), 14 => array('city' => 'Aguascalientes', 'lat' => 21.88, 'lng' => -102.30, 'country' => 'Mexico'), 15 => array('city' => 'Ahmadābād', 'lat' => 23.03, 'lng' => 72.58, 'country' => 'India'), 16 => array('city' => 'Ahvāz', 'lat' => 31.28, 'lng' => 48.72, 'country' => 'Iran'), 17 => array('city' => 'Ajmer', 'lat' => 26.45, 'lng' => 74.64, 'country' => 'India'), 18 => array('city' => 'Aksu', 'lat' => 41.15, 'lng' => 80.25, 'country' => 'China'), 19 => array('city' => 'Akure', 'lat' => 7.25, 'lng' => 5.19, 'country' => 'Nigeria'), 20 => array('city' => 'al-\'Amārah', 'lat' => 31.84, 'lng' => 47.15, 'country' => 'Iraq'), 21 => array('city' => 'al-\'Ayn', 'lat' => 24.23, 'lng' => 55.74, 'country' => 'United Arab Emirates'), 22 => array('city' => 'al-Başrah', 'lat' => 30.53, 'lng' => 47.82, 'country' => 'Iraq'), 23 => array('city' => 'Albuquerque', 'lat' => 35.12, 'lng' => -106.62, 'country' => 'USA'), 24 => array('city' => 'Aleppo', 'lat' => 36.23, 'lng' => 37.17, 'country' => 'Syria'), 25 => array('city' => 'Alexandria', 'lat' => 31.22, 'lng' => 29.95, 'country' => 'Egypt'), 26 => array('city' => 'Algiers', 'lat' => 36.77, 'lng' => 3.04, 'country' => 'Algeria'), 27 => array('city' => 'al-Khartūm Bahrī', 'lat' => 15.64, 'lng' => 32.52, 'country' => 'Sudan'), 28 => array('city' => 'al-Hillah', 'lat' => 32.48, 'lng' => 44.43, 'country' => 'Iraq'), 29 => array('city' => 'Alīgarh', 'lat' => 27.89, 'lng' => 78.06, 'country' => 'India'), 30 => array('city' => 'Allahābād', 'lat' => 25.45, 'lng' => 81.84, 'country' => 'India'), 31 => array('city' => 'al-Madīnah', 'lat' => 24.48, 'lng' => 39.59, 'country' => 'Saudi Arabia'), 32 => array('city' => 'Almaty', 'lat' => 43.32, 'lng' => 76.92, 'country' => 'Kazakhstan'), 33 => array('city' => 'al-Mawşil', 'lat' => 36.34, 'lng' => 43.14, 'country' => 'Iraq'), 34 => array('city' => '\'Ammān', 'lat' => 31.95, 'lng' => 35.93, 'country' => 'Jordan'), 35 => array('city' => 'Amrāvati', 'lat' => 20.95, 'lng' => 77.76, 'country' => 'India'), 36 => array('city' => 'Amritsar', 'lat' => 31.64, 'lng' => 74.87, 'country' => 'India'), 37 => array('city' => 'Amsterdam', 'lat' => 52.37, 'lng' => 4.89, 'country' => 'Netherlands'), 38 => array('city' => 'Ankara', 'lat' => 39.93, 'lng' => 32.85, 'country' => 'Turkey'), 39 => array('city' => 'an-Najaf', 'lat' => 32.00, 'lng' => 44.34, 'country' => 'Iraq'), 40 => array('city' => 'Ansan', 'lat' => 37.35, 'lng' => 126.86, 'country' => 'Korea (South)'), 41 => array('city' => 'Anshan', 'lat' => 41.12, 'lng' => 122.95, 'country' => 'China'), 42 => array('city' => 'Antalya', 'lat' => 36.89, 'lng' => 30.71, 'country' => 'Turkey'), 43 => array('city' => 'Antananarivo', 'lat' => -18.89, 'lng' => 47.51, 'country' => 'Madagascar'), 44 => array('city' => 'Antipolo', 'lat' => 14.63, 'lng' => 121.12, 'country' => 'Philippines'), 45 => array('city' => 'Anyang', 'lat' => 36.08, 'lng' => 114.35, 'country' => 'China'), 46 => array('city' => 'Anyang', 'lat' => 37.39, 'lng' => 126.92, 'country' => 'Korea (South)'), 47 => array('city' => 'Aracaju', 'lat' => -10.91, 'lng' => -37.07, 'country' => 'Brazil'), 48 => array('city' => 'Arequipa', 'lat' => -16.39, 'lng' => -71.53, 'country' => 'Peru'), 49 => array('city' => 'Arusha', 'lat' => -3.36, 'lng' => 36.67, 'country' => 'Tanzania'), 50 => array('city' => 'Asansol', 'lat' => 23.69, 'lng' => 86.98, 'country' => 'India'), 51 => array('city' => 'Aşgabat', 'lat' => 37.95, 'lng' => 58.38, 'country' => 'Turkmenistan'), 52 => array('city' => 'Āsmara', 'lat' => 15.33, 'lng' => 38.94, 'country' => 'Eritrea'), 53 => array('city' => 'as-Sulaymānīyah', 'lat' => 35.56, 'lng' => 45.43, 'country' => 'Iraq'), 54 => array('city' => 'Asunción', 'lat' => -25.30, 'lng' => -57.63, 'country' => 'Paraguay'), 55 => array('city' => 'Athens', 'lat' => 37.98, 'lng' => 23.73, 'country' => 'Greece'), 56 => array('city' => 'aţ-Ţā\'īf', 'lat' => 21.26, 'lng' => 40.38, 'country' => 'Saudi Arabia'), 57 => array('city' => 'Aurangābād', 'lat' => 19.89, 'lng' => 75.32, 'country' => 'India'), 58 => array('city' => 'Austin', 'lat' => 30.31, 'lng' => -97.75, 'country' => 'USA'), 59 => array('city' => 'Bacolod', 'lat' => 10.67, 'lng' => 122.95, 'country' => 'Philippines'), 60 => array('city' => 'Bacoor', 'lat' => 14.46, 'lng' => 120.93, 'country' => 'Philippines'), 61 => array('city' => 'Bagdād', 'lat' => 33.33, 'lng' => 44.44, 'country' => 'Iraq'), 62 => array('city' => 'Bahāwalpur', 'lat' => 29.39, 'lng' => 71.67, 'country' => 'Pakistan'), 63 => array('city' => 'Baku', 'lat' => 40.39, 'lng' => 49.86, 'country' => 'Azerbaijan'), 64 => array('city' => 'Balikpapan', 'lat' => -1.26, 'lng' => 116.83, 'country' => 'Indonesia'), 65 => array('city' => 'Baltimore', 'lat' => 39.30, 'lng' => -76.61, 'country' => 'USA'), 66 => array('city' => 'Bamako', 'lat' => 12.65, 'lng' => -7.99, 'country' => 'Mali'), 67 => array('city' => 'Bandar Lampung', 'lat' => -5.44, 'lng' => 105.27, 'country' => 'Indonesia'), 68 => array('city' => 'Bandung', 'lat' => -6.91, 'lng' => 107.60, 'country' => 'Indonesia'), 69 => array('city' => 'Bangalore', 'lat' => 12.97, 'lng' => 77.56, 'country' => 'India'), 70 => array('city' => 'Bangāzī', 'lat' => 32.11, 'lng' => 20.08, 'country' => 'Libya'), 71 => array('city' => 'Bangkok', 'lat' => 13.73, 'lng' => 100.50, 'country' => 'Thailand'), 72 => array('city' => 'Bangui', 'lat' => 4.36, 'lng' => 18.56, 'country' => 'Central African Republic'), 73 => array('city' => 'Banjarmasin', 'lat' => -3.33, 'lng' => 114.59, 'country' => 'Indonesia'), 74 => array('city' => 'Bănqiáo', 'lat' => 25.02, 'lng' => 121.44, 'country' => 'Taiwan'), 75 => array('city' => 'Baoding', 'lat' => 38.87, 'lng' => 115.48, 'country' => 'China'), 76 => array('city' => 'Baotou', 'lat' => 40.60, 'lng' => 110.05, 'country' => 'China'), 77 => array('city' => 'Barcelona', 'lat' => 41.40, 'lng' => 2.17, 'country' => 'Spain'), 78 => array('city' => 'Bareli', 'lat' => 28.36, 'lng' => 79.41, 'country' => 'India'), 79 => array('city' => 'Barnaul', 'lat' => 53.36, 'lng' => 83.75, 'country' => 'Russia'), 80 => array('city' => 'Barquisimeto', 'lat' => 10.05, 'lng' => -69.30, 'country' => 'Venezuela'), 81 => array('city' => 'Barranquilla', 'lat' => 10.96, 'lng' => -74.80, 'country' => 'Colombia'), 82 => array('city' => 'Batam', 'lat' => 1.03, 'lng' => 103.92, 'country' => 'Indonesia'), 83 => array('city' => 'Bayrūt', 'lat' => 33.89, 'lng' => 35.50, 'country' => 'Lebanon'), 84 => array('city' => 'Bekasi', 'lat' => -6.22, 'lng' => 106.97, 'country' => 'Indonesia'), 85 => array('city' => 'Belém', 'lat' => -1.44, 'lng' => -48.50, 'country' => 'Brazil'), 86 => array('city' => 'Belgrade', 'lat' => 44.83, 'lng' => 20.50, 'country' => 'Serbia'), 87 => array('city' => 'Belo Horizonte', 'lat' => -19.92, 'lng' => -43.94, 'country' => 'Brazil'), 88 => array('city' => 'Bengbu', 'lat' => 32.95, 'lng' => 117.33, 'country' => 'China'), 89 => array('city' => 'Benin', 'lat' => 6.34, 'lng' => 5.62, 'country' => 'Nigeria'), 90 => array('city' => 'Benoni', 'lat' => -26.15, 'lng' => 28.33, 'country' => 'South Africa'), 91 => array('city' => 'Benxi', 'lat' => 41.33, 'lng' => 123.75, 'country' => 'China'), 92 => array('city' => 'Berlin', 'lat' => 52.52, 'lng' => 13.38, 'country' => 'Germany'), 93 => array('city' => 'Bhātpāra', 'lat' => 22.89, 'lng' => 88.42, 'country' => 'India'), 94 => array('city' => 'Bhāvnagar', 'lat' => 21.79, 'lng' => 72.13, 'country' => 'India'), 95 => array('city' => 'Bhilai', 'lat' => 21.21, 'lng' => 81.38, 'country' => 'India'), 96 => array('city' => 'Bhiwandi', 'lat' => 19.30, 'lng' => 73.05, 'country' => 'India'), 97 => array('city' => 'Bhopāl', 'lat' => 23.24, 'lng' => 77.40, 'country' => 'India'), 98 => array('city' => 'Bhubaneswar', 'lat' => 20.27, 'lng' => 85.84, 'country' => 'India'), 99 => array('city' => 'Bīkāner', 'lat' => 28.03, 'lng' => 73.32, 'country' => 'India'), 100 => array('city' => 'Birmingham', 'lat' => 52.48, 'lng' => -1.91, 'country' => 'United Kingdom'), 101 => array('city' => 'Bişkek', 'lat' => 42.87, 'lng' => 74.57, 'country' => 'Kyrgyzstan'), 102 => array('city' => 'Blantyre', 'lat' => -15.79, 'lng' => 34.99, 'country' => 'Malawi'), 103 => array('city' => 'Bloemfontein', 'lat' => -29.15, 'lng' => 26.23, 'country' => 'South Africa'), 104 => array('city' => 'Bobo Dioulasso', 'lat' => 11.18, 'lng' => -4.29, 'country' => 'Burkina Faso'), 105 => array('city' => 'Bogor', 'lat' => -6.58, 'lng' => 106.79, 'country' => 'Indonesia'), 106 => array('city' => 'Bogotá', 'lat' => 4.63, 'lng' => -74.09, 'country' => 'Colombia'), 107 => array('city' => 'Boksburg', 'lat' => -26.27, 'lng' => 28.23, 'country' => 'South Africa'), 108 => array('city' => 'Bombay', 'lat' => 18.96, 'lng' => 72.82, 'country' => 'India'), 109 => array('city' => 'Boston', 'lat' => 42.34, 'lng' => -71.02, 'country' => 'USA'), 110 => array('city' => 'Bouaké', 'lat' => 7.69, 'lng' => -5.03, 'country' => 'Ivory Coast'), 111 => array('city' => 'Brasília', 'lat' => -15.78, 'lng' => -47.91, 'country' => 'Brazil'), 112 => array('city' => 'Brazzaville', 'lat' => -4.25, 'lng' => 15.26, 'country' => 'Congo'), 113 => array('city' => 'Bremen', 'lat' => 53.08, 'lng' => 8.81, 'country' => 'Germany'), 114 => array('city' => 'Brisbane', 'lat' => -27.46, 'lng' => 153.02, 'country' => 'Australia'), 115 => array('city' => 'Brussels', 'lat' => 50.83, 'lng' => 4.33, 'country' => 'Belgium'), 116 => array('city' => 'Bucaramanga', 'lat' => 7.13, 'lng' => -73.13, 'country' => 'Colombia'), 117 => array('city' => 'Bucharest', 'lat' => 44.44, 'lng' => 26.10, 'country' => 'Romania'), 118 => array('city' => 'Budapest', 'lat' => 47.51, 'lng' => 19.08, 'country' => 'Hungary'), 119 => array('city' => 'Buenos Aires', 'lat' => -34.61, 'lng' => -58.37, 'country' => 'Argentina'), 120 => array('city' => 'Bukavu', 'lat' => -2.51, 'lng' => 28.84, 'country' => 'Congo (Dem. Rep.)'), 121 => array('city' => 'Bulawayo', 'lat' => -20.17, 'lng' => 28.58, 'country' => 'Zimbabwe'), 122 => array('city' => 'Bursa', 'lat' => 40.20, 'lng' => 29.08, 'country' => 'Turkey'), 123 => array('city' => 'Būr Sūdān', 'lat' => 19.63, 'lng' => 37.12, 'country' => 'Sudan'), 124 => array('city' => 'Cagayan de Oro', 'lat' => 8.48, 'lng' => 124.64, 'country' => 'Philippines'), 125 => array('city' => 'Cairo', 'lat' => 30.06, 'lng' => 31.25, 'country' => 'Egypt'), 126 => array('city' => 'Calcutta', 'lat' => 22.57, 'lng' => 88.36, 'country' => 'India'), 127 => array('city' => 'Calgary', 'lat' => 51.05, 'lng' => -114.06, 'country' => 'Canada'), 128 => array('city' => 'Cali', 'lat' => 3.44, 'lng' => -76.52, 'country' => 'Colombia'), 129 => array('city' => 'Campinas', 'lat' => -22.91, 'lng' => -47.08, 'country' => 'Brazil'), 130 => array('city' => 'Campo Grande', 'lat' => -20.45, 'lng' => -54.63, 'country' => 'Brazil'), 131 => array('city' => 'Cancún', 'lat' => 21.16, 'lng' => -86.85, 'country' => 'Mexico'), 132 => array('city' => 'Cangzhou', 'lat' => 38.32, 'lng' => 116.87, 'country' => 'China'), 133 => array('city' => 'Cape Town', 'lat' => -33.93, 'lng' => 18.46, 'country' => 'South Africa'), 134 => array('city' => 'Caracas', 'lat' => 10.54, 'lng' => -66.93, 'country' => 'Venezuela'), 135 => array('city' => 'Carrefour', 'lat' => 18.53, 'lng' => -72.42, 'country' => 'Haiti'), 136 => array('city' => 'Cartagena', 'lat' => 10.40, 'lng' => -75.50, 'country' => 'Colombia'), 137 => array('city' => 'Casablanca', 'lat' => 33.60, 'lng' => -7.62, 'country' => 'Morocco'), 138 => array('city' => 'Cebu', 'lat' => 10.32, 'lng' => 123.75, 'country' => 'Philippines'), 139 => array('city' => 'Chandīgarh', 'lat' => 30.75, 'lng' => 76.78, 'country' => 'India'), 140 => array('city' => 'Changchun', 'lat' => 43.87, 'lng' => 125.35, 'country' => 'China'), 141 => array('city' => 'Changde', 'lat' => 29.03, 'lng' => 111.68, 'country' => 'China'), 142 => array('city' => 'Changsha', 'lat' => 28.20, 'lng' => 112.97, 'country' => 'China'), 143 => array('city' => 'Changwŏn', 'lat' => 35.27, 'lng' => 128.62, 'country' => 'Korea (South)'), 144 => array('city' => 'Changzhi', 'lat' => 35.22, 'lng' => 111.75, 'country' => 'China'), 145 => array('city' => 'Changzhou', 'lat' => 31.78, 'lng' => 119.97, 'country' => 'China'), 146 => array('city' => 'Chaoyang', 'lat' => 41.55, 'lng' => 120.42, 'country' => 'China'), 147 => array('city' => 'Chaozhou', 'lat' => 23.67, 'lng' => 116.64, 'country' => 'China'), 148 => array('city' => 'Charlotte', 'lat' => 35.20, 'lng' => -80.83, 'country' => 'USA'), 149 => array('city' => 'Chāţţagām', 'lat' => 22.33, 'lng' => 91.81, 'country' => 'Bangladesh'), 150 => array('city' => 'Chelyabinsk', 'lat' => 55.15, 'lng' => 61.43, 'country' => 'Russia'), 151 => array('city' => 'Chengdu', 'lat' => 30.67, 'lng' => 104.07, 'country' => 'China'), 152 => array('city' => 'Chiba', 'lat' => 35.61, 'lng' => 140.11, 'country' => 'Japan'), 153 => array('city' => 'Chicago', 'lat' => 41.84, 'lng' => -87.68, 'country' => 'USA'), 154 => array('city' => 'Chiclayo', 'lat' => -6.76, 'lng' => -79.84, 'country' => 'Peru'), 155 => array('city' => 'Chihuahua', 'lat' => 28.64, 'lng' => -106.09, 'country' => 'Mexico'), 156 => array('city' => 'Chimalhuacán', 'lat' => 19.44, 'lng' => -98.95, 'country' => 'Mexico'), 157 => array('city' => 'Chişinău', 'lat' => 47.03, 'lng' => 28.83, 'country' => 'Moldova'), 158 => array('city' => 'Chŏnan', 'lat' => 36.81, 'lng' => 127.16, 'country' => 'Korea (South)'), 159 => array('city' => 'Chŏngju', 'lat' => 36.64, 'lng' => 127.50, 'country' => 'Korea (South)'), 160 => array('city' => 'Chongqing', 'lat' => 29.57, 'lng' => 106.58, 'country' => 'China'), 161 => array('city' => 'Chŏnju', 'lat' => 35.83, 'lng' => 127.14, 'country' => 'Korea (South)'), 162 => array('city' => 'Cimahi', 'lat' => -6.83, 'lng' => 107.48, 'country' => 'Indonesia'), 163 => array('city' => 'Ciudad Apodaca', 'lat' => 25.78, 'lng' => -100.19, 'country' => 'Mexico'), 164 => array('city' => 'Ciudad de México', 'lat' => 19.36, 'lng' => -99.09, 'country' => 'Mexico'), 165 => array('city' => 'Ciudad Guayana', 'lat' => 8.37, 'lng' => -62.62, 'country' => 'Venezuela'), 166 => array('city' => 'Ciudad Nezahualcóyotl', 'lat' => 19.40, 'lng' => -98.99, 'country' => 'Mexico'), 167 => array('city' => 'Cochabamba', 'lat' => -17.38, 'lng' => -66.17, 'country' => 'Bolivia'), 168 => array('city' => 'Cologne', 'lat' => 50.95, 'lng' => 6.97, 'country' => 'Germany'), 169 => array('city' => 'Colombo', 'lat' => 6.93, 'lng' => 79.85, 'country' => 'Sri Lanka'), 170 => array('city' => 'Columbus', 'lat' => 39.99, 'lng' => -82.99, 'country' => 'USA'), 171 => array('city' => 'Conakry', 'lat' => 9.55, 'lng' => -13.67, 'country' => 'Guinea'), 172 => array('city' => 'Contagem', 'lat' => -19.91, 'lng' => -44.10, 'country' => 'Brazil'), 173 => array('city' => 'Córdoba', 'lat' => -31.40, 'lng' => -64.19, 'country' => 'Argentina'), 174 => array('city' => 'Cotonou', 'lat' => 6.36, 'lng' => 2.44, 'country' => 'Benin'), 175 => array('city' => 'Cracow', 'lat' => 50.06, 'lng' => 19.96, 'country' => 'Poland'), 176 => array('city' => 'Cúcuta', 'lat' => 7.88, 'lng' => -72.51, 'country' => 'Colombia'), 177 => array('city' => 'Cuiabá', 'lat' => -15.61, 'lng' => -56.09, 'country' => 'Brazil'), 178 => array('city' => 'Culiacán Rosales', 'lat' => 24.79, 'lng' => -107.40, 'country' => 'Mexico'), 179 => array('city' => 'Curitiba', 'lat' => -25.42, 'lng' => -49.29, 'country' => 'Brazil'), 180 => array('city' => 'Dadiangas', 'lat' => 6.11, 'lng' => 125.17, 'country' => 'Philippines'), 181 => array('city' => 'Dakar', 'lat' => 14.72, 'lng' => -17.48, 'country' => 'Senegal'), 182 => array('city' => 'Dalian', 'lat' => 38.92, 'lng' => 121.65, 'country' => 'China'), 183 => array('city' => 'Dallas', 'lat' => 32.79, 'lng' => -96.77, 'country' => 'USA'), 184 => array('city' => 'Damascus', 'lat' => 33.50, 'lng' => 36.32, 'country' => 'Syria'), 185 => array('city' => 'Dandong', 'lat' => 40.13, 'lng' => 124.40, 'country' => 'China'), 186 => array('city' => 'Dar es Salaam', 'lat' => -6.82, 'lng' => 39.28, 'country' => 'Tanzania'), 187 => array('city' => 'Dasarahalli', 'lat' => 13.01, 'lng' => 77.49, 'country' => 'India'), 188 => array('city' => 'Dasmariñas', 'lat' => 14.33, 'lng' => 120.94, 'country' => 'Philippines'), 189 => array('city' => 'Datong', 'lat' => 40.08, 'lng' => 113.30, 'country' => 'China'), 190 => array('city' => 'Davao', 'lat' => 7.07, 'lng' => 125.61, 'country' => 'Philippines'), 191 => array('city' => 'Dehra Dūn', 'lat' => 30.34, 'lng' => 78.05, 'country' => 'India'), 192 => array('city' => 'Delhi', 'lat' => 28.67, 'lng' => 77.21, 'country' => 'India'), 193 => array('city' => 'Denpasar', 'lat' => -8.65, 'lng' => 115.22, 'country' => 'Indonesia'), 194 => array('city' => 'Denver', 'lat' => 39.77, 'lng' => -104.87, 'country' => 'USA'), 195 => array('city' => 'Depok', 'lat' => -6.39, 'lng' => 106.83, 'country' => 'Indonesia'), 196 => array('city' => 'Detroit', 'lat' => 42.38, 'lng' => -83.10, 'country' => 'USA'), 197 => array('city' => 'Dezhou', 'lat' => 37.45, 'lng' => 116.30, 'country' => 'China'), 198 => array('city' => 'Dhāka', 'lat' => 23.70, 'lng' => 90.39, 'country' => 'Bangladesh'), 199 => array('city' => 'Diyarbakır', 'lat' => 37.92, 'lng' => 40.23, 'country' => 'Turkey'), 200 => array('city' => 'Djibouti', 'lat' => 11.59, 'lng' => 43.15, 'country' => 'Djibouti'), 201 => array('city' => 'Dnipropetrovs\'k', 'lat' => 48.45, 'lng' => 34.98, 'country' => 'Ukraine'), 202 => array('city' => 'Donetsk', 'lat' => 48.00, 'lng' => 37.82, 'country' => 'Ukraine'), 203 => array('city' => 'Dortmund', 'lat' => 51.51, 'lng' => 7.48, 'country' => 'Germany'), 204 => array('city' => 'Douala', 'lat' => 4.06, 'lng' => 9.71, 'country' => 'Cameroon'), 205 => array('city' => 'Dresden', 'lat' => 51.05, 'lng' => 13.74, 'country' => 'Germany'), 206 => array('city' => 'Dubai', 'lat' => 25.27, 'lng' => 55.33, 'country' => 'United Arab Emirates'), 207 => array('city' => 'Dublin', 'lat' => 53.33, 'lng' => -6.25, 'country' => 'Ireland'), 208 => array('city' => 'Duque de Caxias', 'lat' => -22.77, 'lng' => -43.31, 'country' => 'Brazil'), 209 => array('city' => 'Durban', 'lat' => -29.87, 'lng' => 30.99, 'country' => 'South Africa'), 210 => array('city' => 'Durgāpur', 'lat' => 23.50, 'lng' => 87.31, 'country' => 'India'), 211 => array('city' => 'Dushanbe', 'lat' => 38.57, 'lng' => 68.78, 'country' => 'Tajikistan'), 212 => array('city' => 'Düsseldorf', 'lat' => 51.24, 'lng' => 6.79, 'country' => 'Germany'), 213 => array('city' => 'Ecatepec de Morelos', 'lat' => 19.61, 'lng' => -99.06, 'country' => 'Mexico'), 214 => array('city' => 'Edmonton', 'lat' => 53.57, 'lng' => -113.54, 'country' => 'Canada'), 215 => array('city' => 'El Alto', 'lat' => -16.50, 'lng' => -68.17, 'country' => 'Bolivia'), 216 => array('city' => 'El Paso', 'lat' => 31.85, 'lng' => -106.44, 'country' => 'USA'), 217 => array('city' => 'Enugu', 'lat' => 6.44, 'lng' => 7.51, 'country' => 'Nigeria'), 218 => array('city' => 'Eşfahān', 'lat' => 32.68, 'lng' => 51.68, 'country' => 'Iran'), 219 => array('city' => 'Eskişehir', 'lat' => 39.79, 'lng' => 30.52, 'country' => 'Turkey'), 220 => array('city' => 'Essen', 'lat' => 51.47, 'lng' => 7.00, 'country' => 'Germany'), 221 => array('city' => 'Faisalābād', 'lat' => 31.41, 'lng' => 73.11, 'country' => 'Pakistan'), 222 => array('city' => 'Farīdābad', 'lat' => 28.38, 'lng' => 77.30, 'country' => 'India'), 223 => array('city' => 'Feira de Santana', 'lat' => -12.25, 'lng' => -38.97, 'country' => 'Brazil'), 224 => array('city' => 'Fez', 'lat' => 34.05, 'lng' => -5.00, 'country' => 'Morocco'), 225 => array('city' => 'Fortaleza', 'lat' => -3.78, 'lng' => -38.59, 'country' => 'Brazil'), 226 => array('city' => 'Fort Worth', 'lat' => 32.75, 'lng' => -97.34, 'country' => 'USA'), 227 => array('city' => 'Foshan', 'lat' => 23.03, 'lng' => 113.12, 'country' => 'China'), 228 => array('city' => 'Frankfurt', 'lat' => 50.12, 'lng' => 8.68, 'country' => 'Germany'), 229 => array('city' => 'Freetown', 'lat' => 8.49, 'lng' => -13.24, 'country' => 'Sierra Leone'), 230 => array('city' => 'Fresno', 'lat' => 36.78, 'lng' => -119.79, 'country' => 'USA'), 231 => array('city' => 'Fukuoka', 'lat' => 33.59, 'lng' => 130.41, 'country' => 'Japan'), 232 => array('city' => 'Funabashi', 'lat' => 35.70, 'lng' => 139.99, 'country' => 'Japan'), 233 => array('city' => 'Fushun', 'lat' => 41.87, 'lng' => 123.88, 'country' => 'China'), 234 => array('city' => 'Fuxin', 'lat' => 42.01, 'lng' => 121.65, 'country' => 'China'), 235 => array('city' => 'Fuzhou', 'lat' => 26.08, 'lng' => 119.30, 'country' => 'China'), 236 => array('city' => 'Gāoxióng', 'lat' => 22.63, 'lng' => 120.27, 'country' => 'Taiwan'), 237 => array('city' => 'Gaya', 'lat' => 24.81, 'lng' => 85.00, 'country' => 'India'), 238 => array('city' => 'Gaziantep', 'lat' => 37.07, 'lng' => 37.39, 'country' => 'Turkey'), 239 => array('city' => 'Gboko', 'lat' => 7.33, 'lng' => 9.00, 'country' => 'Nigeria'), 240 => array('city' => 'Genoa', 'lat' => 44.42, 'lng' => 8.93, 'country' => 'Italy'), 241 => array('city' => 'Ghāziābād', 'lat' => 28.66, 'lng' => 77.41, 'country' => 'India'), 242 => array('city' => 'Gizeh', 'lat' => 30.01, 'lng' => 31.21, 'country' => 'Egypt'), 243 => array('city' => 'Glasgow', 'lat' => 55.87, 'lng' => -4.27, 'country' => 'United Kingdom'), 244 => array('city' => 'Goiânia', 'lat' => -16.72, 'lng' => -49.26, 'country' => 'Brazil'), 245 => array('city' => 'Gold Coast-Tweed Heads', 'lat' => -28.07, 'lng' => 153.44, 'country' => 'Australia'), 246 => array('city' => 'Gorakhpur', 'lat' => 26.76, 'lng' => 83.36, 'country' => 'India'), 247 => array('city' => 'Göteborg', 'lat' => 57.72, 'lng' => 12.01, 'country' => 'Sweden'), 248 => array('city' => 'Guadalajara', 'lat' => 20.68, 'lng' => -103.34, 'country' => 'Mexico'), 249 => array('city' => 'Guadalupe', 'lat' => 25.68, 'lng' => -100.24, 'country' => 'Mexico'), 250 => array('city' => 'Guangzhou', 'lat' => 23.12, 'lng' => 113.25, 'country' => 'China'), 251 => array('city' => 'Guarulhos', 'lat' => -23.46, 'lng' => -46.49, 'country' => 'Brazil'), 252 => array('city' => 'Guatemala', 'lat' => 14.63, 'lng' => -90.55, 'country' => 'Guatemala'), 253 => array('city' => 'Guayaquil', 'lat' => -2.21, 'lng' => -79.90, 'country' => 'Ecuador'), 254 => array('city' => 'Guilin', 'lat' => 25.28, 'lng' => 110.28, 'country' => 'China'), 255 => array('city' => 'Guiyang', 'lat' => 26.58, 'lng' => 106.72, 'country' => 'China'), 256 => array('city' => 'Gujrānwāla', 'lat' => 32.16, 'lng' => 74.18, 'country' => 'Pakistan'), 257 => array('city' => 'Gulbarga', 'lat' => 17.34, 'lng' => 76.82, 'country' => 'India'), 258 => array('city' => 'Guntūr', 'lat' => 16.31, 'lng' => 80.44, 'country' => 'India'), 259 => array('city' => 'Guwāhāti', 'lat' => 26.19, 'lng' => 91.75, 'country' => 'India'), 260 => array('city' => 'Gwalior', 'lat' => 26.23, 'lng' => 78.17, 'country' => 'India'), 261 => array('city' => 'Hachiōji', 'lat' => 35.66, 'lng' => 139.33, 'country' => 'Japan'), 262 => array('city' => 'Haikou', 'lat' => 20.05, 'lng' => 110.32, 'country' => 'China'), 263 => array('city' => 'Hai Phòng', 'lat' => 20.86, 'lng' => 106.68, 'country' => 'Vietnam'), 264 => array('city' => 'Hamāh', 'lat' => 35.15, 'lng' => 36.73, 'country' => 'Syria'), 265 => array('city' => 'Hamamatsu', 'lat' => 34.72, 'lng' => 137.73, 'country' => 'Japan'), 266 => array('city' => 'Hamburg', 'lat' => 53.55, 'lng' => 10.00, 'country' => 'Germany'), 267 => array('city' => 'Hamhŭng', 'lat' => 39.91, 'lng' => 127.54, 'country' => 'Korea (North)'), 268 => array('city' => 'Hamilton', 'lat' => 43.26, 'lng' => -79.85, 'country' => 'Canada'), 269 => array('city' => 'Hamīs Mušayţ', 'lat' => 18.31, 'lng' => 42.73, 'country' => 'Saudi Arabia'), 270 => array('city' => 'Handan', 'lat' => 36.58, 'lng' => 114.48, 'country' => 'China'), 271 => array('city' => 'Hangzhou', 'lat' => 30.25, 'lng' => 120.17, 'country' => 'China'), 272 => array('city' => 'Hà Noi', 'lat' => 21.03, 'lng' => 105.84, 'country' => 'Vietnam'), 273 => array('city' => 'Hanover', 'lat' => 52.40, 'lng' => 9.73, 'country' => 'Germany'), 274 => array('city' => 'Hāora', 'lat' => 22.58, 'lng' => 88.33, 'country' => 'India'), 275 => array('city' => 'Harare', 'lat' => -17.82, 'lng' => 31.05, 'country' => 'Zimbabwe'), 276 => array('city' => 'Harbin', 'lat' => 45.75, 'lng' => 126.65, 'country' => 'China'), 277 => array('city' => 'Havanna', 'lat' => 23.13, 'lng' => -82.39, 'country' => 'Cuba'), 278 => array('city' => 'Hefei', 'lat' => 31.85, 'lng' => 117.28, 'country' => 'China'), 279 => array('city' => 'Hegang', 'lat' => 47.40, 'lng' => 130.37, 'country' => 'China'), 280 => array('city' => 'Helsinki', 'lat' => 60.17, 'lng' => 24.94, 'country' => 'Finland'), 281 => array('city' => 'Hengshui', 'lat' => 37.72, 'lng' => 115.70, 'country' => 'China'), 282 => array('city' => 'Hengyang', 'lat' => 26.89, 'lng' => 112.62, 'country' => 'China'), 283 => array('city' => 'Hermosillo', 'lat' => 29.10, 'lng' => -110.95, 'country' => 'Mexico'), 284 => array('city' => 'Heróica Puebla de Zaragoza', 'lat' => 19.05, 'lng' => -98.20, 'country' => 'Mexico'), 285 => array('city' => 'Higashiōsaka', 'lat' => 34.67, 'lng' => 135.59, 'country' => 'Japan'), 286 => array('city' => 'Hiroshima', 'lat' => 34.39, 'lng' => 132.44, 'country' => 'Japan'), 287 => array('city' => 'Ho Chi Minh City', 'lat' => 10.78, 'lng' => 106.69, 'country' => 'Vietnam'), 288 => array('city' => 'Hohhot', 'lat' => 40.82, 'lng' => 111.64, 'country' => 'China'), 289 => array('city' => 'Homş', 'lat' => 34.73, 'lng' => 36.72, 'country' => 'Syria'), 290 => array('city' => 'Hong Kong', 'lat' => 22.27, 'lng' => 114.14, 'country' => 'China'), 291 => array('city' => 'Houston', 'lat' => 29.77, 'lng' => -95.39, 'country' => 'USA'), 292 => array('city' => 'Huaibei', 'lat' => 33.95, 'lng' => 116.75, 'country' => 'China'), 293 => array('city' => 'Huainan', 'lat' => 32.63, 'lng' => 116.98, 'country' => 'China'), 294 => array('city' => 'Huaiyin', 'lat' => 33.58, 'lng' => 119.03, 'country' => 'China'), 295 => array('city' => 'Huangshi', 'lat' => 30.22, 'lng' => 115.10, 'country' => 'China'), 296 => array('city' => 'Hubli', 'lat' => 15.36, 'lng' => 75.13, 'country' => 'India'), 297 => array('city' => 'Hwasŏng', 'lat' => 37.20, 'lng' => 126.83, 'country' => 'Korea (South)'), 298 => array('city' => 'Hyderabad', 'lat' => 17.40, 'lng' => 78.48, 'country' => 'India'), 299 => array('city' => 'Hyderabad', 'lat' => 25.38, 'lng' => 68.37, 'country' => 'Pakistan'), 300 => array('city' => 'Ibadan', 'lat' => 7.38, 'lng' => 3.93, 'country' => 'Nigeria'), 301 => array('city' => 'Ibagué', 'lat' => 4.45, 'lng' => -75.24, 'country' => 'Colombia'), 302 => array('city' => 'Ife', 'lat' => 7.48, 'lng' => 4.56, 'country' => 'Nigeria'), 303 => array('city' => 'Ilorin', 'lat' => 8.49, 'lng' => 4.55, 'country' => 'Nigeria'), 304 => array('city' => 'Inchŏn', 'lat' => 37.48, 'lng' => 126.64, 'country' => 'Korea (South)'), 305 => array('city' => 'Indianapolis', 'lat' => 39.78, 'lng' => -86.15, 'country' => 'USA'), 306 => array('city' => 'Indore', 'lat' => 22.72, 'lng' => 75.86, 'country' => 'India'), 307 => array('city' => 'Irbīl', 'lat' => 36.18, 'lng' => 44.01, 'country' => 'Iraq'), 308 => array('city' => 'Irkutsk', 'lat' => 52.33, 'lng' => 104.24, 'country' => 'Russia'), 309 => array('city' => 'Islāmābād', 'lat' => 33.72, 'lng' => 73.06, 'country' => 'Pakistan'), 310 => array('city' => 'İstanbul', 'lat' => 41.10, 'lng' => 29.00, 'country' => 'Turkey'), 311 => array('city' => 'Izhevsk', 'lat' => 56.85, 'lng' => 53.23, 'country' => 'Russia'), 312 => array('city' => 'İzmir', 'lat' => 38.43, 'lng' => 27.15, 'country' => 'Turkey'), 313 => array('city' => 'Jabalpur', 'lat' => 23.17, 'lng' => 79.94, 'country' => 'India'), 314 => array('city' => 'Jaboatão', 'lat' => -8.11, 'lng' => -35.02, 'country' => 'Brazil'), 315 => array('city' => 'Jacksonville', 'lat' => 30.33, 'lng' => -81.66, 'country' => 'USA'), 316 => array('city' => 'Jaipur', 'lat' => 26.92, 'lng' => 75.80, 'country' => 'India'), 317 => array('city' => 'Jakarta', 'lat' => -6.18, 'lng' => 106.83, 'country' => 'Indonesia'), 318 => array('city' => 'Jalandhar', 'lat' => 31.33, 'lng' => 75.57, 'country' => 'India'), 319 => array('city' => 'Jālgaon', 'lat' => 21.01, 'lng' => 75.56, 'country' => 'India'), 320 => array('city' => 'Jambi', 'lat' => -1.59, 'lng' => 103.61, 'country' => 'Indonesia'), 321 => array('city' => 'Jammu', 'lat' => 32.71, 'lng' => 74.85, 'country' => 'India'), 322 => array('city' => 'Jāmnagar', 'lat' => 22.47, 'lng' => 70.07, 'country' => 'India'), 323 => array('city' => 'Jamshedpur', 'lat' => 22.79, 'lng' => 86.20, 'country' => 'India'), 324 => array('city' => 'Jerusalem', 'lat' => 31.78, 'lng' => 35.22, 'country' => 'Israel'), 325 => array('city' => 'Jiamusi', 'lat' => 46.83, 'lng' => 130.35, 'country' => 'China'), 326 => array('city' => 'Jiangmen', 'lat' => 22.58, 'lng' => 113.08, 'country' => 'China'), 327 => array('city' => 'Jiaojiang', 'lat' => 28.68, 'lng' => 121.45, 'country' => 'China'), 328 => array('city' => 'Jiaozuo', 'lat' => 35.25, 'lng' => 113.22, 'country' => 'China'), 329 => array('city' => 'Jiaxing', 'lat' => 30.77, 'lng' => 120.75, 'country' => 'China'), 330 => array('city' => 'Jiddah', 'lat' => 21.50, 'lng' => 39.17, 'country' => 'Saudi Arabia'), 331 => array('city' => 'Jilin', 'lat' => 43.85, 'lng' => 126.55, 'country' => 'China'), 332 => array('city' => 'Jinan', 'lat' => 36.67, 'lng' => 117.00, 'country' => 'China'), 333 => array('city' => 'Jincheng', 'lat' => 35.50, 'lng' => 112.83, 'country' => 'China'), 334 => array('city' => 'Jining', 'lat' => 35.40, 'lng' => 116.55, 'country' => 'China'), 335 => array('city' => 'Jinzhou', 'lat' => 41.12, 'lng' => 121.10, 'country' => 'China'), 336 => array('city' => 'Kowloon', 'lat' => 22.32, 'lng' => 114.17, 'country' => 'China'), 337 => array('city' => 'Jixi', 'lat' => 45.30, 'lng' => 130.97, 'country' => 'China'), 338 => array('city' => 'João Pessoa', 'lat' => -7.12, 'lng' => -34.86, 'country' => 'Brazil'), 339 => array('city' => 'Jodhpur', 'lat' => 26.29, 'lng' => 73.02, 'country' => 'India'), 340 => array('city' => 'Johannesburg', 'lat' => -26.19, 'lng' => 28.04, 'country' => 'South Africa'), 341 => array('city' => 'Joinville', 'lat' => -26.32, 'lng' => -48.84, 'country' => 'Brazil'), 342 => array('city' => 'Jos', 'lat' => 9.93, 'lng' => 8.89, 'country' => 'Nigeria'), 343 => array('city' => 'Juárez', 'lat' => 31.74, 'lng' => -106.49, 'country' => 'Mexico'), 344 => array('city' => 'Juba', 'lat' => 4.86, 'lng' => 31.60, 'country' => 'South Sudan'), 345 => array('city' => 'Juiz de Fora', 'lat' => -21.75, 'lng' => -43.36, 'country' => 'Brazil'), 346 => array('city' => 'Kabul', 'lat' => 34.53, 'lng' => 69.17, 'country' => 'Afghanistan'), 347 => array('city' => 'Kaduna', 'lat' => 10.52, 'lng' => 7.44, 'country' => 'Nigeria'), 348 => array('city' => 'Kagoshima', 'lat' => 31.59, 'lng' => 130.56, 'country' => 'Japan'), 349 => array('city' => 'Kaifeng', 'lat' => 34.85, 'lng' => 114.35, 'country' => 'China'), 350 => array('city' => 'Kalyān', 'lat' => 19.25, 'lng' => 73.16, 'country' => 'India'), 351 => array('city' => 'Kampala', 'lat' => 0.32, 'lng' => 32.58, 'country' => 'Uganda'), 352 => array('city' => 'Kananga', 'lat' => -5.89, 'lng' => 22.40, 'country' => 'Congo (Dem. Rep.)'), 353 => array('city' => 'Kano', 'lat' => 12.00, 'lng' => 8.52, 'country' => 'Nigeria'), 354 => array('city' => 'Kānpur', 'lat' => 26.47, 'lng' => 80.33, 'country' => 'India'), 355 => array('city' => 'Karāchi', 'lat' => 24.86, 'lng' => 67.01, 'country' => 'Pakistan'), 356 => array('city' => 'Karaj', 'lat' => 35.80, 'lng' => 50.97, 'country' => 'Iran'), 357 => array('city' => 'Karbalā\'', 'lat' => 32.61, 'lng' => 44.03, 'country' => 'Iraq'), 358 => array('city' => 'Kassalā', 'lat' => 15.46, 'lng' => 36.39, 'country' => 'Sudan'), 359 => array('city' => 'Kataka', 'lat' => 20.47, 'lng' => 85.88, 'country' => 'India'), 360 => array('city' => 'Kathmandu', 'lat' => 27.71, 'lng' => 85.31, 'country' => 'Nepal'), 361 => array('city' => 'Kawaguchi', 'lat' => 35.81, 'lng' => 139.73, 'country' => 'Japan'), 362 => array('city' => 'Kawasaki', 'lat' => 35.53, 'lng' => 139.70, 'country' => 'Japan'), 363 => array('city' => 'Kayseri', 'lat' => 38.74, 'lng' => 35.48, 'country' => 'Turkey'), 364 => array('city' => 'Kazan', 'lat' => 55.75, 'lng' => 49.13, 'country' => 'Russia'), 365 => array('city' => 'Kemerovo', 'lat' => 55.33, 'lng' => 86.08, 'country' => 'Russia'), 366 => array('city' => 'Kermān', 'lat' => 30.30, 'lng' => 57.08, 'country' => 'Iran'), 367 => array('city' => 'Kermānshāh', 'lat' => 34.38, 'lng' => 47.06, 'country' => 'Iran'), 368 => array('city' => 'Khabarovsk', 'lat' => 48.42, 'lng' => 135.12, 'country' => 'Russia'), 369 => array('city' => 'Kharkiv', 'lat' => 49.98, 'lng' => 36.22, 'country' => 'Ukraine'), 370 => array('city' => 'Khartoum', 'lat' => 15.58, 'lng' => 32.52, 'country' => 'Sudan'), 371 => array('city' => 'Khulnā', 'lat' => 22.84, 'lng' => 89.56, 'country' => 'Bangladesh'), 372 => array('city' => 'Kiev', 'lat' => 50.43, 'lng' => 30.52, 'country' => 'Ukraine'), 373 => array('city' => 'Kigali', 'lat' => -1.94, 'lng' => 30.06, 'country' => 'Rwanda'), 374 => array('city' => 'Kimhae', 'lat' => 35.19, 'lng' => 128.93, 'country' => 'Korea (South)'), 375 => array('city' => 'Kingston', 'lat' => 17.99, 'lng' => -76.80, 'country' => 'Jamaica'), 376 => array('city' => 'Kinshasa', 'lat' => -4.31, 'lng' => 15.32, 'country' => 'Congo (Dem. Rep.)'), 377 => array('city' => 'Kirkūk', 'lat' => 35.47, 'lng' => 44.39, 'country' => 'Iraq'), 378 => array('city' => 'Kisangani', 'lat' => 0.53, 'lng' => 25.19, 'country' => 'Congo (Dem. Rep.)'), 379 => array('city' => 'Kitakyūshū', 'lat' => 33.88, 'lng' => 130.86, 'country' => 'Japan'), 380 => array('city' => 'Kitwe', 'lat' => -12.81, 'lng' => 28.22, 'country' => 'Zambia'), 381 => array('city' => 'Kōbe', 'lat' => 34.68, 'lng' => 135.17, 'country' => 'Japan'), 382 => array('city' => 'København', 'lat' => 55.67, 'lng' => 12.58, 'country' => 'Denmark'), 383 => array('city' => 'Kolhāpur', 'lat' => 16.70, 'lng' => 74.22, 'country' => 'India'), 384 => array('city' => 'Konya', 'lat' => 37.88, 'lng' => 32.48, 'country' => 'Turkey'), 385 => array('city' => 'Korba', 'lat' => 22.35, 'lng' => 82.69, 'country' => 'India'), 386 => array('city' => 'Kota', 'lat' => 25.18, 'lng' => 75.83, 'country' => 'India'), 387 => array('city' => 'Koyampattur', 'lat' => 11.01, 'lng' => 76.96, 'country' => 'India'), 388 => array('city' => 'Koyang', 'lat' => 37.70, 'lng' => 126.93, 'country' => 'Korea (South)'), 389 => array('city' => 'Krasnodar', 'lat' => 45.03, 'lng' => 38.98, 'country' => 'Russia'), 390 => array('city' => 'Krasnoyarsk', 'lat' => 56.02, 'lng' => 93.06, 'country' => 'Russia'), 391 => array('city' => 'Kryvyy Rih', 'lat' => 47.92, 'lng' => 33.35, 'country' => 'Ukraine'), 392 => array('city' => 'Kuala Lumpur', 'lat' => 3.16, 'lng' => 101.71, 'country' => 'Malaysia'), 393 => array('city' => 'Kumamoto', 'lat' => 32.80, 'lng' => 130.71, 'country' => 'Japan'), 394 => array('city' => 'Kumasi', 'lat' => 6.69, 'lng' => -1.63, 'country' => 'Ghana'), 395 => array('city' => 'Kunming', 'lat' => 25.05, 'lng' => 102.70, 'country' => 'China'), 396 => array('city' => 'Kwangju', 'lat' => 35.16, 'lng' => 126.91, 'country' => 'Korea (South)'), 397 => array('city' => 'Kyōto', 'lat' => 35.01, 'lng' => 135.75, 'country' => 'Japan'), 398 => array('city' => 'Lagos', 'lat' => 6.50, 'lng' => 3.35, 'country' => 'Nigeria'), 399 => array('city' => 'Lahore', 'lat' => 31.56, 'lng' => 74.35, 'country' => 'Pakistan'), 400 => array('city' => 'Lakhnau', 'lat' => 26.85, 'lng' => 80.92, 'country' => 'India'), 401 => array('city' => 'Langfang', 'lat' => 39.52, 'lng' => 116.68, 'country' => 'China'), 402 => array('city' => 'Lanzhou', 'lat' => 36.05, 'lng' => 103.68, 'country' => 'China'), 403 => array('city' => 'La Paz', 'lat' => -16.50, 'lng' => -68.15, 'country' => 'Bolivia'), 404 => array('city' => 'La Plata', 'lat' => -34.92, 'lng' => -57.96, 'country' => 'Argentina'), 405 => array('city' => 'Las Vegas', 'lat' => 36.21, 'lng' => -115.22, 'country' => 'USA'), 406 => array('city' => 'Leipzig', 'lat' => 51.35, 'lng' => 12.40, 'country' => 'Germany'), 407 => array('city' => 'León de los Aldama', 'lat' => 21.12, 'lng' => -101.68, 'country' => 'Mexico'), 408 => array('city' => 'Liaoyang', 'lat' => 41.28, 'lng' => 123.18, 'country' => 'China'), 409 => array('city' => 'Libreville', 'lat' => 0.39, 'lng' => 9.45, 'country' => 'Gabon'), 410 => array('city' => 'Lilongwe', 'lat' => -13.97, 'lng' => 33.80, 'country' => 'Malawi'), 411 => array('city' => 'Lima', 'lat' => -12.07, 'lng' => -77.05, 'country' => 'Peru'), 412 => array('city' => 'Lipetsk', 'lat' => 52.62, 'lng' => 39.62, 'country' => 'Russia'), 413 => array('city' => 'Liuzhou', 'lat' => 24.28, 'lng' => 109.25, 'country' => 'China'), 414 => array('city' => 'Łódź', 'lat' => 51.77, 'lng' => 19.46, 'country' => 'Poland'), 415 => array('city' => 'Lomé', 'lat' => 6.17, 'lng' => 1.35, 'country' => 'Togo'), 416 => array('city' => 'London', 'lat' => 51.52, 'lng' => -0.10, 'country' => 'United Kingdom'), 417 => array('city' => 'Londrina', 'lat' => -23.30, 'lng' => -51.18, 'country' => 'Brazil'), 418 => array('city' => 'Los Angeles', 'lat' => 34.11, 'lng' => -118.41, 'country' => 'USA'), 419 => array('city' => 'Louisville', 'lat' => 38.22, 'lng' => -85.74, 'country' => 'USA'), 420 => array('city' => 'Luancheng', 'lat' => 37.88, 'lng' => 114.65, 'country' => 'China'), 421 => array('city' => 'Luanda', 'lat' => -8.82, 'lng' => 13.24, 'country' => 'Angola'), 422 => array('city' => 'Lubumbashi', 'lat' => -11.66, 'lng' => 27.48, 'country' => 'Congo (Dem. Rep.)'), 423 => array('city' => 'Ludhiāna', 'lat' => 30.91, 'lng' => 75.84, 'country' => 'India'), 424 => array('city' => 'Luohe', 'lat' => 33.57, 'lng' => 114.03, 'country' => 'China'), 425 => array('city' => 'Luoyang', 'lat' => 34.68, 'lng' => 112.47, 'country' => 'China'), 426 => array('city' => 'Lusaka', 'lat' => -15.42, 'lng' => 28.29, 'country' => 'Zambia'), 427 => array('city' => 'Luxor', 'lat' => 25.70, 'lng' => 32.65, 'country' => 'Egypt'), 428 => array('city' => 'L\'viv', 'lat' => 49.83, 'lng' => 24.00, 'country' => 'Ukraine'), 429 => array('city' => 'Maanshan', 'lat' => 31.73, 'lng' => 118.48, 'country' => 'China'), 430 => array('city' => 'Macao', 'lat' => 22.27, 'lng' => 113.56, 'country' => 'China'), 431 => array('city' => 'Maceió', 'lat' => -9.65, 'lng' => -35.75, 'country' => 'Brazil'), 432 => array('city' => 'Madras', 'lat' => 13.09, 'lng' => 80.27, 'country' => 'India'), 433 => array('city' => 'Madrid', 'lat' => 40.42, 'lng' => -3.71, 'country' => 'Spain'), 434 => array('city' => 'Madurai', 'lat' => 9.92, 'lng' => 78.12, 'country' => 'India'), 435 => array('city' => 'Maheshtala', 'lat' => 22.51, 'lng' => 88.23, 'country' => 'India'), 436 => array('city' => 'Maiduguri', 'lat' => 11.85, 'lng' => 13.16, 'country' => 'Nigeria'), 437 => array('city' => 'Maisūru', 'lat' => 12.31, 'lng' => 76.65, 'country' => 'India'), 438 => array('city' => 'Makasar', 'lat' => -5.14, 'lng' => 119.41, 'country' => 'Indonesia'), 439 => array('city' => 'Málaga', 'lat' => 36.72, 'lng' => -4.42, 'country' => 'Spain'), 440 => array('city' => 'Malang', 'lat' => -7.98, 'lng' => 112.62, 'country' => 'Indonesia'), 441 => array('city' => 'Managua', 'lat' => 12.15, 'lng' => -86.27, 'country' => 'Nicaragua'), 442 => array('city' => 'Manaus', 'lat' => -3.12, 'lng' => -60.02, 'country' => 'Brazil'), 443 => array('city' => 'Mandalay', 'lat' => 21.98, 'lng' => 96.09, 'country' => 'Myanmar'), 444 => array('city' => 'Manila', 'lat' => 14.60, 'lng' => 120.98, 'country' => 'Philippines'), 445 => array('city' => 'Maoming', 'lat' => 21.92, 'lng' => 110.87, 'country' => 'China'), 446 => array('city' => 'Maputo', 'lat' => -25.95, 'lng' => 32.57, 'country' => 'Mozambique'), 447 => array('city' => 'Maracaibo', 'lat' => 10.73, 'lng' => -71.66, 'country' => 'Venezuela'), 448 => array('city' => 'Maracay', 'lat' => 10.33, 'lng' => -67.47, 'country' => 'Venezuela'), 449 => array('city' => 'Mar del Plata', 'lat' => -38.00, 'lng' => -57.58, 'country' => 'Argentina'), 450 => array('city' => 'Marrakesh', 'lat' => 31.63, 'lng' => -8.00, 'country' => 'Morocco'), 451 => array('city' => 'Marseille', 'lat' => 43.31, 'lng' => 5.37, 'country' => 'France'), 452 => array('city' => 'Mashhad', 'lat' => 36.27, 'lng' => 59.57, 'country' => 'Iran'), 453 => array('city' => 'Matola', 'lat' => -25.97, 'lng' => 32.46, 'country' => 'Mozambique'), 454 => array('city' => 'Matsuyama', 'lat' => 33.84, 'lng' => 132.77, 'country' => 'Japan'), 455 => array('city' => 'Maturín', 'lat' => 9.75, 'lng' => -63.17, 'country' => 'Venezuela'), 456 => array('city' => 'Mawlamyine', 'lat' => 16.49, 'lng' => 97.63, 'country' => 'Myanmar'), 457 => array('city' => 'Mbuji-Mayi', 'lat' => -6.13, 'lng' => 23.59, 'country' => 'Congo (Dem. Rep.)'), 458 => array('city' => 'Mecca', 'lat' => 21.43, 'lng' => 39.82, 'country' => 'Saudi Arabia'), 459 => array('city' => 'Medan', 'lat' => 3.59, 'lng' => 98.67, 'country' => 'Indonesia'), 460 => array('city' => 'Medellín', 'lat' => 6.29, 'lng' => -75.54, 'country' => 'Colombia'), 461 => array('city' => 'Meknes', 'lat' => 33.90, 'lng' => -5.56, 'country' => 'Morocco'), 462 => array('city' => 'Melbourne', 'lat' => -37.81, 'lng' => 144.96, 'country' => 'Australia'), 463 => array('city' => 'Memphis', 'lat' => 35.11, 'lng' => -90.01, 'country' => 'USA'), 464 => array('city' => 'Mendoza', 'lat' => -32.89, 'lng' => -68.83, 'country' => 'Argentina'), 465 => array('city' => 'Mérida', 'lat' => 20.97, 'lng' => -89.62, 'country' => 'Mexico'), 466 => array('city' => 'Mersin', 'lat' => 36.81, 'lng' => 34.63, 'country' => 'Turkey'), 467 => array('city' => 'Mexicali', 'lat' => 32.66, 'lng' => -115.47, 'country' => 'Mexico'), 468 => array('city' => 'Milan', 'lat' => 45.48, 'lng' => 9.19, 'country' => 'Italy'), 469 => array('city' => 'Milwaukee', 'lat' => 43.06, 'lng' => -87.97, 'country' => 'USA'), 470 => array('city' => 'Minsk', 'lat' => 53.91, 'lng' => 27.55, 'country' => 'Belarus'), 471 => array('city' => 'Mira Bhayandar', 'lat' => 19.29, 'lng' => 72.85, 'country' => 'India'), 472 => array('city' => 'Mīrat', 'lat' => 28.99, 'lng' => 77.70, 'country' => 'India'), 473 => array('city' => 'Mixco', 'lat' => 14.64, 'lng' => -90.60, 'country' => 'Guatemala'), 474 => array('city' => 'Mombasa', 'lat' => -4.04, 'lng' => 39.66, 'country' => 'Kenya'), 475 => array('city' => 'Monrovia', 'lat' => 6.31, 'lng' => -10.80, 'country' => 'Liberia'), 476 => array('city' => 'Monterrey', 'lat' => 25.67, 'lng' => -100.31, 'country' => 'Mexico'), 477 => array('city' => 'Montevideo', 'lat' => -34.87, 'lng' => -56.17, 'country' => 'Uruguay'), 478 => array('city' => 'Montreal', 'lat' => 45.52, 'lng' => -73.57, 'country' => 'Canada'), 479 => array('city' => 'Morādābād', 'lat' => 28.84, 'lng' => 78.76, 'country' => 'India'), 480 => array('city' => 'Morelia', 'lat' => 19.70, 'lng' => -101.19, 'country' => 'Mexico'), 481 => array('city' => 'Moscow', 'lat' => 55.75, 'lng' => 37.62, 'country' => 'Russia'), 482 => array('city' => 'Mudanjiang', 'lat' => 44.58, 'lng' => 129.60, 'country' => 'China'), 483 => array('city' => 'Multān', 'lat' => 30.20, 'lng' => 71.45, 'country' => 'Pakistan'), 484 => array('city' => 'Munich', 'lat' => 48.14, 'lng' => 11.58, 'country' => 'Germany'), 485 => array('city' => 'Muqdisho', 'lat' => 2.05, 'lng' => 45.33, 'country' => 'Somalia'), 486 => array('city' => 'Mwanza', 'lat' => -2.52, 'lng' => 32.89, 'country' => 'Tanzania'), 487 => array('city' => 'Mykolayiv', 'lat' => 46.97, 'lng' => 32.00, 'country' => 'Ukraine'), 488 => array('city' => 'Nagoya', 'lat' => 35.15, 'lng' => 136.91, 'country' => 'Japan'), 489 => array('city' => 'Nāgpur', 'lat' => 21.16, 'lng' => 79.08, 'country' => 'India'), 490 => array('city' => 'Nairobi', 'lat' => -1.29, 'lng' => 36.82, 'country' => 'Kenya'), 491 => array('city' => 'Nampula', 'lat' => -15.13, 'lng' => 39.24, 'country' => 'Mozambique'), 492 => array('city' => 'Namyangju', 'lat' => 37.66, 'lng' => 127.28, 'country' => 'Korea (South)'), 493 => array('city' => 'Nanchang', 'lat' => 28.68, 'lng' => 115.88, 'country' => 'China'), 494 => array('city' => 'Nānded', 'lat' => 19.17, 'lng' => 77.29, 'country' => 'India'), 495 => array('city' => 'Nanjing', 'lat' => 32.05, 'lng' => 118.78, 'country' => 'China'), 496 => array('city' => 'Nanning', 'lat' => 22.82, 'lng' => 108.32, 'country' => 'China'), 497 => array('city' => 'Nantong', 'lat' => 32.02, 'lng' => 120.82, 'country' => 'China'), 498 => array('city' => 'Naples', 'lat' => 40.85, 'lng' => 14.27, 'country' => 'Italy'), 499 => array('city' => 'Nārāyanganj', 'lat' => 23.62, 'lng' => 90.50, 'country' => 'Bangladesh'), 500 => array('city' => 'Nāshik', 'lat' => 20.01, 'lng' => 73.78, 'country' => 'India'), 501 => array('city' => 'Nashville', 'lat' => 36.17, 'lng' => -86.78, 'country' => 'USA'), 502 => array('city' => 'Natal', 'lat' => -5.80, 'lng' => -35.22, 'country' => 'Brazil'), 503 => array('city' => 'Naucalpan de Juárez', 'lat' => 19.48, 'lng' => -99.24, 'country' => 'Mexico'), 504 => array('city' => 'Navi Mumbai', 'lat' => 19.11, 'lng' => 73.06, 'country' => 'India'), 505 => array('city' => 'N\'Djaména', 'lat' => 12.11, 'lng' => 15.05, 'country' => 'Chad'), 506 => array('city' => 'Ndola', 'lat' => -12.97, 'lng' => 28.64, 'country' => 'Zambia'), 507 => array('city' => 'Neijiang', 'lat' => 29.58, 'lng' => 105.05, 'country' => 'China'), 508 => array('city' => 'New York', 'lat' => 40.67, 'lng' => -73.94, 'country' => 'USA'), 509 => array('city' => 'Niamey', 'lat' => 13.52, 'lng' => 2.12, 'country' => 'Niger'), 510 => array('city' => 'Niigata', 'lat' => 37.92, 'lng' => 139.04, 'country' => 'Japan'), 511 => array('city' => 'Ningbo', 'lat' => 29.88, 'lng' => 121.55, 'country' => 'China'), 512 => array('city' => 'Nishinomiya', 'lat' => 34.73, 'lng' => 135.34, 'country' => 'Japan'), 513 => array('city' => 'Nizhniy Novgorod', 'lat' => 56.33, 'lng' => 44.00, 'country' => 'Russia'), 514 => array('city' => 'Noida', 'lat' => 28.58, 'lng' => 77.33, 'country' => 'India'), 515 => array('city' => 'Nouakchott', 'lat' => 18.09, 'lng' => -15.98, 'country' => 'Mauritania'), 516 => array('city' => 'Nova Iguaçu', 'lat' => -22.74, 'lng' => -43.47, 'country' => 'Brazil'), 517 => array('city' => 'Novokuznetsk', 'lat' => 53.75, 'lng' => 87.10, 'country' => 'Russia'), 518 => array('city' => 'Novosibirsk', 'lat' => 55.04, 'lng' => 82.93, 'country' => 'Russia'), 519 => array('city' => 'Nuremberg', 'lat' => 49.45, 'lng' => 11.05, 'country' => 'Germany'), 520 => array('city' => 'Odesa', 'lat' => 46.47, 'lng' => 30.73, 'country' => 'Ukraine'), 521 => array('city' => 'Okayama', 'lat' => 34.67, 'lng' => 133.92, 'country' => 'Japan'), 522 => array('city' => 'Oklahoma City', 'lat' => 35.47, 'lng' => -97.51, 'country' => 'USA'), 523 => array('city' => 'Omsk', 'lat' => 55.00, 'lng' => 73.40, 'country' => 'Russia'), 524 => array('city' => 'Ondo', 'lat' => 7.09, 'lng' => 4.84, 'country' => 'Nigeria'), 525 => array('city' => 'Onitsha', 'lat' => 6.14, 'lng' => 6.78, 'country' => 'Nigeria'), 526 => array('city' => 'Oran', 'lat' => 35.70, 'lng' => -0.62, 'country' => 'Algeria'), 527 => array('city' => 'Orenburg', 'lat' => 51.78, 'lng' => 55.10, 'country' => 'Russia'), 528 => array('city' => 'Orūmīyeh', 'lat' => 37.53, 'lng' => 45.00, 'country' => 'Iran'), 529 => array('city' => 'Ōsaka', 'lat' => 34.68, 'lng' => 135.50, 'country' => 'Japan'), 530 => array('city' => 'Osasco', 'lat' => -23.53, 'lng' => -46.78, 'country' => 'Brazil'), 531 => array('city' => 'Oshogbo', 'lat' => 7.77, 'lng' => 4.56, 'country' => 'Nigeria'), 532 => array('city' => 'Oslo', 'lat' => 59.91, 'lng' => 10.75, 'country' => 'Norway'), 533 => array('city' => 'Ottawa', 'lat' => 45.42, 'lng' => -75.71, 'country' => 'Canada'), 534 => array('city' => 'Ouagadougou', 'lat' => 12.37, 'lng' => -1.53, 'country' => 'Burkina Faso'), 535 => array('city' => 'Owerri', 'lat' => 5.49, 'lng' => 7.04, 'country' => 'Nigeria'), 536 => array('city' => 'Pacet', 'lat' => -6.75, 'lng' => 107.05, 'country' => 'Indonesia'), 537 => array('city' => 'Padang', 'lat' => -0.95, 'lng' => 100.35, 'country' => 'Indonesia'), 538 => array('city' => 'Palembang', 'lat' => -2.99, 'lng' => 104.75, 'country' => 'Indonesia'), 539 => array('city' => 'Palermo', 'lat' => 38.12, 'lng' => 13.36, 'country' => 'Italy'), 540 => array('city' => 'Panjin', 'lat' => 41.18, 'lng' => 122.05, 'country' => 'China'), 541 => array('city' => 'Paris', 'lat' => 48.86, 'lng' => 2.34, 'country' => 'France'), 542 => array('city' => 'Patna', 'lat' => 25.62, 'lng' => 85.13, 'country' => 'India'), 543 => array('city' => 'Pekan Baru', 'lat' => 0.56, 'lng' => 101.43, 'country' => 'Indonesia'), 544 => array('city' => 'Beijing', 'lat' => 39.93, 'lng' => 116.40, 'country' => 'China'), 545 => array('city' => 'Perm', 'lat' => 58.00, 'lng' => 56.25, 'country' => 'Russia'), 546 => array('city' => 'Perth', 'lat' => -31.96, 'lng' => 115.84, 'country' => 'Australia'), 547 => array('city' => 'Peshāwar', 'lat' => 34.01, 'lng' => 71.54, 'country' => 'Pakistan'), 548 => array('city' => 'Petare', 'lat' => 10.52, 'lng' => -66.83, 'country' => 'Venezuela'), 549 => array('city' => 'Philadelphia', 'lat' => 40.01, 'lng' => -75.13, 'country' => 'USA'), 550 => array('city' => 'Phnum Pénh', 'lat' => 11.57, 'lng' => 104.92, 'country' => 'Cambodia'), 551 => array('city' => 'Phoenix', 'lat' => 33.54, 'lng' => -112.07, 'country' => 'USA'), 552 => array('city' => 'Pietermaritzburg', 'lat' => -29.61, 'lng' => 30.39, 'country' => 'South Africa'), 553 => array('city' => 'Pimpri', 'lat' => 18.62, 'lng' => 73.80, 'country' => 'India'), 554 => array('city' => 'Pingdingshan', 'lat' => 33.73, 'lng' => 113.30, 'country' => 'China'), 555 => array('city' => 'Pohang', 'lat' => 36.03, 'lng' => 129.37, 'country' => 'Korea (South)'), 556 => array('city' => 'Pointe Noire', 'lat' => -4.77, 'lng' => 11.87, 'country' => 'Congo'), 557 => array('city' => 'Pontianak', 'lat' => -0.02, 'lng' => 109.34, 'country' => 'Indonesia'), 558 => array('city' => 'Port-au-Prince', 'lat' => 18.54, 'lng' => -72.34, 'country' => 'Haiti'), 559 => array('city' => 'Port Elizabeth', 'lat' => -33.96, 'lng' => 25.59, 'country' => 'South Africa'), 560 => array('city' => 'Port Harcourt', 'lat' => 4.81, 'lng' => 7.01, 'country' => 'Nigeria'), 561 => array('city' => 'Portland', 'lat' => 45.54, 'lng' => -122.66, 'country' => 'USA'), 562 => array('city' => 'Porto Alegre', 'lat' => -30.04, 'lng' => -51.22, 'country' => 'Brazil'), 563 => array('city' => 'Port Said', 'lat' => 31.26, 'lng' => 32.29, 'country' => 'Egypt'), 564 => array('city' => 'Poznań', 'lat' => 52.40, 'lng' => 16.90, 'country' => 'Poland'), 565 => array('city' => 'Prague', 'lat' => 50.08, 'lng' => 14.43, 'country' => 'Czech Republic'), 566 => array('city' => 'Pretoria', 'lat' => -25.73, 'lng' => 28.22, 'country' => 'South Africa'), 567 => array('city' => 'Puchŏn', 'lat' => 37.48, 'lng' => 126.77, 'country' => 'Korea (South)'), 568 => array('city' => 'Puente Alto', 'lat' => -33.61, 'lng' => -70.57, 'country' => 'Chile'), 569 => array('city' => 'Pune', 'lat' => 18.53, 'lng' => 73.84, 'country' => 'India'), 570 => array('city' => 'Pusan', 'lat' => 35.11, 'lng' => 129.03, 'country' => 'Korea (South)'), 571 => array('city' => 'Puyang', 'lat' => 35.70, 'lng' => 114.98, 'country' => 'China'), 572 => array('city' => 'Pyŏngyang', 'lat' => 39.02, 'lng' => 125.75, 'country' => 'Korea (North)'), 573 => array('city' => 'Qingdao', 'lat' => 36.07, 'lng' => 120.32, 'country' => 'China'), 574 => array('city' => 'Qinhuangdao', 'lat' => 39.93, 'lng' => 119.62, 'country' => 'China'), 575 => array('city' => 'Qiqihar', 'lat' => 47.35, 'lng' => 124.00, 'country' => 'China'), 576 => array('city' => 'Qom', 'lat' => 34.65, 'lng' => 50.95, 'country' => 'Iran'), 577 => array('city' => 'Quebec', 'lat' => 46.82, 'lng' => -71.23, 'country' => 'Canada'), 578 => array('city' => 'Quetta', 'lat' => 30.21, 'lng' => 67.02, 'country' => 'Pakistan'), 579 => array('city' => 'Quito', 'lat' => -0.19, 'lng' => -78.50, 'country' => 'Ecuador'), 580 => array('city' => 'Qutubullapur', 'lat' => 17.43, 'lng' => 78.47, 'country' => 'India'), 581 => array('city' => 'Rabat', 'lat' => 34.02, 'lng' => -6.84, 'country' => 'Morocco'), 582 => array('city' => 'Raipur', 'lat' => 21.24, 'lng' => 81.63, 'country' => 'India'), 583 => array('city' => 'Rājkot', 'lat' => 22.31, 'lng' => 70.79, 'country' => 'India'), 584 => array('city' => 'Rājpur', 'lat' => 22.44, 'lng' => 88.44, 'country' => 'India'), 585 => array('city' => 'Rājshāhī', 'lat' => 24.37, 'lng' => 88.59, 'country' => 'Bangladesh'), 586 => array('city' => 'Rānchi', 'lat' => 23.36, 'lng' => 85.33, 'country' => 'India'), 587 => array('city' => 'Rangoon', 'lat' => 16.79, 'lng' => 96.15, 'country' => 'Myanmar'), 588 => array('city' => 'Rāwalpindi', 'lat' => 33.60, 'lng' => 73.04, 'country' => 'Pakistan'), 589 => array('city' => 'Recife', 'lat' => -8.08, 'lng' => -34.92, 'country' => 'Brazil'), 590 => array('city' => 'Resht', 'lat' => 37.30, 'lng' => 49.63, 'country' => 'Iran'), 591 => array('city' => 'Reynosa', 'lat' => 26.09, 'lng' => -98.28, 'country' => 'Mexico'), 592 => array('city' => 'Ribeirão Preto', 'lat' => -21.17, 'lng' => -47.80, 'country' => 'Brazil'), 593 => array('city' => 'Rīga', 'lat' => 56.97, 'lng' => 24.13, 'country' => 'Latvia'), 594 => array('city' => 'Rio de Janeiro', 'lat' => -22.91, 'lng' => -43.20, 'country' => 'Brazil'), 595 => array('city' => 'Riyadh', 'lat' => 24.65, 'lng' => 46.77, 'country' => 'Saudi Arabia'), 596 => array('city' => 'Rome', 'lat' => 41.89, 'lng' => 12.50, 'country' => 'Italy'), 597 => array('city' => 'Rongcheng', 'lat' => 23.54, 'lng' => 116.34, 'country' => 'China'), 598 => array('city' => 'Rosario', 'lat' => -32.94, 'lng' => -60.67, 'country' => 'Argentina'), 599 => array('city' => 'Rostov-na-Donu', 'lat' => 47.24, 'lng' => 39.71, 'country' => 'Russia'), 600 => array('city' => 'Rotterdam', 'lat' => 51.93, 'lng' => 4.48, 'country' => 'Netherlands'), 601 => array('city' => 'Ryazan', 'lat' => 54.62, 'lng' => 39.74, 'country' => 'Russia'), 602 => array('city' => 'Sagamihara', 'lat' => 35.58, 'lng' => 139.38, 'country' => 'Japan'), 603 => array('city' => 'Sahāranpur', 'lat' => 29.97, 'lng' => 77.54, 'country' => 'India'), 604 => array('city' => 'Saint Petersburg', 'lat' => 59.93, 'lng' => 30.32, 'country' => 'Russia'), 605 => array('city' => 'Saitama', 'lat' => 35.87, 'lng' => 139.64, 'country' => 'Japan'), 606 => array('city' => 'Sakai', 'lat' => 34.57, 'lng' => 135.48, 'country' => 'Japan'), 607 => array('city' => 'Salem', 'lat' => 11.67, 'lng' => 78.16, 'country' => 'India'), 608 => array('city' => 'Salta', 'lat' => -24.79, 'lng' => -65.41, 'country' => 'Argentina'), 609 => array('city' => 'Saltillo', 'lat' => 25.43, 'lng' => -101.00, 'country' => 'Mexico'), 610 => array('city' => 'Salvador', 'lat' => -12.97, 'lng' => -38.50, 'country' => 'Brazil'), 611 => array('city' => 'Samara', 'lat' => 53.20, 'lng' => 50.15, 'country' => 'Russia'), 612 => array('city' => 'Samarinda', 'lat' => -0.50, 'lng' => 117.15, 'country' => 'Indonesia'), 613 => array('city' => 'Şan\'ā', 'lat' => 15.38, 'lng' => 44.21, 'country' => 'Yemen'), 614 => array('city' => 'San Antonio', 'lat' => 29.46, 'lng' => -98.51, 'country' => 'USA'), 615 => array('city' => 'San Diego', 'lat' => 32.81, 'lng' => -117.14, 'country' => 'USA'), 616 => array('city' => 'San Francisco', 'lat' => 37.77, 'lng' => -122.45, 'country' => 'USA'), 617 => array('city' => 'Sangli-Miraj', 'lat' => 16.86, 'lng' => 74.57, 'country' => 'India'), 618 => array('city' => 'San Jose', 'lat' => 37.30, 'lng' => -121.85, 'country' => 'USA'), 619 => array('city' => 'San Jose del Monte', 'lat' => 14.80, 'lng' => 120.88, 'country' => 'Philippines'), 620 => array('city' => 'San Luis Potosí', 'lat' => 22.15, 'lng' => -100.98, 'country' => 'Mexico'), 621 => array('city' => 'Sanmenxia', 'lat' => 34.83, 'lng' => 111.08, 'country' => 'China'), 622 => array('city' => 'San Pedro Sula', 'lat' => 15.47, 'lng' => -88.03, 'country' => 'Honduras'), 623 => array('city' => 'San Salvador', 'lat' => 13.69, 'lng' => -89.19, 'country' => 'El Salvador'), 624 => array('city' => 'Santa Cruz', 'lat' => -17.77, 'lng' => -63.21, 'country' => 'Bolivia'), 625 => array('city' => 'Santa Fé', 'lat' => -31.60, 'lng' => -60.69, 'country' => 'Argentina'), 626 => array('city' => 'Santiago', 'lat' => -33.46, 'lng' => -70.64, 'country' => 'Chile'), 627 => array('city' => 'Santiago', 'lat' => 19.48, 'lng' => -70.69, 'country' => 'Dominican Republic'), 628 => array('city' => 'Santiago de Querétaro', 'lat' => 20.59, 'lng' => -100.39, 'country' => 'Mexico'), 629 => array('city' => 'Santo André', 'lat' => -23.65, 'lng' => -46.53, 'country' => 'Brazil'), 630 => array('city' => 'Santo Domingo', 'lat' => 18.48, 'lng' => -69.91, 'country' => 'Dominican Republic'), 631 => array('city' => 'São Bernardo do Campo', 'lat' => -23.71, 'lng' => -46.54, 'country' => 'Brazil'), 632 => array('city' => 'São Gonçalo', 'lat' => -22.84, 'lng' => -43.07, 'country' => 'Brazil'), 633 => array('city' => 'São José dos Campos', 'lat' => -23.20, 'lng' => -45.88, 'country' => 'Brazil'), 634 => array('city' => 'São Luís', 'lat' => -2.50, 'lng' => -44.30, 'country' => 'Brazil'), 635 => array('city' => 'São Paulo', 'lat' => -23.53, 'lng' => -46.63, 'country' => 'Brazil'), 636 => array('city' => 'Sapporo', 'lat' => 43.06, 'lng' => 141.34, 'country' => 'Japan'), 637 => array('city' => 'Saratov', 'lat' => 51.57, 'lng' => 46.03, 'country' => 'Russia'), 638 => array('city' => 'Sargodha', 'lat' => 32.08, 'lng' => 72.67, 'country' => 'Pakistan'), 639 => array('city' => 'Seattle', 'lat' => 47.62, 'lng' => -122.35, 'country' => 'USA'), 640 => array('city' => 'Semarang', 'lat' => -6.97, 'lng' => 110.42, 'country' => 'Indonesia'), 641 => array('city' => 'Sendai', 'lat' => 38.26, 'lng' => 140.89, 'country' => 'Japan'), 642 => array('city' => 'Serang', 'lat' => -6.11, 'lng' => 106.15, 'country' => 'Indonesia'), 643 => array('city' => 'Sevilla', 'lat' => 37.40, 'lng' => -5.98, 'country' => 'Spain'), 644 => array('city' => 'Shanghai', 'lat' => 31.23, 'lng' => 121.47, 'country' => 'China'), 645 => array('city' => 'Shangrao', 'lat' => 28.47, 'lng' => 117.97, 'country' => 'China'), 646 => array('city' => 'Shantou', 'lat' => 23.37, 'lng' => 116.67, 'country' => 'China'), 647 => array('city' => 'Shaoguan', 'lat' => 24.80, 'lng' => 113.58, 'country' => 'China'), 648 => array('city' => 'Shaoxing', 'lat' => 30.00, 'lng' => 120.57, 'country' => 'China'), 649 => array('city' => 'Shaoyang', 'lat' => 27.00, 'lng' => 111.20, 'country' => 'China'), 650 => array('city' => 'Sharjah', 'lat' => 25.37, 'lng' => 55.41, 'country' => 'United Arab Emirates'), 651 => array('city' => 'Shashi', 'lat' => 30.32, 'lng' => 112.23, 'country' => 'China'), 652 => array('city' => 'Sha Tin', 'lat' => 22.38, 'lng' => 114.19, 'country' => 'China'), 653 => array('city' => 'Shenyang', 'lat' => 41.80, 'lng' => 123.45, 'country' => 'China'), 654 => array('city' => 'Shenzhen', 'lat' => 22.53, 'lng' => 114.13, 'country' => 'China'), 655 => array('city' => 'Shihezi', 'lat' => 44.30, 'lng' => 86.03, 'country' => 'China'), 656 => array('city' => 'Shijiazhuang', 'lat' => 38.05, 'lng' => 114.48, 'country' => 'China'), 657 => array('city' => 'Shilīguri', 'lat' => 26.73, 'lng' => 88.42, 'country' => 'India'), 658 => array('city' => 'Shiongshui', 'lat' => 22.52, 'lng' => 114.12, 'country' => 'China'), 659 => array('city' => 'Shīrāz', 'lat' => 29.63, 'lng' => 52.57, 'country' => 'Iran'), 660 => array('city' => 'Shizuoka', 'lat' => 34.98, 'lng' => 138.39, 'country' => 'Japan'), 661 => array('city' => 'Sholāpur', 'lat' => 17.67, 'lng' => 75.89, 'country' => 'India'), 662 => array('city' => 'Shubra-El-Khema', 'lat' => 30.11, 'lng' => 31.25, 'country' => 'Egypt'), 663 => array('city' => 'Siālkot', 'lat' => 32.52, 'lng' => 74.55, 'country' => 'Pakistan'), 664 => array('city' => 'Sihlangu', 'lat' => -27.75, 'lng' => 29.92, 'country' => 'South Africa'), 665 => array('city' => 'Singapore', 'lat' => 1.30, 'lng' => 103.85, 'country' => 'Singapore'), 666 => array('city' => 'Siping', 'lat' => 43.17, 'lng' => 124.33, 'country' => 'China'), 667 => array('city' => 'Soacha', 'lat' => 4.58, 'lng' => -74.22, 'country' => 'Colombia'), 668 => array('city' => 'Sofia', 'lat' => 42.69, 'lng' => 23.31, 'country' => 'Bulgaria'), 669 => array('city' => 'Soledad', 'lat' => 10.92, 'lng' => -74.77, 'country' => 'Colombia'), 670 => array('city' => 'Sŏngnam', 'lat' => 37.44, 'lng' => 127.15, 'country' => 'Korea (South)'), 671 => array('city' => 'Sorocaba', 'lat' => -23.49, 'lng' => -47.47, 'country' => 'Brazil'), 672 => array('city' => 'Sŏul', 'lat' => 37.56, 'lng' => 126.99, 'country' => 'Korea (South)'), 673 => array('city' => 'South Dum Dum', 'lat' => 22.61, 'lng' => 88.41, 'country' => 'India'), 674 => array('city' => 'Soweto', 'lat' => -26.28, 'lng' => 27.84, 'country' => 'South Africa'), 675 => array('city' => 'Srīnagar', 'lat' => 34.09, 'lng' => 74.79, 'country' => 'India'), 676 => array('city' => 'Stockholm', 'lat' => 59.33, 'lng' => 18.07, 'country' => 'Sweden'), 677 => array('city' => 'Stuttgart', 'lat' => 48.79, 'lng' => 9.19, 'country' => 'Germany'), 678 => array('city' => 'Sucheng', 'lat' => 33.95, 'lng' => 118.29, 'country' => 'China'), 679 => array('city' => 'Suez', 'lat' => 29.98, 'lng' => 32.54, 'country' => 'Egypt'), 680 => array('city' => 'Surabaya', 'lat' => -7.24, 'lng' => 112.74, 'country' => 'Indonesia'), 681 => array('city' => 'Sūrat', 'lat' => 21.20, 'lng' => 72.82, 'country' => 'India'), 682 => array('city' => 'Suwŏn', 'lat' => 37.26, 'lng' => 127.01, 'country' => 'Korea (South)'), 683 => array('city' => 'Suzhou', 'lat' => 31.30, 'lng' => 120.62, 'country' => 'China'), 684 => array('city' => 'Sydney', 'lat' => -33.87, 'lng' => 151.21, 'country' => 'Australia'), 685 => array('city' => 'Tabrīz', 'lat' => 38.08, 'lng' => 46.30, 'country' => 'Iran'), 686 => array('city' => 'Tabūk', 'lat' => 28.39, 'lng' => 36.57, 'country' => 'Saudi Arabia'), 687 => array('city' => 'Taegu', 'lat' => 35.87, 'lng' => 128.60, 'country' => 'Korea (South)'), 688 => array('city' => 'Taejŏn', 'lat' => 36.33, 'lng' => 127.43, 'country' => 'Korea (South)'), 689 => array('city' => 'Taian', 'lat' => 36.20, 'lng' => 117.12, 'country' => 'China'), 690 => array('city' => 'Táiběi', 'lat' => 25.02, 'lng' => 121.45, 'country' => 'Taiwan'), 691 => array('city' => 'Táinán', 'lat' => 23.00, 'lng' => 120.19, 'country' => 'Taiwan'), 692 => array('city' => 'Taiyuan', 'lat' => 37.87, 'lng' => 112.55, 'country' => 'China'), 693 => array('city' => 'Táizhōng', 'lat' => 24.15, 'lng' => 120.68, 'country' => 'Taiwan'), 694 => array('city' => 'Taizhou', 'lat' => 32.49, 'lng' => 119.90, 'country' => 'China'), 695 => array('city' => 'Ta\'izz', 'lat' => 13.60, 'lng' => 44.04, 'country' => 'Yemen'), 696 => array('city' => 'Tamale', 'lat' => 9.40, 'lng' => -0.84, 'country' => 'Ghana'), 697 => array('city' => 'Tambun', 'lat' => -6.27, 'lng' => 107.05, 'country' => 'Indonesia'), 698 => array('city' => 'Tanger', 'lat' => 35.79, 'lng' => -5.81, 'country' => 'Morocco'), 699 => array('city' => 'Tangerang', 'lat' => -6.18, 'lng' => 106.63, 'country' => 'Indonesia'), 700 => array('city' => 'Tanggu', 'lat' => 39.00, 'lng' => 117.67, 'country' => 'China'), 701 => array('city' => 'Tangshan', 'lat' => 39.62, 'lng' => 118.19, 'country' => 'China'), 702 => array('city' => 'Ţarābulus', 'lat' => 32.83, 'lng' => 13.08, 'country' => 'Libya'), 703 => array('city' => 'Tashkent', 'lat' => 41.31, 'lng' => 69.30, 'country' => 'Uzbekistan'), 704 => array('city' => 'Tasikmalaya', 'lat' => -7.32, 'lng' => 108.21, 'country' => 'Indonesia'), 705 => array('city' => 'Tbilisi', 'lat' => 41.72, 'lng' => 44.79, 'country' => 'Georgia'), 706 => array('city' => 'Tegucigalpa', 'lat' => 14.09, 'lng' => -87.22, 'country' => 'Honduras'), 707 => array('city' => 'Tehrān', 'lat' => 35.67, 'lng' => 51.43, 'country' => 'Iran'), 708 => array('city' => 'Tembisa', 'lat' => -25.99, 'lng' => 28.22, 'country' => 'South Africa'), 709 => array('city' => 'Teresina', 'lat' => -5.10, 'lng' => -42.80, 'country' => 'Brazil'), 710 => array('city' => 'Thāna', 'lat' => 19.20, 'lng' => 72.97, 'country' => 'India'), 711 => array('city' => 'Thiruvananthapuram', 'lat' => 8.51, 'lng' => 76.95, 'country' => 'India'), 712 => array('city' => 'Tianjin', 'lat' => 39.13, 'lng' => 117.20, 'country' => 'China'), 713 => array('city' => 'Tijuana', 'lat' => 32.53, 'lng' => -117.04, 'country' => 'Mexico'), 714 => array('city' => 'Tirana', 'lat' => 41.33, 'lng' => 19.82, 'country' => 'Albania'), 715 => array('city' => 'Tiruchchirāppalli', 'lat' => 10.81, 'lng' => 78.69, 'country' => 'India'), 716 => array('city' => 'Tirunelveli', 'lat' => 8.73, 'lng' => 77.69, 'country' => 'India'), 717 => array('city' => 'Tiruppur', 'lat' => 11.09, 'lng' => 77.35, 'country' => 'India'), 718 => array('city' => 'Tlalnepantla', 'lat' => 19.54, 'lng' => -99.19, 'country' => 'Mexico'), 719 => array('city' => 'Tlaquepaque', 'lat' => 20.64, 'lng' => -103.31, 'country' => 'Mexico'), 720 => array('city' => 'Tōkyō', 'lat' => 35.67, 'lng' => 139.77, 'country' => 'Japan'), 721 => array('city' => 'Toluca de Lerdo', 'lat' => 19.29, 'lng' => -99.65, 'country' => 'Mexico'), 722 => array('city' => 'Tolyatti', 'lat' => 53.48, 'lng' => 49.51, 'country' => 'Russia'), 723 => array('city' => 'Toronto', 'lat' => 43.65, 'lng' => -79.38, 'country' => 'Canada'), 724 => array('city' => 'Torreón', 'lat' => 25.54, 'lng' => -103.44, 'country' => 'Mexico'), 725 => array('city' => 'Trujillo', 'lat' => -8.11, 'lng' => -79.03, 'country' => 'Peru'), 726 => array('city' => 'Tshikapa', 'lat' => -6.41, 'lng' => 20.77, 'country' => 'Congo (Dem. Rep.)'), 727 => array('city' => 'Tucson', 'lat' => 32.20, 'lng' => -110.89, 'country' => 'USA'), 728 => array('city' => 'Tucumán', 'lat' => -26.83, 'lng' => -65.22, 'country' => 'Argentina'), 729 => array('city' => 'Tunis', 'lat' => 36.84, 'lng' => 10.22, 'country' => 'Tunisia'), 730 => array('city' => 'Turin', 'lat' => 45.08, 'lng' => 7.68, 'country' => 'Italy'), 731 => array('city' => 'Tuxtla Gutiérrez', 'lat' => 16.75, 'lng' => -93.12, 'country' => 'Mexico'), 732 => array('city' => 'Tyumen', 'lat' => 57.15, 'lng' => 65.53, 'country' => 'Russia'), 733 => array('city' => 'Uberlândia', 'lat' => -18.90, 'lng' => -48.28, 'country' => 'Brazil'), 734 => array('city' => 'Ufa', 'lat' => 54.78, 'lng' => 56.04, 'country' => 'Russia'), 735 => array('city' => 'Ujjain', 'lat' => 23.19, 'lng' => 75.78, 'country' => 'India'), 736 => array('city' => 'Ulaanbaatar', 'lat' => 47.93, 'lng' => 106.91, 'country' => 'Mongolia'), 737 => array('city' => 'Ulhāsnagar', 'lat' => 19.23, 'lng' => 73.15, 'country' => 'India'), 738 => array('city' => 'Ulsan', 'lat' => 35.55, 'lng' => 129.31, 'country' => 'Korea (South)'), 739 => array('city' => 'Ulyanovsk', 'lat' => 54.33, 'lng' => 48.40, 'country' => 'Russia'), 740 => array('city' => 'Umm Durmān', 'lat' => 15.65, 'lng' => 32.48, 'country' => 'Sudan'), 741 => array('city' => 'Urfa', 'lat' => 37.17, 'lng' => 38.79, 'country' => 'Turkey'), 742 => array('city' => 'Urumqi', 'lat' => 43.80, 'lng' => 87.58, 'country' => 'China'), 743 => array('city' => 'Vadodara', 'lat' => 22.31, 'lng' => 73.18, 'country' => 'India'), 744 => array('city' => 'Valencia', 'lat' => 10.23, 'lng' => -67.98, 'country' => 'Venezuela'), 745 => array('city' => 'Valencia', 'lat' => 39.48, 'lng' => -0.39, 'country' => 'Spain'), 746 => array('city' => 'Vancouver', 'lat' => 49.28, 'lng' => -123.13, 'country' => 'Canada'), 747 => array('city' => 'Vārānasī', 'lat' => 25.32, 'lng' => 83.01, 'country' => 'India'), 748 => array('city' => 'Veracruz', 'lat' => 19.19, 'lng' => -96.15, 'country' => 'Mexico'), 749 => array('city' => 'Victoria de Durango', 'lat' => 24.02, 'lng' => -104.65, 'country' => 'Mexico'), 750 => array('city' => 'Vienna', 'lat' => 48.22, 'lng' => 16.37, 'country' => 'Austria'), 751 => array('city' => 'Vijayawāda', 'lat' => 16.52, 'lng' => 80.63, 'country' => 'India'), 752 => array('city' => 'Villa Nueva', 'lat' => 14.53, 'lng' => -90.59, 'country' => 'Guatemala'), 753 => array('city' => 'Vilnius', 'lat' => 54.70, 'lng' => 25.27, 'country' => 'Lithuania'), 754 => array('city' => 'Visakhapatnam', 'lat' => 17.73, 'lng' => 83.30, 'country' => 'India'), 755 => array('city' => 'Vladivostok', 'lat' => 43.13, 'lng' => 131.90, 'country' => 'Russia'), 756 => array('city' => 'Volgograd', 'lat' => 48.71, 'lng' => 44.48, 'country' => 'Russia'), 757 => array('city' => 'Voronezh', 'lat' => 51.72, 'lng' => 39.26, 'country' => 'Russia'), 758 => array('city' => 'Warangal', 'lat' => 18.01, 'lng' => 79.58, 'country' => 'India'), 759 => array('city' => 'Warri', 'lat' => 5.52, 'lng' => 5.76, 'country' => 'Nigeria'), 760 => array('city' => 'Warsaw', 'lat' => 52.26, 'lng' => 21.02, 'country' => 'Poland'), 761 => array('city' => 'Washington', 'lat' => 38.91, 'lng' => -77.02, 'country' => 'USA'), 762 => array('city' => 'Welkom', 'lat' => -27.97, 'lng' => 26.73, 'country' => 'South Africa'), 763 => array('city' => 'Wenzhou', 'lat' => 28.02, 'lng' => 120.65, 'country' => 'China'), 764 => array('city' => 'Winnipeg', 'lat' => 49.88, 'lng' => -97.17, 'country' => 'Canada'), 765 => array('city' => 'Wrocław', 'lat' => 51.11, 'lng' => 17.03, 'country' => 'Poland'), 766 => array('city' => 'Wuhan', 'lat' => 30.58, 'lng' => 114.27, 'country' => 'China'), 767 => array('city' => 'Wuxi', 'lat' => 31.58, 'lng' => 120.30, 'country' => 'China'), 768 => array('city' => 'Xiamen', 'lat' => 24.45, 'lng' => 118.08, 'country' => 'China'), 769 => array('city' => 'Xian', 'lat' => 34.27, 'lng' => 108.90, 'country' => 'China'), 770 => array('city' => 'Xiangtan', 'lat' => 27.85, 'lng' => 112.90, 'country' => 'China'), 771 => array('city' => 'Xianyang', 'lat' => 34.37, 'lng' => 108.70, 'country' => 'China'), 772 => array('city' => 'Sai Kung', 'lat' => 22.33, 'lng' => 114.25, 'country' => 'China'), 773 => array('city' => 'Xingtai', 'lat' => 37.07, 'lng' => 114.49, 'country' => 'China'), 774 => array('city' => 'Xining', 'lat' => 36.62, 'lng' => 101.77, 'country' => 'China'), 775 => array('city' => 'Xinpu', 'lat' => 34.60, 'lng' => 119.17, 'country' => 'China'), 776 => array('city' => 'Xinxiang', 'lat' => 35.32, 'lng' => 113.87, 'country' => 'China'), 777 => array('city' => 'Xinyang', 'lat' => 32.13, 'lng' => 114.07, 'country' => 'China'), 778 => array('city' => 'Xuanhua', 'lat' => 40.60, 'lng' => 115.03, 'country' => 'China'), 779 => array('city' => 'Xuchang', 'lat' => 34.02, 'lng' => 113.82, 'country' => 'China'), 780 => array('city' => 'Xuzhou', 'lat' => 34.27, 'lng' => 117.18, 'country' => 'China'), 781 => array('city' => 'Yancheng', 'lat' => 33.39, 'lng' => 120.12, 'country' => 'China'), 782 => array('city' => 'Yangzhou', 'lat' => 32.40, 'lng' => 119.43, 'country' => 'China'), 783 => array('city' => 'Yantai', 'lat' => 37.53, 'lng' => 121.40, 'country' => 'China'), 784 => array('city' => 'Yaoundé', 'lat' => 3.87, 'lng' => 11.52, 'country' => 'Cameroon'), 785 => array('city' => 'Yaroslavl', 'lat' => 57.62, 'lng' => 39.87, 'country' => 'Russia'), 786 => array('city' => 'Yekaterinburg', 'lat' => 56.85, 'lng' => 60.60, 'country' => 'Russia'), 787 => array('city' => 'Yerevan', 'lat' => 40.17, 'lng' => 44.52, 'country' => 'Armenia'), 788 => array('city' => 'Yinchuan', 'lat' => 38.47, 'lng' => 106.32, 'country' => 'China'), 789 => array('city' => 'Yingkou', 'lat' => 40.67, 'lng' => 122.28, 'country' => 'China'), 790 => array('city' => 'Yokohama', 'lat' => 35.47, 'lng' => 139.62, 'country' => 'Japan'), 791 => array('city' => 'Yongin', 'lat' => 37.28, 'lng' => 127.12, 'country' => 'Korea (South)'), 792 => array('city' => 'Yuanlong', 'lat' => 22.44, 'lng' => 114.02, 'country' => 'China'), 793 => array('city' => 'Yueyang', 'lat' => 29.38, 'lng' => 113.10, 'country' => 'China'), 794 => array('city' => 'Zagreb', 'lat' => 45.80, 'lng' => 15.97, 'country' => 'Croatia'), 795 => array('city' => 'Zāhedān', 'lat' => 29.50, 'lng' => 60.83, 'country' => 'Iran'), 796 => array('city' => 'Zamboanga', 'lat' => 6.91, 'lng' => 122.07, 'country' => 'Philippines'), 797 => array('city' => 'Zanzibar', 'lat' => -6.16, 'lng' => 39.20, 'country' => 'Tanzania'), 798 => array('city' => 'Zapopan', 'lat' => 20.72, 'lng' => -103.39, 'country' => 'Mexico'), 799 => array('city' => 'Zaporizhzhya', 'lat' => 47.85, 'lng' => 35.17, 'country' => 'Ukraine'), 800 => array('city' => 'Zaragoza', 'lat' => 41.65, 'lng' => -0.89, 'country' => 'Spain'), 801 => array('city' => 'Zaria', 'lat' => 11.08, 'lng' => 7.71, 'country' => 'Nigeria'), 802 => array('city' => 'Zhangdian', 'lat' => 36.80, 'lng' => 118.06, 'country' => 'China'), 803 => array('city' => 'Zhangjiakou', 'lat' => 40.83, 'lng' => 114.93, 'country' => 'China'), 804 => array('city' => 'Zhangzhou', 'lat' => 24.52, 'lng' => 117.67, 'country' => 'China'), 805 => array('city' => 'Zhanjiang', 'lat' => 21.20, 'lng' => 110.38, 'country' => 'China'), 806 => array('city' => 'Zhengzhou', 'lat' => 34.75, 'lng' => 113.67, 'country' => 'China'), 807 => array('city' => 'Zhenjiang', 'lat' => 32.22, 'lng' => 119.43, 'country' => 'China'), 808 => array('city' => 'Zhuhai', 'lat' => 22.28, 'lng' => 113.57, 'country' => 'China'), 809 => array('city' => 'Zhunmen', 'lat' => 22.41, 'lng' => 113.98, 'country' => 'China'), 810 => array('city' => 'Zhuzhou', 'lat' => 27.83, 'lng' => 113.15, 'country' => 'China'), 811 => array('city' => 'Zigong', 'lat' => 29.40, 'lng' => 104.78, 'country' => 'China'), 812 => array('city' => 'Zunyi', 'lat' => 27.70, 'lng' => 106.92, 'country' => 'China'), 813 => array('city' => 'New Orleans', 'lat' => 29.97, 'lng' => -90.06, 'country' => 'USA'), 814 => array('city' => 'Springfield (MO)', 'lat' => 37.19, 'lng' => -93.29, 'country' => 'USA'), 815 => array('city' => 'Greenbelt', 'lat' => 39.00, 'lng' => -76.89, 'country' => 'USA'), 816 => array('city' => 'North Pole', 'lat' => 90.00, 'lng' => 0.00, 'country' => 'Earth'), 817 => array('city' => 'South Pole', 'lat' => -90.00, 'lng' => 0.00, 'country' => 'Earth'), 818 => array('city' => '(0°N, 0°E)', 'lat' => 0, 'lng' => 0, 'country' => 'Earth'), 819 => array('city' => 'Bermuda Triangle', 'lat' => 25.00, 'lng' => -71.00, 'country' => 'Earth') );
mit
mmnaseri/spring-data-mock
spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/sample/usecases/proxy/resolvers/SampleMappedRepository.java
413
package com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers; import org.springframework.data.jpa.repository.Query; /** * @author Milad Naseri (m.m.naseri@gmail.com) * @since 1.0 (4/12/16, 6:31 PM) */ public interface SampleMappedRepository { void mappedSignature(String string); void findByFirstName(String firstName); @Query void nativeMethod(); void normalMethodBy(); }
mit
ohler55/wabur
lib/wab/ui.rb
360
require 'wab' module WAB # Web Application Builder reference implemenation UI. module UI end end require 'wab/ui/display' require 'wab/ui/flow' require 'wab/ui/multi_flow' # These are the classes needed for the REST displays/flow. require 'wab/ui/rest_flow' require 'wab/ui/list' require 'wab/ui/view' require 'wab/ui/create' require 'wab/ui/update'
mit
josecols/fundahog
ayuda/admin.py
602
#!/usr/bin/python # -*- coding: utf-8 -*- # FUNDAHOG - Django 1.4 - Python 2.7.3 # Universidad Católica Andrés Bello Guayana # Desarrollado por José Cols - josecolsg@gmail.com - @josecols - (0414)8530463 from django.contrib import admin from ayuda.models import Seccion, Video from ayuda.forms import SeccionForm class SeccionAdmin(admin.ModelAdmin): form = SeccionForm filter_horizontal = ('videos',) class Media: js = ('/static/js/ckeditor/ckeditor.js', '/static/js/ckeditor/init.js') admin.site.register(Seccion, SeccionAdmin) admin.site.register(Video)
mit
LAPIS-Lazurite/test920j
lib/prog_write.rb
2985
# encoding: utf-8 require 'serialport' class Lazurite::Test def prog_write(devName,program,setting=true) @@testBin = @@testBin + 1 funcNum = 0 if setting == true then cmd = "sudo rmmod ftdi_sio" system(cmd) ret = $?.exitstatus funcNum = funcNum + 1 cmd = "sudo rmmod usbserial" system(cmd) ret = $?.exitstatus funcNum = funcNum + 1 cmd = sprintf("sudo ../lib/cpp/bootmode/bootmode \"%s\"",devName); system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = "sudo insmod "+@@kernel+"/kernel/drivers/usb/serial/usbserial.ko" system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = "sudo insmod "+@@kernel+"/kernel/drivers/usb/serial/ftdi_sio.ko" system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end end funcNum = funcNum + 1 sleep(0.1) cmd = "sudo stty -F " + @@com_target + " 115200" system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = sprintf("sudo sx -b %s > %s < %s",program,@@com_target,@@com_target) system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = "sudo rmmod ftdi_sio" system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = "sudo rmmod usbserial" system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = sprintf("sudo ../lib/cpp/reset/reset \"%s\"",devName); system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = "sudo insmod "+@@kernel +"/kernel/drivers/usb/serial/usbserial.ko" system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end funcNum = funcNum + 1 cmd = "sudo insmod "+@@kernel+"/kernel/drivers/usb/serial/ftdi_sio.ko" system(cmd) ret = $?.exitstatus print @@testBin,",",funcNum,",",cmd,",",ret,"\n" if ret != 0 then p @@testBin,funcNum,ret return @@testBin,funcNum,ret end return "OK" end end
mit
akshaysura/sitecoremvc
Code/SitecoreMVC/SitecoreMVC.ModelMaps/Base/FacebookMetadataMap.cs
463
using Glass.Mapper.Sc.Maps; using SitecoreMVC.Models.TemplateModels.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SitecoreMVC.ModelMaps.Base { public class FacebookMetadataMap : SitecoreGlassMap<IFacebookMetadata> { public override void Configure() { Map(x => { x.AutoMap(); }); } } }
mit
c-bit/c-bit
src/qt/test/paymentservertests.cpp
8386
// Copyright (c) 2009-2015 The C-Bit Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "paymentservertests.h" #include "optionsmodel.h" #include "paymentrequestdata.h" #include "amount.h" #include "random.h" #include "script/script.h" #include "script/standard.h" #include "util.h" #include "utilstrencodings.h" #include <openssl/x509.h> #include <openssl/x509_vfy.h> #include <QFileOpenEvent> #include <QTemporaryFile> X509 *parse_b64der_cert(const char* cert_data) { std::vector<unsigned char> data = DecodeBase64(cert_data); assert(data.size() > 0); const unsigned char* dptr = &data[0]; X509 *cert = d2i_X509(NULL, &dptr, data.size()); assert(cert); return cert; } // // Test payment request handling // static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsigned char>& data) { RecipientCatcher sigCatcher; QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), &sigCatcher, SLOT(getRecipient(SendCoinsRecipient))); // Write data to a temp file: QTemporaryFile f; f.open(); f.write((const char*)&data[0], data.size()); f.close(); // Create a QObject, install event filter from PaymentServer // and send a file open event to the object QObject object; object.installEventFilter(server); QFileOpenEvent event(f.fileName()); // If sending the event fails, this will cause sigCatcher to be empty, // which will lead to a test failure anyway. QCoreApplication::sendEvent(&object, &event); QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), &sigCatcher, SLOT(getRecipient(SendCoinsRecipient))); // Return results from sigCatcher return sigCatcher.recipient; } void PaymentServerTests::paymentServerTests() { SelectParams(CBaseChainParams::MAIN); OptionsModel optionsModel; PaymentServer* server = new PaymentServer(NULL, false); X509_STORE* caStore = X509_STORE_new(); X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64)); PaymentServer::LoadRootCAs(caStore); server->setOptionsModel(&optionsModel); server->uiReady(); std::vector<unsigned char> data; SendCoinsRecipient r; QString merchant; // Now feed PaymentRequests to server, and observe signals it produces // This payment request validates directly against the // caCert1 certificate authority: data = DecodeBase64(paymentrequest1_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("testmerchant.org")); // Signed, but expired, merchant cert in the request: data = DecodeBase64(paymentrequest2_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // 10-long certificate chain, all intermediates valid: data = DecodeBase64(paymentrequest3_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("testmerchant8.org")); // Long certificate chain, with an expired certificate in the middle: data = DecodeBase64(paymentrequest4_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // Validly signed, but by a CA not in our root CA list: data = DecodeBase64(paymentrequest5_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // Try again with no root CA's, verifiedMerchant should be empty: caStore = X509_STORE_new(); PaymentServer::LoadRootCAs(caStore); data = DecodeBase64(paymentrequest1_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // Load second root certificate caStore = X509_STORE_new(); X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64)); PaymentServer::LoadRootCAs(caStore); QByteArray byteArray; // For the tests below we just need the payment request data from // paymentrequestdata.h parsed + stored in r.paymentRequest. // // These tests require us to bypass the following normal client execution flow // shown below to be able to explicitly just trigger a certain condition! // // handleRequest() // -> PaymentServer::eventFilter() // -> PaymentServer::handleURIOrFile() // -> PaymentServer::readPaymentRequestFromFile() // -> PaymentServer::processPaymentRequest() // Contains a testnet paytoaddress, so payment request network doesn't match client network: data = DecodeBase64(paymentrequest1_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized, because network "main" is default, even for // uninizialized payment requests and that will fail our test here. QVERIFY(r.paymentRequest.IsInitialized()); QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false); // Expired payment request (expires is set to 1 = 1970-01-01 00:00:01): data = DecodeBase64(paymentrequest2_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // compares 1 < GetTime() == false (treated as expired payment request) QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true); // Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t): // 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t) // -1 is 1969-12-31 23:59:59 (for a 32 bit time values) data = DecodeBase64(paymentrequest3_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request) QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false); // Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64): // 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t) // 0 is 1970-01-01 00:00:00 (for a 32 bit time values) data = DecodeBase64(paymentrequest4_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // compares -9223372036854775808 < GetTime() == true (treated as expired payment request) QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true); // Test BIP70 DoS protection: unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1]; GetRandBytes(randData, sizeof(randData)); // Write data to a temp file: QTemporaryFile tempFile; tempFile.open(); tempFile.write((const char*)randData, sizeof(randData)); tempFile.close(); // compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false QCOMPARE(PaymentServer::verifySize(tempFile.size()), false); // Payment request with amount overflow (amount is set to 21000001 XCT): data = DecodeBase64(paymentrequest5_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // Extract address and amount from the request QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo(); Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) { CTxDestination dest; if (ExtractDestination(sendingTo.first, dest)) QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false); } delete server; } void RecipientCatcher::getRecipient(SendCoinsRecipient r) { recipient = r; }
mit
GrottoPress/jentil
app/libraries/Jentil/Utilities/Page/Layout.php
2453
<?php declare (strict_types = 1); namespace GrottoPress\Jentil\Utilities\Page; use GrottoPress\Jentil\Utilities\Page; use GrottoPress\Jentil\Utilities\ThemeMods\Layout as LayoutMod; class Layout { /** * @var Page */ private $page; public function __construct(Page $page) { $this->page = $page; } public function themeMod(): LayoutMod { $page = $this->page->type; $specific = ''; $more_specific = 0; foreach ($page as $type) { if ('post_type_archive' === $type) { $specific = \get_query_var('post_type'); } elseif ('tax' === $type) { $specific = \get_query_var('taxonomy'); } elseif ('category' === $type) { $specific = 'category'; } elseif ('tag' === $type) { $specific = 'post_tag'; } elseif ('singular' === $type) { $specific = ($post = \get_post())->post_type; if ($this->isPagelike($post->post_type, $post->ID)) { $more_specific = $post->ID; } } if (\is_array($specific)) { $specific = $specific[0]; } if (\is_array($more_specific)) { $more_specific = $more_specific[0]; } $mod = $this->page->utilities->themeMods->layout([ 'context' => $type, 'specific' => $specific, 'more_specific' => $more_specific ]); if ($mod->id) { return $mod; } } return $mod; } public function column(): string { foreach ($this->page->layouts->get() as $column_slug => $layouts) { foreach ($layouts as $layout_id => $layout_name) { if ($this->themeMod()->get() === $layout_id) { return \sanitize_title($column_slug); } } } return ''; } public function isPagelike(string $post_type = '', int $post_id = 0): bool { $check = ( \is_post_type_hierarchical($post_type) && !\get_post_type_archive_link($post_type) ); if ($check && $post_id && ('page' === \get_option('show_on_front'))) { return ($post_id !== (int)\get_option('page_for_posts')); } return $check; } }
mit
lildude/twitter
data/js/tweets/2019_05.js
102790
Grailbird.data.tweets_2019_05 = [ { "created_at": "Thu May 30 17:12:44 +0000 2019", "id": 1134145631566610400, "id_str": "1134145631566610432", "text": "RT @scott_riley: Unpopular opinion: prefacing your shit take with \"unpopular opinion\" does not give you carte blanche on being an insuffera…", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "scott_riley", "name": "Scott 🐙", "id": 36305390, "id_str": "36305390", "indices": [ 3, 15 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃‍♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 991, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5545, "lang": null, "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "retweeted_status": { "created_at": "Thu May 30 12:25:31 +0000 2019", "id": 1134073352518287400, "id_str": "1134073352518287360", "text": "Unpopular opinion: prefacing your shit take with \"unpopular opinion\" does not give you carte blanche on being an insufferable cunt.", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [] }, "source": "<a href=\"https://mobile.twitter.com\" rel=\"nofollow\">Twitter Web App</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 36305390, "id_str": "36305390", "name": "Scott 🐙", "screen_name": "scott_riley", "location": "Nottingham", "description": "🎨 Designer & mental health advocate ᗈ\n🍳 Sentient brunch ᗈ\n🥺 Professional sad boi ᗈ\n🧠 Buy my fuckin book: https://t.co/G5WXG0tuvy", "url": null, "entities": { "description": { "urls": [ { "url": "https://t.co/G5WXG0tuvy", "expanded_url": "https://mindfuldesign.xyz", "display_url": "mindfuldesign.xyz", "indices": [ 105, 128 ] } ] } }, "protected": false, "followers_count": 3970, "friends_count": 668, "listed_count": 180, "created_at": "Wed Apr 29 06:35:57 +0000 2009", "favourites_count": 25508, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 24914, "lang": null, "contributors_enabled": false, "is_translator": false, "is_translation_enabled": true, "profile_background_color": "F5F5F5", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme15/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme15/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/1099372088442454016/V7ZRTImz_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/1099372088442454016/V7ZRTImz_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/36305390/1550947030", "profile_link_color": "FAB81E", "profile_sidebar_border_color": "FFFFFF", "profile_sidebar_fill_color": "C0DFEC", "profile_text_color": "333333", "profile_use_background_image": true, "has_extended_profile": true, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 6, "favorite_count": 73, "favorited": true, "retweeted": true, "lang": "en" }, "is_quote_status": false, "retweet_count": 6, "favorite_count": 0, "favorited": true, "retweeted": true, "lang": "en" }, { "created_at": "Thu May 30 17:11:27 +0000 2019", "id": 1134145310018740200, "id_str": "1134145310018740224", "text": "RT @james_s_white: If you use @SlackHQ threads to reply to me, I'm just going to assume we were having a conversation and you walked out of…", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "james_s_white", "name": "One of your dependencies may have a security vuln", "id": 16439529, "id_str": "16439529", "indices": [ 3, 17 ] }, { "screen_name": "SlackHQ", "name": "Slack", "id": 1305940272, "id_str": "1305940272", "indices": [ 30, 38 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃‍♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 991, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5545, "lang": null, "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "retweeted_status": { "created_at": "Thu May 30 12:23:26 +0000 2019", "id": 1134072827865378800, "id_str": "1134072827865378817", "text": "If you use @SlackHQ threads to reply to me, I'm just going to assume we were having a conversation and you walked o… https://t.co/tEhMXr4NDP", "truncated": true, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "SlackHQ", "name": "Slack", "id": 1305940272, "id_str": "1305940272", "indices": [ 11, 19 ] } ], "urls": [ { "url": "https://t.co/tEhMXr4NDP", "expanded_url": "https://twitter.com/i/web/status/1134072827865378817", "display_url": "twitter.com/i/web/status/1…", "indices": [ 117, 140 ] } ] }, "source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 16439529, "id_str": "16439529", "name": "One of your dependencies may have a security vuln", "screen_name": "james_s_white", "location": "Nashville, TN", "description": "GitHubber, Nair for Yaks", "url": "https://t.co/PtinVFr500", "entities": { "url": { "urls": [ { "url": "https://t.co/PtinVFr500", "expanded_url": "http://www.jameswhite.org", "display_url": "jameswhite.org", "indices": [ 0, 23 ] } ] }, "description": { "urls": [] } }, "protected": false, "followers_count": 722, "friends_count": 605, "listed_count": 42, "created_at": "Wed Sep 24 19:34:57 +0000 2008", "favourites_count": 2206, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 7831, "lang": null, "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "9AE4E8", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/1081598356953034753/uw9RRU90_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/1081598356953034753/uw9RRU90_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/16439529/1404393772", "profile_link_color": "0084B4", "profile_sidebar_border_color": "BDDCAD", "profile_sidebar_fill_color": "DDFFCC", "profile_text_color": "333333", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": true, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 2, "favorite_count": 11, "favorited": true, "retweeted": true, "lang": "en" }, "is_quote_status": false, "retweet_count": 2, "favorite_count": 0, "favorited": true, "retweeted": true, "lang": "en" }, { "created_at": "Thu May 30 12:06:25 +0000 2019", "id": 1134068542041657300, "id_str": "1134068542041657345", "text": "Sorry boss, gonna be a little distracted for the next month and a bit; I've moved to my summer office for the crick… https://t.co/rqh9FIneqr", "truncated": true, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [ { "url": "https://t.co/rqh9FIneqr", "expanded_url": "https://twitter.com/i/web/status/1134068542041657345", "display_url": "twitter.com/i/web/status/1…", "indices": [ 117, 140 ] } ] }, "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃‍♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 991, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5545, "lang": null, "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 2, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Sat May 25 19:11:34 +0000 2019", "id": 1132363597177413600, "id_str": "1132363597177413632", "text": "This is how you troll foreigners (even the English speakers) when they visit Reading, pronounced \"redding\" 🤣😂 https://t.co/n2ZYHCk9s0", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [], "media": [ { "id": 1132363596132958200, "id_str": "1132363596132958220", "indices": [ 110, 133 ], "media_url": "http://pbs.twimg.com/media/D7b2sPAWwAwqxu4.jpg", "media_url_https": "https://pbs.twimg.com/media/D7b2sPAWwAwqxu4.jpg", "url": "https://t.co/n2ZYHCk9s0", "display_url": "pic.twitter.com/n2ZYHCk9s0", "expanded_url": "https://twitter.com/lildude/status/1132363597177413632/photo/1", "type": "photo", "sizes": { "thumb": { "w": 150, "h": 150, "resize": "crop" }, "large": { "w": 1024, "h": 1024, "resize": "fit" }, "small": { "w": 680, "h": 680, "resize": "fit" }, "medium": { "w": 1024, "h": 1024, "resize": "fit" } } } ] }, "extended_entities": { "media": [ { "id": 1132363596132958200, "id_str": "1132363596132958220", "indices": [ 110, 133 ], "media_url": "http://pbs.twimg.com/media/D7b2sPAWwAwqxu4.jpg", "media_url_https": "https://pbs.twimg.com/media/D7b2sPAWwAwqxu4.jpg", "url": "https://t.co/n2ZYHCk9s0", "display_url": "pic.twitter.com/n2ZYHCk9s0", "expanded_url": "https://twitter.com/lildude/status/1132363597177413632/photo/1", "type": "photo", "sizes": { "thumb": { "w": 150, "h": 150, "resize": "crop" }, "large": { "w": 1024, "h": 1024, "resize": "fit" }, "small": { "w": 680, "h": 680, "resize": "fit" }, "medium": { "w": 1024, "h": 1024, "resize": "fit" } } } ] }, "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 527, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 989, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5542, "lang": null, "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Tue May 21 21:09:28 +0000 2019", "id": 1130943716141752300, "id_str": "1130943716141752321", "text": "This is definitely my best batch of patacones/tostones ever, thanks to using a block of lard for the frying 😋 https://t.co/3wfI1fLjNj", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [], "media": [ { "id": 1130943714774405100, "id_str": "1130943714774405121", "indices": [ 110, 133 ], "media_url": "http://pbs.twimg.com/media/D7HrUQwW0AEDAT6.jpg", "media_url_https": "https://pbs.twimg.com/media/D7HrUQwW0AEDAT6.jpg", "url": "https://t.co/3wfI1fLjNj", "display_url": "pic.twitter.com/3wfI1fLjNj", "expanded_url": "https://twitter.com/lildude/status/1130943716141752321/photo/1", "type": "photo", "sizes": { "medium": { "w": 1024, "h": 1022, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "large": { "w": 1024, "h": 1022, "resize": "fit" }, "small": { "w": 680, "h": 679, "resize": "fit" } } } ] }, "extended_entities": { "media": [ { "id": 1130943714774405100, "id_str": "1130943714774405121", "indices": [ 110, 133 ], "media_url": "http://pbs.twimg.com/media/D7HrUQwW0AEDAT6.jpg", "media_url_https": "https://pbs.twimg.com/media/D7HrUQwW0AEDAT6.jpg", "url": "https://t.co/3wfI1fLjNj", "display_url": "pic.twitter.com/3wfI1fLjNj", "expanded_url": "https://twitter.com/lildude/status/1130943716141752321/photo/1", "type": "photo", "sizes": { "medium": { "w": 1024, "h": 1022, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "large": { "w": 1024, "h": 1022, "resize": "fit" }, "small": { "w": 680, "h": 679, "resize": "fit" } } } ] }, "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1004, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5542, "lang": null, "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Sat May 18 18:39:01 +0000 2019", "id": 1129818692055982100, "id_str": "1129818692055982080", "text": "@tabamatu Is that a new beer? 😜", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "tabamatu", "name": "Andy Parker", "id": 19486018, "id_str": "19486018", "indices": [ 0, 9 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1129813007192797200, "in_reply_to_status_id_str": "1129813007192797186", "in_reply_to_user_id": 19486018, "in_reply_to_user_id_str": "19486018", "in_reply_to_screen_name": "tabamatu", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1005, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5541, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Sat May 18 16:26:39 +0000 2019", "id": 1129785377500422100, "id_str": "1129785377500422150", "text": "@tabamatu @SirenCraftBrew @sjehoile Delight (which I found myself in the front of the queue for without even trying… https://t.co/ILz6X77onH", "truncated": true, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "tabamatu", "name": "Andy Parker", "id": 19486018, "id_str": "19486018", "indices": [ 0, 9 ] }, { "screen_name": "SirenCraftBrew", "name": "Siren Craft Brew", "id": 945733406, "id_str": "945733406", "indices": [ 10, 25 ] }, { "screen_name": "sjehoile", "name": "Steve Hoile", "id": 2353583588, "id_str": "2353583588", "indices": [ 26, 35 ] } ], "urls": [ { "url": "https://t.co/ILz6X77onH", "expanded_url": "https://twitter.com/i/web/status/1129785377500422150", "display_url": "twitter.com/i/web/status/1…", "indices": [ 117, 140 ] } ] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1129779750099198000, "in_reply_to_status_id_str": "1129779750099197953", "in_reply_to_user_id": 8812362, "in_reply_to_user_id_str": "8812362", "in_reply_to_screen_name": "lildude", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1005, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5541, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Sat May 18 16:04:17 +0000 2019", "id": 1129779750099198000, "id_str": "1129779750099197953", "text": "@tabamatu @SirenCraftBrew @sjehoile Indeed. Fantastic beer!!! 👏👏👏 @SirenCraftBrew", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "tabamatu", "name": "Andy Parker", "id": 19486018, "id_str": "19486018", "indices": [ 0, 9 ] }, { "screen_name": "SirenCraftBrew", "name": "Siren Craft Brew", "id": 945733406, "id_str": "945733406", "indices": [ 10, 25 ] }, { "screen_name": "sjehoile", "name": "Steve Hoile", "id": 2353583588, "id_str": "2353583588", "indices": [ 26, 35 ] }, { "screen_name": "SirenCraftBrew", "name": "Siren Craft Brew", "id": 945733406, "id_str": "945733406", "indices": [ 66, 81 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1129765329842954200, "in_reply_to_status_id_str": "1129765329842954240", "in_reply_to_user_id": 19486018, "in_reply_to_user_id_str": "19486018", "in_reply_to_screen_name": "tabamatu", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1005, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5541, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Sat May 18 15:01:15 +0000 2019", "id": 1129763889393086500, "id_str": "1129763889393086466", "text": "Look at me coming to a beer festival all prepared with my own meaty snacks. Biltong &amp; droëwors go so well with craf… https://t.co/szis8gqO89", "truncated": true, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [ { "url": "https://t.co/szis8gqO89", "expanded_url": "https://twitter.com/i/web/status/1129763889393086466", "display_url": "twitter.com/i/web/status/1…", "indices": [ 121, 144 ] } ] }, "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 285, "listed_count": 17, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1005, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5541, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Thu May 16 17:38:23 +0000 2019", "id": 1129078657169989600, "id_str": "1129078657169989637", "text": "@lukehefson Oh yes, and the boerewors and biltong weren't delivered until today 😁", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "lukehefson", "name": "Luke Hefson", "id": 19663455, "id_str": "19663455", "indices": [ 0, 11 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1129076696349630500, "in_reply_to_status_id_str": "1129076696349630464", "in_reply_to_user_id": 19663455, "in_reply_to_user_id_str": "19663455", "in_reply_to_screen_name": "lukehefson", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7BR5o", "url": "https://t.co/3MoMsEwP9E", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEwP9E", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7BR5o", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1004, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5537, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1557591320", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Thu May 16 17:34:37 +0000 2019", "id": 1129077709039132700, "id_str": "1129077709039132679", "text": "@lukehefson But you live by the sea; you get summer more often than us in-landers 😜", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "lukehefson", "name": "Luke Hefson", "id": 19663455, "id_str": "19663455", "indices": [ 0, 11 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1129076696349630500, "in_reply_to_status_id_str": "1129076696349630464", "in_reply_to_user_id": 19663455, "in_reply_to_user_id_str": "19663455", "in_reply_to_screen_name": "lukehefson", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7BR5o", "url": "https://t.co/3MoMsEwP9E", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEwP9E", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7BR5o", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1004, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5537, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1557591320", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Thu May 16 16:51:38 +0000 2019", "id": 1129066890591129600, "id_str": "1129066890591129600", "text": "I declare 🇬🇧 summer 2019 officially open!!! 😎 Just fired up the braai for the first time this year 🤘.", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [] }, "source": "<a href=\"https://about.twitter.com/products/tweetdeck\" rel=\"nofollow\">TweetDeck</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7BR5o", "url": "https://t.co/3MoMsEwP9E", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEwP9E", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7BR5o", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1004, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5537, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1557591320", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Sun May 12 14:51:13 +0000 2019", "id": 1127587036385423400, "id_str": "1127587036385423360", "text": "RT @benbloomsport: 1. Just look how far out he launches the dive.\n2. The face plant at the end. What a face plant.\n3. His name is Infinite…", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "benbloomsport", "name": "Ben Bloom", "id": 403477834, "id_str": "403477834", "indices": [ 3, 17 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7BR5o", "url": "https://t.co/3MoMsEwP9E", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEwP9E", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7BR5o", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 284, "listed_count": 0, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1001, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5535, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1557591320", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "retweeted_status": { "created_at": "Sun May 12 06:28:23 +0000 2019", "id": 1127460493025669100, "id_str": "1127460493025669120", "text": "1. Just look how far out he launches the dive.\n2. The face plant at the end. What a face plant.\n3. His name is Infi… https://t.co/deGtEHL0LW", "truncated": true, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [ { "url": "https://t.co/deGtEHL0LW", "expanded_url": "https://twitter.com/i/web/status/1127460493025669120", "display_url": "twitter.com/i/web/status/1…", "indices": [ 117, 140 ] } ] }, "source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 403477834, "id_str": "403477834", "name": "Ben Bloom", "screen_name": "benbloomsport", "location": "", "description": "Journalist for @TelegraphSport. Athletics Correspondent in summer and other sports in winter.", "url": "https://t.co/taRhmIBmUQ", "entities": { "url": { "urls": [ { "url": "https://t.co/taRhmIBmUQ", "expanded_url": "http://www.telegraph.co.uk/authors/ben-bloom/", "display_url": "telegraph.co.uk/authors/ben-bl…", "indices": [ 0, 23 ] } ] }, "description": { "urls": [] } }, "protected": false, "followers_count": 6174, "friends_count": 594, "listed_count": 101, "created_at": "Wed Nov 02 15:13:31 +0000 2011", "favourites_count": 6, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": true, "statuses_count": 4408, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "C0DEED", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/850817370918662148/u6EwnVo3_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/850817370918662148/u6EwnVo3_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/403477834/1503418474", "profile_link_color": "1DA1F2", "profile_sidebar_border_color": "C0DEED", "profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "333333", "profile_use_background_image": true, "has_extended_profile": false, "default_profile": true, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 346, "favorite_count": 1306, "favorited": false, "retweeted": true, "possibly_sensitive": false, "lang": "en" }, "is_quote_status": false, "retweet_count": 346, "favorite_count": 0, "favorited": false, "retweeted": true, "lang": "en" }, { "created_at": "Sat May 11 18:12:32 +0000 2019", "id": 1127275311010406400, "id_str": "1127275311010406400", "text": "@tabamatu 🤫 I won't tell anyone if you don't 😉", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "tabamatu", "name": "Andy Parker", "id": 19486018, "id_str": "19486018", "indices": [ 0, 9 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1127272551321874400, "in_reply_to_status_id_str": "1127272551321874432", "in_reply_to_user_id": 19486018, "in_reply_to_user_id_str": "19486018", "in_reply_to_screen_name": "tabamatu", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7BR5o", "url": "https://t.co/3MoMsEwP9E", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEwP9E", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7BR5o", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1001, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5534, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1557591320", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Sat May 11 17:54:31 +0000 2019", "id": 1127270775432597500, "id_str": "1127270775432597504", "text": "@tabamatu #BIPACOMEBACK doesn't need a companion 😂🤣", "truncated": false, "entities": { "hashtags": [ { "text": "BIPACOMEBACK", "indices": [ 10, 23 ] } ], "symbols": [], "user_mentions": [ { "screen_name": "tabamatu", "name": "Andy Parker", "id": 19486018, "id_str": "19486018", "indices": [ 0, 9 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1127261817246449700, "in_reply_to_status_id_str": "1127261817246449665", "in_reply_to_user_id": 19486018, "in_reply_to_user_id_str": "19486018", "in_reply_to_screen_name": "tabamatu", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7BR5o", "url": "https://t.co/3MoMsEwP9E", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEwP9E", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7BR5o", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1001, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5534, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1557591320", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Sat May 11 15:53:33 +0000 2019", "id": 1127240334252048400, "id_str": "1127240334252048384", "text": "@shiftkey @haacked @vcsjones @GitHubDesktop 👏👏👏 took you long enough 😜", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "shiftkey", "name": "brendan forster 🇨🇦", "id": 14671135, "id_str": "14671135", "indices": [ 0, 9 ] }, { "screen_name": "haacked", "name": "Boom Haackalacka", "id": 768197, "id_str": "768197", "indices": [ 10, 18 ] }, { "screen_name": "vcsjones", "name": "Kevin Jones 🏒🏳️🌈", "id": 23236722, "id_str": "23236722", "indices": [ 19, 28 ] }, { "screen_name": "GitHubDesktop", "name": "GitHub Desktop", "id": 872108011719983100, "id_str": "872108011719983106", "indices": [ 29, 43 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1127233189242712000, "in_reply_to_status_id_str": "1127233189242712064", "in_reply_to_user_id": 14671135, "in_reply_to_user_id_str": "14671135", "in_reply_to_screen_name": "shiftkey", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7BR5o", "url": "https://t.co/3MoMsEwP9E", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEwP9E", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7BR5o", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 528, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 1001, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5534, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1557591320", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Mon May 06 19:09:41 +0000 2019", "id": 1125477753543974900, "id_str": "1125477753543974912", "text": "🏃♂️: Oooo, a 🦌 in a farmer's field next to the woods.\n🦌: Oooo, a 🏃♂️ in the woods next to a farmer's field. #run… https://t.co/cwQIrFswPh", "truncated": true, "entities": { "hashtags": [ { "text": "run", "indices": [ 110, 114 ] } ], "symbols": [], "user_mentions": [], "urls": [ { "url": "https://t.co/cwQIrFswPh", "expanded_url": "https://twitter.com/i/web/status/1125477753543974912", "display_url": "twitter.com/i/web/status/1…", "indices": [ 116, 139 ] } ] }, "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 530, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 996, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5532, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Sun May 05 18:33:33 +0000 2019", "id": 1125106274629189600, "id_str": "1125106274629189637", "text": "@beckiblairjones is this how your haircut in Ibiza went? 😂🤣 https://t.co/1pTMomJ75v", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "beckiblairjones", "name": "Becki BlairJones", "id": 82072414, "id_str": "82072414", "indices": [ 0, 16 ] } ], "urls": [ { "url": "https://t.co/1pTMomJ75v", "expanded_url": "https://youtu.be/XZY4ovo5hjM", "display_url": "youtu.be/XZY4ovo5hjM", "indices": [ 60, 83 ] } ] }, "source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": 82072414, "in_reply_to_user_id_str": "82072414", "in_reply_to_screen_name": "beckiblairjones", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 530, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 996, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5531, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 3, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Thu May 02 19:09:50 +0000 2019", "id": 1124028241218555900, "id_str": "1124028241218555909", "text": "I don't wear dressing gowns but I might be tempted with one of these, but for modern local craft breweries. #beer… https://t.co/Tvhy4MlZAB", "truncated": true, "entities": { "hashtags": [ { "text": "beer", "indices": [ 109, 114 ] } ], "symbols": [], "user_mentions": [], "urls": [ { "url": "https://t.co/Tvhy4MlZAB", "expanded_url": "https://twitter.com/i/web/status/1124028241218555909", "display_url": "twitter.com/i/web/status/1…", "indices": [ 116, 139 ] } ] }, "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 996, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5530, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Thu May 02 18:29:31 +0000 2019", "id": 1124018092143710200, "id_str": "1124018092143710211", "text": "@JockItch96 Adorable!!! RT as requested Sir.", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "JockItch96", "name": "Ben Martin-Dye", "id": 98069620, "id_str": "98069620", "indices": [ 0, 11 ] } ], "urls": [] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1124010580812103700, "in_reply_to_status_id_str": "1124010580812103680", "in_reply_to_user_id": 98069620, "in_reply_to_user_id_str": "98069620", "in_reply_to_screen_name": "JockItch96", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 996, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5530, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 1, "favorited": false, "retweeted": false, "lang": "es" }, { "created_at": "Thu May 02 18:28:47 +0000 2019", "id": 1124017908210966500, "id_str": "1124017908210966529", "text": "RT @JockItch96: Retweet! https://t.co/zKfx7QkZWo", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "JockItch96", "name": "Ben Martin-Dye", "id": 98069620, "id_str": "98069620", "indices": [ 3, 14 ] } ], "urls": [], "media": [ { "id": 1124010573883220000, "id_str": "1124010573883219969", "indices": [ 25, 48 ], "media_url": "http://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "media_url_https": "https://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "url": "https://t.co/zKfx7QkZWo", "display_url": "pic.twitter.com/zKfx7QkZWo", "expanded_url": "https://twitter.com/JockItch96/status/1124010580812103680/photo/1", "type": "photo", "sizes": { "large": { "w": 1152, "h": 2048, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 675, "h": 1200, "resize": "fit" }, "small": { "w": 383, "h": 680, "resize": "fit" } }, "source_status_id": 1124010580812103700, "source_status_id_str": "1124010580812103680", "source_user_id": 98069620, "source_user_id_str": "98069620" } ] }, "extended_entities": { "media": [ { "id": 1124010573883220000, "id_str": "1124010573883219969", "indices": [ 25, 48 ], "media_url": "http://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "media_url_https": "https://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "url": "https://t.co/zKfx7QkZWo", "display_url": "pic.twitter.com/zKfx7QkZWo", "expanded_url": "https://twitter.com/JockItch96/status/1124010580812103680/photo/1", "type": "photo", "sizes": { "large": { "w": 1152, "h": 2048, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 675, "h": 1200, "resize": "fit" }, "small": { "w": 383, "h": 680, "resize": "fit" } }, "source_status_id": 1124010580812103700, "source_status_id_str": "1124010580812103680", "source_user_id": 98069620, "source_user_id_str": "98069620" } ] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 996, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5530, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "retweeted_status": { "created_at": "Thu May 02 17:59:40 +0000 2019", "id": 1124010580812103700, "id_str": "1124010580812103680", "text": "Retweet! https://t.co/zKfx7QkZWo", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [], "media": [ { "id": 1124010573883220000, "id_str": "1124010573883219969", "indices": [ 9, 32 ], "media_url": "http://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "media_url_https": "https://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "url": "https://t.co/zKfx7QkZWo", "display_url": "pic.twitter.com/zKfx7QkZWo", "expanded_url": "https://twitter.com/JockItch96/status/1124010580812103680/photo/1", "type": "photo", "sizes": { "large": { "w": 1152, "h": 2048, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 675, "h": 1200, "resize": "fit" }, "small": { "w": 383, "h": 680, "resize": "fit" } } } ] }, "extended_entities": { "media": [ { "id": 1124010573883220000, "id_str": "1124010573883219969", "indices": [ 9, 32 ], "media_url": "http://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "media_url_https": "https://pbs.twimg.com/media/D5lJqWQXoAElnyd.jpg", "url": "https://t.co/zKfx7QkZWo", "display_url": "pic.twitter.com/zKfx7QkZWo", "expanded_url": "https://twitter.com/JockItch96/status/1124010580812103680/photo/1", "type": "photo", "sizes": { "large": { "w": 1152, "h": 2048, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 675, "h": 1200, "resize": "fit" }, "small": { "w": 383, "h": 680, "resize": "fit" } } } ] }, "source": "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>", "in_reply_to_status_id": 1123997738935386100, "in_reply_to_status_id_str": "1123997738935386118", "in_reply_to_user_id": 98069620, "in_reply_to_user_id_str": "98069620", "in_reply_to_screen_name": "JockItch96", "user": { "id": 98069620, "id_str": "98069620", "name": "Ben Martin-Dye", "screen_name": "JockItch96", "location": "Bracknell, Berkshire", "description": "2.40 Mara and 1.13 Half Mara runner. Journeyman. Former GB Baseball team member. ❤😄 Family and running, everything else sucks balls.", "url": "https://t.co/UV7eQ2QX9I", "entities": { "url": { "urls": [ { "url": "https://t.co/UV7eQ2QX9I", "expanded_url": "http://www.thepowerof10.info/athletes/profile.aspx?athleteid=55022", "display_url": "thepowerof10.info/athletes/profi…", "indices": [ 0, 23 ] } ] }, "description": { "urls": [] } }, "protected": false, "followers_count": 640, "friends_count": 638, "listed_count": 25, "created_at": "Sun Dec 20 06:52:52 +0000 2009", "favourites_count": 11076, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 7541, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "C0DEED", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": true, "profile_image_url": "http://pbs.twimg.com/profile_images/1117874862947696641/9efsQXAh_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/1117874862947696641/9efsQXAh_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/98069620/1550402935", "profile_link_color": "E81C4F", "profile_sidebar_border_color": "C0DEED", "profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "333333", "profile_use_background_image": false, "has_extended_profile": true, "default_profile": false, "default_profile_image": false, "following": true, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 3, "favorite_count": 10, "favorited": false, "retweeted": true, "possibly_sensitive": false, "lang": "en" }, "is_quote_status": false, "retweet_count": 3, "favorite_count": 0, "favorited": false, "retweeted": true, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Thu May 02 18:18:41 +0000 2019", "id": 1124015369331585000, "id_str": "1124015369331585024", "text": "@BearSeymours you'll never guess who Pops met this evening... @Humph_Hugo!!!! And they said I need more beer.… https://t.co/9smHgl4PEi", "truncated": true, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "BearSeymours", "name": "The Bear-Seymours", "id": 2373358168, "id_str": "2373358168", "indices": [ 0, 13 ] }, { "screen_name": "Humph_Hugo", "name": "Humphrey & Hugo", "id": 953012374730133500, "id_str": "953012374730133504", "indices": [ 62, 73 ] } ], "urls": [ { "url": "https://t.co/9smHgl4PEi", "expanded_url": "https://twitter.com/i/web/status/1124015369331585024", "display_url": "twitter.com/i/web/status/1…", "indices": [ 111, 134 ] } ] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": 2373358168, "in_reply_to_user_id_str": "2373358168", "in_reply_to_screen_name": "BearSeymours", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 996, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5530, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 2, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" }, { "created_at": "Wed May 01 19:12:26 +0000 2019", "id": 1123666507156918300, "id_str": "1123666507156918272", "text": "@coljohnson 🙁 but with a growing family, your might find the Y better in the long run. Daddy's toys can always wait… https://t.co/x2S2Hwb45l", "truncated": true, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "coljohnson", "name": "Colin Johnson :", "id": 6499742, "id_str": "6499742", "indices": [ 0, 11 ] } ], "urls": [ { "url": "https://t.co/x2S2Hwb45l", "expanded_url": "https://twitter.com/i/web/status/1123666507156918272", "display_url": "twitter.com/i/web/status/1…", "indices": [ 117, 140 ] } ] }, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>", "in_reply_to_status_id": 1123664724065955800, "in_reply_to_status_id_str": "1123664724065955841", "in_reply_to_user_id": 6499742, "in_reply_to_user_id_str": "6499742", "in_reply_to_screen_name": "coljohnson", "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 992, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5526, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "lang": "en" }, { "created_at": "Wed May 01 09:09:51 +0000 2019", "id": 1123514862351654900, "id_str": "1123514862351654912", "text": "Did a little light shopping this morning 😁 Gotta wait until late June at the earliest though 😭 https://t.co/0QBvRlhUHp", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [], "urls": [], "media": [ { "id": 1123514861319856100, "id_str": "1123514861319856129", "indices": [ 95, 118 ], "media_url": "http://pbs.twimg.com/media/D5eG0FDXoAET_TS.jpg", "media_url_https": "https://pbs.twimg.com/media/D5eG0FDXoAET_TS.jpg", "url": "https://t.co/0QBvRlhUHp", "display_url": "pic.twitter.com/0QBvRlhUHp", "expanded_url": "https://twitter.com/lildude/status/1123514862351654912/photo/1", "type": "photo", "sizes": { "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 820, "h": 820, "resize": "fit" }, "small": { "w": 680, "h": 680, "resize": "fit" }, "large": { "w": 820, "h": 820, "resize": "fit" } } } ] }, "extended_entities": { "media": [ { "id": 1123514861319856100, "id_str": "1123514861319856129", "indices": [ 95, 118 ], "media_url": "http://pbs.twimg.com/media/D5eG0FDXoAET_TS.jpg", "media_url_https": "https://pbs.twimg.com/media/D5eG0FDXoAET_TS.jpg", "url": "https://t.co/0QBvRlhUHp", "display_url": "pic.twitter.com/0QBvRlhUHp", "expanded_url": "https://twitter.com/lildude/status/1123514862351654912/photo/1", "type": "photo", "sizes": { "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 820, "h": 820, "resize": "fit" }, "small": { "w": 680, "h": 680, "resize": "fit" }, "large": { "w": 820, "h": 820, "resize": "fit" } } } ] }, "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 8812362, "id_str": "8812362", "name": "Lildude Esquire 🤘at 🏃♂️", "screen_name": "lildude", "location": "Everywhere. Wha ha ha ha haaa!", "description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY", "url": "https://t.co/3MoMsEOqye", "entities": { "url": { "urls": [ { "url": "https://t.co/3MoMsEOqye", "expanded_url": "https://lildude.co.uk", "display_url": "lildude.co.uk", "indices": [ 0, 23 ] } ] }, "description": { "urls": [ { "url": "https://t.co/OlEtj7TstY", "expanded_url": "http://gonefora.run", "display_url": "gonefora.run", "indices": [ 90, 113 ] } ] } }, "protected": false, "followers_count": 529, "friends_count": 284, "listed_count": 18, "created_at": "Tue Sep 11 15:19:08 +0000 2007", "favourites_count": 992, "utc_offset": null, "time_zone": null, "geo_enabled": true, "verified": false, "statuses_count": 5526, "lang": "en", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "000000", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1546088343", "profile_link_color": "1B95E0", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 6, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "en" } ]
mit
cricanr/AlgorithmsHackerRank
src/main/scala/hackerRank/algorithms/BalancedBrackets.scala
1185
package hackerRank.algorithms object BalancedBrackets { def main(args: Array[String]): Unit = { val scanner = new java.util.Scanner(System.in) val noOfExpressions = scanner.nextInt() var index = 0 def isClosedBracket(left: Char, right: Char): Boolean = { val pair = (left, right) pair match { case ('(', ')') => true case ('[', ']') => true case ('{', '}') => true case _ => false } } def balancedBracket(str: String): Boolean = { if (str.isEmpty || str.length % 2 == 1 ) return false val stackChars = new scala.collection.mutable.Stack[Char] str.foreach { c => if (c == '(' || c == '[' || c == '{') stackChars.push(c) else { if (stackChars.isEmpty) return false val lastSymbol = stackChars.pop() if (!isClosedBracket(lastSymbol, c)) return false } } if (stackChars.nonEmpty) return false true } while(index < noOfExpressions){ val expression = scanner.next() if (balancedBracket(expression)) println("YES") else println("NO") index+=1 } } }
mit
sufianshari/guesthouse
application/views/dashboard/fasilitas/fasilitas_form.php
1567
<section class="content-header"> <h1><?php echo $button ?> Fasilitas</h1> </section> <section class="content"> <div class="box box-success"> <div class="box-header with-border"> <h3 class="box-title"><?php echo $button ?> Fasilitas</h3> <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> </div> </div> <div class="box-body"> <form action="<?php echo $action; ?>" enctype="multipart/form-data" class="form-horizontal" method="post"> <div class="form-group"> <label class="col-sm-2 control-label" for="varchar">Fasilitas <?php echo form_error('nm_fasilitas') ?></label> <div class="col-sm-10"> <input type="text" class="form-control" name="nm_fasilitas" id="nm_fasilitas" placeholder="Fasilitas" value="<?php echo $nm_fasilitas; ?>" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="hidden" name="id_fasilitas" value="<?php echo $id_fasilitas; ?>" /> <button type="submit" class="btn btn-primary"><?php echo $button ?></button> <a href="<?php echo site_url('dashboard/fasilitas') ?>" class="btn btn-warning">Batal</a> </div> </div> </form> </div> </div> </section>
mit
webkitz/SSBuildersCrack
code/BuildersCrack.php
6703
<?php class BuildersCrack extends DataExtension { protected static $url = "https://builderscrack.co.nz/"; //url of the review to be scrapped protected static $sandBox = false; protected static $trader = false; protected static $workmanship = 3; /** * @param $url URL of builders crack review to be scrapped */ public static function setUrl($url) { self::$url = $url; } /** * @param $min Set min amount as workmanship */ public static function setWorkmanship($min) { //@todo check is number self::$workmanship = $min; } /** * @param $trader | Trader ID */ public static function setTrader($trader) { self::$trader = $trader; } /** * @param $sandbox bool sets sandbox mode */ public static function set_sandbox($sandbox) { self::$sandBox = $sandbox; } public static function BuildersCrackItemHandler($attributes, $content = null, $parser = null) { } /** * @return DataList | JobReviews */ public function JobReviews() { return DataObject::get('JobReviews', "enabled = '1'", "date ASC"); } /** * @return HTMLText | Just render Template only */ public function JobReviewsTemplate() { $reviewsArray = $this->JobReviews(); $data = new ArrayData( array( 'Reviews' => $reviewsArray ) ); return $data->renderWith('buildersReview'); } public static function cronJob() { $html = new simple_html_dom(); //get page source load into simplehtml $source = self::downloadReview(); $html->load($source); //setup our reviews array $reviewsArray = ArrayList::create(); //loop all reviews foreach ($html->find('div[class=review-row]') as $review) { //check we have a comment element if ($review->find('div[class=comment]', 0)) { $theReview = array( 'workmanship' => '0', 'cost' => '0', 'schedule' => '0', 'professionalism' => '0', 'responsiveness' => '0', ); //lets get the reviews inside the table self::getScore($theReview,$review->find('table',0)); //date if ($review->find('p[class=text-muted]', 0)) $theReview['date'] = $review->find('p[class=text-muted]', 0)->plaintext; else { //this is silly front end designers using text warning than //try grab date if ($review->find('p[class=text-warning bold]', 0)) $theReview['date'] = $review->find('p[class=text-warning bold]', 0)->plaintext; else $theReview['date'] = 'Couldn\'t locate'; } //get the first a link its the title $reviewObj = $review->find('a', 0); //title $theReview['title'] = $reviewObj->plaintext; //get the href link to job $theReview['href'] = $reviewObj->href; //get the job_number jobs\/(\d+) if (preg_match('/jobs\/(\d+)/i', $theReview['href'], $job_number)) { $theReview['jobNumber'] = $job_number[1]; } //comment $theReview['comment'] = trim(str_replace(array("\r", "\n", "\s", "&ndash;"), '', strip_tags($review->find('div[class=comment]', 0)->plaintext))); //check review length if (strlen($theReview['comment']) > 2) $reviewsArray->push($theReview); $jbNo = $theReview['jobNumber']; if (!$newReview = JobReviews::get_one('JobReviews', "jobNumber = '$jbNo'")) { $newReview = new JobReviews(); } $newReview->jobNumber = $jbNo; $newReview->date = $theReview['date']; $newReview->link = $reviewObj->href; $newReview->comment = $theReview['comment']; $newReview->jobTitle = $theReview['title']; $newReview->workmanship = $theReview['workmanship']; $newReview->cost = $theReview['cost']; $newReview->professionalism = $theReview['professionalism']; $newReview->responsiveness = $theReview['responsiveness']; $newReview->Write(); } } die("Cron job completed"); } private static function getScore(&$theReview ,$table ){ foreach ($table->find('tr') as $rating) { //chec kthe first td as review cat $ratingCat = strtolower($rating->find('td',0)->plaintext); $ratingScore = strtolower($rating->find('td',1)->plaintext); if (isset($theReview[$ratingCat]))$theReview[$ratingCat] = $ratingScore; } } /** * @return string contain contents of review */ public static function downloadReview() { if (self::$sandBox) return file_get_contents('../sandbox.html'); //file need to be in root if (!self::$trader) return file_get_contents(self::$url); return file_get_contents("https://builderscrack.co.nz/reviews/" . self::$trader); } } class BuildersCrackPage extends Page { private static $db = array(); //set $has_many relationship private static $has_many = array( 'Reviews' => 'JobReviews' ); //updating the CMS interface public function getCMSFields() { //declare var $fields $fields = parent::getCMSFields(); //create Reviews Section GridField $fields->addFieldToTab('Root.Reviews', GridField::create( 'Reviews', 'Client Reviews', $this->Reviews(), GridFieldConfig_RecordEditor::create() )); return $fields; } } class BuildersCrackController extends Controller { static $allowed_actions = array( 'cronjob' ); public function index() { if (Permission::check('ADMIN')) BuildersCrack::cronJob(); else return "Need to be logged on as admin"; } public function cronjob() { if (!Director::is_cli() && $_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']) die("cron job needs to run locally"); BuildersCrack::cronJob(); } }
mit
dawyda/betor
application/controllers/login.php
4900
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function __construct() { parent::__construct(); $this->load->library('session'); } public function index() { $this->load->helper('form'); $this->load->view('home'); } public function auth() { $logins["username"] = trim($this->input->post('username')); $logins["password"] = trim($this->input->post('password')); $this->load->helper('form'); if(strlen($logins['username']) > 3 && strlen($logins['password']) > 3) { $this->load->model('betor_users'); $pass = $this->betor_users->login($logins); if($pass){ $this->session->logged_time = date("Y-m-d H:i:s", time()); $this->session->user_ip = $this->input->ip_address(); $this->session->logged = TRUE; $this->session->username = $logins["username"]; redirect('home/profile/'); } else{ $data['disp_msg'] = 'Wrong logins! Try again or '.anchor('login/pswdreset','&nbsp;Reset Password?','style="text-decoration:none; color:#42f4ff;"'); $this->load->view('home',$data); } } else{ $data['disp_msg'] = "user/password too short!"; $this->load->view('home',$data); } } //resetting user password public function pswdreset() { if($this->input->post('action') == "create") { $phone = $this->input->post('phone'); $this->load->model('betor_users'); $info = $this->betor_users->get_user_from_num($phone); if($info !== NULL) { //create code save in session send in sms $code = $this->_genCode(); $sms = "Dear user, Use the following code to reset your password: ".$code; $this->session->reset_code = $code; $this->session->userid = $info["id"]; $this->load->model('betor_sms'); $this->betor_sms->add_sms(array("phone"=>$info["phone"], "sms"=>$sms)); $this->output->set_header("Content-Type: application/json"); echo '{"success":"1"}'; } else { $this->output->set_header("Content-Type: application/json"); echo '{"success":"0", "msg":"Phone not found in catalog!"}'; } } else if($this->input->post('action') == "validate") { if($this->input->post('code') == NULL || $this->session->reset_code == NULL) { echo "Missing form vars & session!"; exit(0); } $code = $this->input->post('code'); if($code == $this->session->reset_code) { $this->session->code_entered = TRUE; unset($this->session->reset_code); $this->output->set_header("Content-Type: application/json"); echo '{"success":"1"}'; } else { $this->session->code_entered = FALSE; $this->output->set_header("Content-Type: application/json"); echo '{"success":"0", "msg":"Invalid code entered!"}'; } } else if($this->input->post('action') == "update") { //security first if($this->session->userid == NULL || $this->session->code_entered == NULL || $this->session->code_entered == FALSE) { $this->output->set_header("Content-Type: application/json"); echo '{"success":"-1", "msg":"Password reset session not found!"}'; exit(0); } unset($this->session->code_entered); //update pwd $passwd = $this->input->post('password'); $passwd2 = $this->input->post('password2'); if($passwd == $passwd2 && $passwd !== "") { $this->load->model("betor_users"); $changed = $this->betor_users->update_user_pwd($this->session->userid, $passwd); if($changed){ unset($this->session->userid); $this->output->set_header("Content-Type: application/json"); echo '{"success":"1", "msg":"OK"}'; } else { unset($this->session->userid); $this->output->set_header("Content-Type: application/json"); echo '{"success":"0", "msg":"Password update failed!"}'; } } else { $this->output->set_header("Content-Type: application/json"); echo '{"success":"0", "msg":"Passwords do not match!"}'; } } else { //display pwd reset page. $this->load->view('pswdreset'); } } // password reset ends here. private function _genCode(){ $str = "1 2 3 4 6 7 8 9 a b c d e f g h k m n P t"; $temp = explode(" ", $str); $c1 = $temp[rand(1, 20)]; $c2 = $temp[rand(1, 11)]; $c3 = $temp[rand(1, 13)]; $c4 = $temp[rand(1, 20)]; $c5 = $temp[rand(1, 18)]; $c6 = $temp[rand(1, 20)]; $chars = $c1.$c2.$c3.$c4.$c5.$c6; return strtolower($chars); } }
mit
Adyen/magento
app/code/community/Adyen/Payment/sql/adyen_setup/mysql4-upgrade-2.3.0-2.3.0.1.php
1106
<?php /** * Adyen Payment Module * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * @category Adyen * @package Adyen_Payment * @copyright Copyright (c) 2011 Adyen (http://www.adyen.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * @category Payment Gateway * @package Adyen_Payment * @author Adyen * @property Adyen B.V * @copyright Copyright (c) 2014 Adyen BV (http://www.adyen.com) */ /* @var $installer Adyen_Payment_Model_Mysql4_Setup */ $installer = $this; $installer->startSetup(); $installer->addAttribute('order_payment', 'adyen_authorisation_amount', array()); $installer->endSetup();
mit
luiscleto/feup-lpoo-android-tower-defense
AndroidTowerDefenseTests/src/pt/up/fe/lpoo/towerdefense/test/TestProjectile.java
947
package pt.up.fe.lpoo.towerdefense.test; import pt.up.fe.lpoo.framework.Image; import pt.up.fe.lpoo.towerdefense.Projectile; import pt.up.fe.lpoo.towerdefense.Enemy; public class TestProjectile extends Projectile { public TestProjectile(int iniX, int iniY, int goalX, int goalY, int movementSpeed, int projectileDamage) { super(iniX, iniY, goalX, goalY, movementSpeed, projectileDamage); damageType = Enemy.DamageType.Piercing; } @Override public Image getCurrentImage() { return null; } public int getYSpeed(){ return ySpeed; } public int getXSpeed(){ return xSpeed; } @Override protected boolean collidedWith(Enemy curEnemy) { int enemyIniX = curEnemy.getX(); int enemyIniY = curEnemy.getY(); int enemyFinalX = enemyIniX+50; int enemyFinalY = enemyIniY+50; if(centerX >= enemyIniX && centerX <= enemyFinalX && centerY >= enemyIniY && centerY <= enemyFinalY) return true; else return false; } }
mit
matthewcaperon/contactless-tls
card-drivers/softcard/src/com/microexpert/cltls/smartcards/softcard/PKCS1Encoding.java
11812
package com.microexpert.cltls.smartcards.softcard; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.SecureRandom; import org.spongycastle.crypto.AsymmetricBlockCipher; import org.spongycastle.crypto.CipherParameters; import org.spongycastle.crypto.InvalidCipherTextException; import org.spongycastle.crypto.params.AsymmetricKeyParameter; import org.spongycastle.crypto.params.ParametersWithRandom; import org.spongycastle.util.encoders.Hex; /** * this does your basic PKCS 1 v1.5 padding - whether or not you should be using this * depends on your application - see PKCS1 Version 2 for details. */ public class PKCS1Encoding implements AsymmetricBlockCipher { /** * some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to * work with one of these set the system property org.bouncycastle.pkcs1.strict to false. * <p> * The system property is checked during construction of the encoding object, it is set to * true by default. * </p> */ public static final String STRICT_LENGTH_ENABLED_PROPERTY = "org.bouncycastle.pkcs1.strict"; private static final int HEADER_LENGTH = 10; private SecureRandom random; private AsymmetricBlockCipher engine; private boolean forEncryption; private boolean forPrivateKey; private boolean useStrictLength; private int pLen = -1; private byte[] fallback = null; /** * Basic constructor. * @param cipher */ public PKCS1Encoding( AsymmetricBlockCipher cipher) { this.engine = cipher; this.useStrictLength = useStrict(); } /** * Constructor for decryption with a fixed plaintext length. * * @param cipher The cipher to use for cryptographic operation. * @param pLen Length of the expected plaintext. */ public PKCS1Encoding( AsymmetricBlockCipher cipher, int pLen) { this.engine = cipher; this.useStrictLength = useStrict(); this.pLen = pLen; } /** * Constructor for decryption with a fixed plaintext length and a fallback * value that is returned, if the padding is incorrect. * * @param cipher * The cipher to use for cryptographic operation. * @param fallback * The fallback value, we don't do an arraycopy here. */ public PKCS1Encoding( AsymmetricBlockCipher cipher, byte[] fallback) { this.engine = cipher; this.useStrictLength = useStrict(); this.fallback = fallback; this.pLen = fallback.length; } // // for J2ME compatibility // private boolean useStrict() { // required if security manager has been installed. String strict = (String)AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty(STRICT_LENGTH_ENABLED_PROPERTY); } }); return strict == null || strict.equals("true"); } public AsymmetricBlockCipher getUnderlyingCipher() { return engine; } public void init( boolean forEncryption, CipherParameters param) { AsymmetricKeyParameter kParam; if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; this.random = rParam.getRandom(); kParam = (AsymmetricKeyParameter)rParam.getParameters(); } else { this.random = new SecureRandom(); kParam = (AsymmetricKeyParameter)param; } engine.init(forEncryption, param); this.forPrivateKey = kParam.isPrivate(); this.forEncryption = forEncryption; } public int getInputBlockSize() { int baseBlockSize = engine.getInputBlockSize(); if (forEncryption) { return baseBlockSize - HEADER_LENGTH; } else { return baseBlockSize; } } public int getOutputBlockSize() { int baseBlockSize = engine.getOutputBlockSize(); if (forEncryption) { return baseBlockSize; } else { return baseBlockSize - HEADER_LENGTH; } } public byte[] processBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { System.out.println("In Block (Before Padding):" + Hex.toHexString(in)); System.out.println("In Block (Before Padding) Length:" + Integer.toString(in.length)); if (forEncryption) { return encodeBlock(in, inOff, inLen); } else { return decodeBlock(in, inOff, inLen); } } private byte[] encodeBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { if (inLen > getInputBlockSize()) { throw new IllegalArgumentException("input data too large"); } byte[] block = new byte[engine.getInputBlockSize()]; if (forPrivateKey) { block[0] = 0x01; // type code 1 for (int i = 1; i != block.length - inLen - 1; i++) { block[i] = (byte)0xFF; } } else { random.nextBytes(block); // random fill block[0] = 0x02; // type code 2 // // a zero byte marks the end of the padding, so all // the pad bytes must be non-zero. // for (int i = 1; i != block.length - inLen - 1; i++) { while (block[i] == 0) { block[i] = (byte)random.nextInt(); } } } block[block.length - inLen - 1] = 0x00; // mark the end of the padding System.arraycopy(in, inOff, block, block.length - inLen, inLen); return engine.processBlock(block, 0, block.length); } /** * Checks if the argument is a correctly PKCS#1.5 encoded Plaintext * for encryption. * * @param encoded The Plaintext. * @param pLen Expected length of the plaintext. * @return Either 0, if the encoding is correct, or -1, if it is incorrect. */ private static int checkPkcs1Encoding(byte[] encoded, int pLen) { int correct = 0; /* * Check if the first two bytes are 0 2 */ correct |= (encoded[0] ^ 2); /* * Now the padding check, check for no 0 byte in the padding */ int plen = encoded.length - ( pLen /* Lenght of the PMS */ + 1 /* Final 0-byte before PMS */ ); for (int i = 1; i < plen; i++) { int tmp = encoded[i]; tmp |= tmp >> 1; tmp |= tmp >> 2; tmp |= tmp >> 4; correct |= (tmp & 1) - 1; } /* * Make sure the padding ends with a 0 byte. */ correct |= encoded[encoded.length - (pLen +1)]; /* * Return 0 or 1, depending on the result. */ correct |= correct >> 1; correct |= correct >> 2; correct |= correct >> 4; return ~((correct & 1) - 1); } /** * Decode PKCS#1.5 encoding, and return a random value if the padding is not correct. * * @param in The encrypted block. * @param inOff Offset in the encrypted block. * @param inLen Length of the encrypted block. * //@param pLen Length of the desired output. * @return The plaintext without padding, or a random value if the padding was incorrect. * * @throws InvalidCipherTextException */ private byte[] decodeBlockOrRandom(byte[] in, int inOff, int inLen) throws InvalidCipherTextException { if (!forPrivateKey) { throw new InvalidCipherTextException("sorry, this method is only for decryption, not for signing"); } byte[] block = engine.processBlock(in, inOff, inLen); byte[] random = null; if (this.fallback == null) { random = new byte[this.pLen]; this.random.nextBytes(random); } else { random = fallback; } /* * TODO: This is a potential dangerous side channel. However, you can * fix this by changing the RSA engine in a way, that it will always * return blocks of the same length and prepend them with 0 bytes if * needed. */ if (block.length < getOutputBlockSize()) { throw new InvalidCipherTextException("block truncated"); } /* * TODO: Potential side channel. Fix it by making the engine always * return blocks of the correct length. */ if (useStrictLength && block.length != engine.getOutputBlockSize()) { throw new InvalidCipherTextException("block incorrect size"); } /* * Check the padding. */ int correct = PKCS1Encoding.checkPkcs1Encoding(block, this.pLen); /* * Now, to a constant time constant memory copy of the decrypted value * or the random value, depending on the validity of the padding. */ byte[] result = new byte[this.pLen]; for (int i = 0; i < this.pLen; i++) { result[i] = (byte)((block[i + (block.length - pLen)] & (~correct)) | (random[i] & correct)); } return result; } /** * @exception InvalidCipherTextException if the decrypted block is not in PKCS1 format. */ private byte[] decodeBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { /* * If the length of the expected plaintext is known, we use a constant-time decryption. * If the decryption fails, we return a random value. */ if (this.pLen != -1) { return this.decodeBlockOrRandom(in, inOff, inLen); } byte[] block = engine.processBlock(in, inOff, inLen); if (block.length < getOutputBlockSize()) { throw new InvalidCipherTextException("block truncated"); } byte type = block[0]; if (forPrivateKey) { if (type != 2) { throw new InvalidCipherTextException("unknown block type"); } } else { if (type != 1) { throw new InvalidCipherTextException("unknown block type"); } } if (useStrictLength && block.length != engine.getOutputBlockSize()) { throw new InvalidCipherTextException("block incorrect size"); } // // find and extract the message block. // int start; for (start = 1; start != block.length; start++) { byte pad = block[start]; if (pad == 0) { break; } if (type == 1 && pad != (byte)0xff) { throw new InvalidCipherTextException("block padding incorrect"); } } start++; // data should start at the next byte if (start > block.length || start < HEADER_LENGTH) { throw new InvalidCipherTextException("no data in block"); } byte[] result = new byte[block.length - start]; System.arraycopy(block, start, result, 0, result.length); return result; } }
mit
Glassay/js-training
egg-study/app.js
2645
/** * 2017-9-27 JifengCheng * 数据库建表 */ 'use strict'; const knex = require('knex')({ client: 'mysql', }); module.exports = app => { app.beforeStart(function* () { // const ctx = app.createAnonymousContext(); const ctx = app.createAnonymousContext(); const hasParticipant = yield app.mysql.query(knex.schema.hasTable('user').toString()); if (hasParticipant.length === 0) { const participantSchema = knex.schema.createTableIfNotExists('user', function(table) { table.increments(); table.string('wechat').notNullable().defaultTo(''); table.string('mobile').notNullable().defaultTo(''); table.string('in').notNullable().defaultTo(''); table.integer('vcount').notNullable().defaultTo(0); // table.string('violation').notNullable().defaultTo(''); table.timestamp('create_at').defaultTo(knex.fn.now()); table.charset('utf8'); }); yield app.mysql.query(participantSchema.toString()); yield ctx.helper.unique(app, 'user', 'wechat'); } const hasWorks = yield app.mysql.query(knex.schema.hasTable('works').toString()); if (hasWorks.length === 0) { const worksSchema = knex.schema.createTableIfNotExists('works', function(table) { table.increments(); // table.string('参赛者').notNullable().defaultTo(''); table.string('wechat').notNullable().defaultTo(''); table.string('works1').notNullable().defaultTo(''); table.string('works2').notNullable().defaultTo(''); table.string('works3').notNullable().defaultTo(''); table.string('violation').notNullable().defaultTo(''); table.timestamp('create_at').defaultTo(knex.fn.now()); table.charset('utf8'); }); yield app.mysql.query(worksSchema.toString()); yield ctx.helper.unique(app, 'works', 'wechat'); } const hasVote = yield app.mysql.query(knex.schema.hasTable('votelist').toString()); if (hasVote.length === 0) { const voteSchema = knex.schema.createTableIfNotExists('votelist', function(table) { table.increments(); table.string('wechat').notNullable().defaultTo(''); table.string('vote1').notNullable().defaultTo(''); table.string('vate2').notNullable().defaultTo(''); table.string('vote3').notNullable().defaultTo(''); // table.string('作品3').notNullable().defaultTo(''); table.timestamp('create_at').defaultTo(knex.fn.now()); table.charset('utf8'); }); yield app.mysql.query(voteSchema.toString()); yield ctx.helper.unique(app, 'user', 'wechat'); } }); };
mit
axelpale/tresdb
client/stores/mapstate.js
713
// This Store takes care of reading and storing a map viewport state // to a given storage, e.g. localStorage. // // The structure of the state: // { // lat: <number>, // lng: <number>, // zoom: <integer>, // mapTypeId: <string>, // } // // API // Constructor // createStore(storage, storageKey, defaultState) // Methods // update(stateDelta, opts) // reset() // isDefault() // isEmpty() // get() // Emits // 'updated' with state // var createStore = require('./lib/createStore'); var storage = require('../connection/storage'); var DEFAULT_STATE = tresdb.config.defaultMapState; module.exports = createStore(storage, 'tresdb-geo-location', DEFAULT_STATE);
mit
schme16/LD39-Running-out-of-Power
Assets/data/Easings.cs
13084
using System; #if UNITY using UnityEngine; using Math = UnityEngine.Mathf; #endif static public class Easings { /// <summary> /// Constant Pi. /// </summary> private const float PI = (float)Math.PI; /// <summary> /// Constant Pi / 2. /// </summary> private const float HALFPI = (float)Math.PI / 2.0f; /// <summary> /// Easing Functions enumeration /// </summary> public enum Functions { Linear, QuadraticEaseIn, QuadraticEaseOut, QuadraticEaseInOut, CubicEaseIn, CubicEaseOut, CubicEaseInOut, QuarticEaseIn, QuarticEaseOut, QuarticEaseInOut, QuinticEaseIn, QuinticEaseOut, QuinticEaseInOut, SineEaseIn, SineEaseOut, SineEaseInOut, CircularEaseIn, CircularEaseOut, CircularEaseInOut, ExponentialEaseIn, ExponentialEaseOut, ExponentialEaseInOut, ElasticEaseIn, ElasticEaseOut, ElasticEaseInOut, BackEaseIn, BackEaseOut, BackEaseInOut, BounceEaseIn, BounceEaseOut, BounceEaseInOut } /// <summary> /// Interpolate using the specified function. /// </summary> static public float Interpolate(float p, Functions function) { switch(function) { default: case Functions.Linear: return Linear(p); case Functions.QuadraticEaseOut: return QuadraticEaseOut(p); case Functions.QuadraticEaseIn: return QuadraticEaseIn(p); case Functions.QuadraticEaseInOut: return QuadraticEaseInOut(p); case Functions.CubicEaseIn: return CubicEaseIn(p); case Functions.CubicEaseOut: return CubicEaseOut(p); case Functions.CubicEaseInOut: return CubicEaseInOut(p); case Functions.QuarticEaseIn: return QuarticEaseIn(p); case Functions.QuarticEaseOut: return QuarticEaseOut(p); case Functions.QuarticEaseInOut: return QuarticEaseInOut(p); case Functions.QuinticEaseIn: return QuinticEaseIn(p); case Functions.QuinticEaseOut: return QuinticEaseOut(p); case Functions.QuinticEaseInOut: return QuinticEaseInOut(p); case Functions.SineEaseIn: return SineEaseIn(p); case Functions.SineEaseOut: return SineEaseOut(p); case Functions.SineEaseInOut: return SineEaseInOut(p); case Functions.CircularEaseIn: return CircularEaseIn(p); case Functions.CircularEaseOut: return CircularEaseOut(p); case Functions.CircularEaseInOut: return CircularEaseInOut(p); case Functions.ExponentialEaseIn: return ExponentialEaseIn(p); case Functions.ExponentialEaseOut: return ExponentialEaseOut(p); case Functions.ExponentialEaseInOut: return ExponentialEaseInOut(p); case Functions.ElasticEaseIn: return ElasticEaseIn(p); case Functions.ElasticEaseOut: return ElasticEaseOut(p); case Functions.ElasticEaseInOut: return ElasticEaseInOut(p); case Functions.BackEaseIn: return BackEaseIn(p); case Functions.BackEaseOut: return BackEaseOut(p); case Functions.BackEaseInOut: return BackEaseInOut(p); case Functions.BounceEaseIn: return BounceEaseIn(p); case Functions.BounceEaseOut: return BounceEaseOut(p); case Functions.BounceEaseInOut: return BounceEaseInOut(p); } } /// <summary> /// Modeled after the line y = x /// </summary> static public float Linear(float p) { return p; } /// <summary> /// Modeled after the parabola y = x^2 /// </summary> static public float QuadraticEaseIn(float p) { return p * p; } /// <summary> /// Modeled after the parabola y = -x^2 + 2x /// </summary> static public float QuadraticEaseOut(float p) { return -(p * (p - 2)); } /// <summary> /// Modeled after the piecewise quadratic /// y = (1/2)((2x)^2) ; [0, 0.5) /// y = -(1/2)((2x-1)*(2x-3) - 1) ; [0.5, 1] /// </summary> static public float QuadraticEaseInOut(float p) { if(p < 0.5f) { return 2 * p * p; } else { return (-2 * p * p) + (4 * p) - 1; } } /// <summary> /// Modeled after the cubic y = x^3 /// </summary> static public float CubicEaseIn(float p) { return p * p * p; } /// <summary> /// Modeled after the cubic y = (x - 1)^3 + 1 /// </summary> static public float CubicEaseOut(float p) { float f = (p - 1); return f * f * f + 1; } /// <summary> /// Modeled after the piecewise cubic /// y = (1/2)((2x)^3) ; [0, 0.5) /// y = (1/2)((2x-2)^3 + 2) ; [0.5, 1] /// </summary> static public float CubicEaseInOut(float p) { if(p < 0.5f) { return 4 * p * p * p; } else { float f = ((2 * p) - 2); return 0.5f * f * f * f + 1; } } /// <summary> /// Modeled after the quartic x^4 /// </summary> static public float QuarticEaseIn(float p) { return p * p * p * p; } /// <summary> /// Modeled after the quartic y = 1 - (x - 1)^4 /// </summary> static public float QuarticEaseOut(float p) { float f = (p - 1); return f * f * f * (1 - p) + 1; } /// <summary> // Modeled after the piecewise quartic // y = (1/2)((2x)^4) ; [0, 0.5) // y = -(1/2)((2x-2)^4 - 2) ; [0.5, 1] /// </summary> static public float QuarticEaseInOut(float p) { if(p < 0.5f) { return 8 * p * p * p * p; } else { float f = (p - 1); return -8 * f * f * f * f + 1; } } /// <summary> /// Modeled after the quintic y = x^5 /// </summary> static public float QuinticEaseIn(float p) { return p * p * p * p * p; } /// <summary> /// Modeled after the quintic y = (x - 1)^5 + 1 /// </summary> static public float QuinticEaseOut(float p) { float f = (p - 1); return f * f * f * f * f + 1; } /// <summary> /// Modeled after the piecewise quintic /// y = (1/2)((2x)^5) ; [0, 0.5) /// y = (1/2)((2x-2)^5 + 2) ; [0.5, 1] /// </summary> static public float QuinticEaseInOut(float p) { if(p < 0.5f) { return 16 * p * p * p * p * p; } else { float f = ((2 * p) - 2); return 0.5f * f * f * f * f * f + 1f; } } /// <summary> /// Modeled after quarter-cycle of sine wave /// </summary> static public float SineEaseIn(float p) { return (float)(float)Math.Sin( ( (float)p - 1f) * (float)HALFPI ) + 1f; } /// <summary> /// Modeled after quarter-cycle of sine wave (different phase) /// </summary> static public float SineEaseOut(float p) { return (float)Math.Sin(p * (float)HALFPI); } /// <summary> /// Modeled after half sine wave /// </summary> static public float SineEaseInOut(float p) { return 0.5f * (1f - (float)Math.Cos(p * PI)); } /// <summary> /// Modeled after shifted quadrant IV of unit circle /// </summary> static public float CircularEaseIn(float p) { return 1f - (float)Math.Sqrt(1f - (p * p)); } /// <summary> /// Modeled after shifted quadrant II of unit circle /// </summary> static public float CircularEaseOut(float p) { return (float)Math.Sqrt((2f - p) * p); } /// <summary> /// Modeled after the piecewise circular function /// y = (1/2)(1 - (float)Math.Sqrt(1 - 4x^2)) ; [0, 0.5) /// y = (1/2)((float)Math.Sqrt(-(2x - 3)*(2x - 1)) + 1) ; [0.5, 1] /// </summary> static public float CircularEaseInOut(float p) { if(p < 0.5f) { return 0.5f * (1f - (float)Math.Sqrt(1f - 4f * (p * p))); } else { return 0.5f * ((float)Math.Sqrt(-((2f * p) - 3f) * ((2f * p) - 1f)) + 1f); } } /// <summary> /// Modeled after the exponential function y = 2^(10(x - 1)) /// </summary> static public float ExponentialEaseIn(float p) { return (p == 0.0f) ? p :(float)Math.Pow(2f, 10f * (p - 1f)); } /// <summary> /// Modeled after the exponential function y = -2^(-10x) + 1 /// </summary> static public float ExponentialEaseOut(float p) { return (p == 1.0f) ? p : 1 -(float)Math.Pow(2f, -10f * p); } /// <summary> /// Modeled after the piecewise exponential /// y = (1/2)2^(10(2x - 1)) ; [0,0.5) /// y = -(1/2)*2^(-10(2x - 1))) + 1 ; [0.5,1] /// </summary> static public float ExponentialEaseInOut(float p) { if(p == 0.0 || p == 1.0) return p; if(p < 0.5f) { return 0.5f *(float)Math.Pow(2, (20 * p) - 10); } else { return -0.5f *(float)Math.Pow(2, (-20 * p) + 10) + 1; } } /// <summary> /// Modeled after the damped sine wave y = sin(13pi/2*x)*Math.Pow(2, 10 * (x - 1)) /// </summary> static public float ElasticEaseIn(float p) { return (float)Math.Sin(13 * (float)HALFPI * p) *(float)Math.Pow(2, 10 * (p - 1)); } /// <summary> /// Modeled after the damped sine wave y = sin(-13pi/2*(x + 1))*Math.Pow(2, -10x) + 1 /// </summary> static public float ElasticEaseOut(float p) { return (float)Math.Sin(-13 * (float)HALFPI * (p + 1)) *(float)Math.Pow(2, -10 * p) + 1; } /// <summary> /// Modeled after the piecewise exponentially-damped sine wave: /// y = (1/2)*sin(13pi/2*(2*x))*Math.Pow(2, 10 * ((2*x) - 1)) ; [0,0.5) /// y = (1/2)*(sin(-13pi/2*((2x-1)+1))*Math.Pow(2,-10(2*x-1)) + 2) ; [0.5, 1] /// </summary> static public float ElasticEaseInOut(float p) { if(p < 0.5f) { return 0.5f * (float)Math.Sin(13 * (float)HALFPI * (2 * p)) *(float)Math.Pow(2, 10 * ((2 * p) - 1)); } else { return 0.5f * ((float)Math.Sin(-13 * (float)HALFPI * ((2 * p - 1) + 1)) *(float)Math.Pow(2, -10 * (2 * p - 1)) + 2); } } /// <summary> /// Modeled after the overshooting cubic y = x^3-x*sin(x*pi) /// </summary> static public float BackEaseIn(float p) { return p * p * p - p * (float)Math.Sin(p * PI); } /// <summary> /// Modeled after overshooting cubic y = 1-((1-x)^3-(1-x)*sin((1-x)*pi)) /// </summary> static public float BackEaseOut(float p) { float f = (1 - p); return 1 - (f * f * f - f * (float)Math.Sin(f * PI)); } /// <summary> /// Modeled after the piecewise overshooting cubic function: /// y = (1/2)*((2x)^3-(2x)*sin(2*x*pi)) ; [0, 0.5) /// y = (1/2)*(1-((1-x)^3-(1-x)*sin((1-x)*pi))+1) ; [0.5, 1] /// </summary> static public float BackEaseInOut(float p) { if(p < 0.5f) { float f = 2 * p; return 0.5f * (f * f * f - f * (float)Math.Sin(f * PI)); } else { float f = (1 - (2*p - 1)); return 0.5f * (1 - (f * f * f - f * (float)Math.Sin(f * PI))) + 0.5f; } } /// <summary> /// </summary> static public float BounceEaseIn(float p) { return 1 - BounceEaseOut(1 - p); } /// <summary> /// </summary> static public float BounceEaseOut(float p) { if(p < 4/11.0f) { return (121 * p * p)/16.0f; } else if(p < 8/11.0f) { return (363/40.0f * p * p) - (99/10.0f * p) + 17/5.0f; } else if(p < 9/10.0f) { return (4356/361.0f * p * p) - (35442/1805.0f * p) + 16061/1805.0f; } else { return (54/5.0f * p * p) - (513/25.0f * p) + 268/25.0f; } } /// <summary> /// </summary> static public float BounceEaseInOut(float p) { if(p < 0.5f) { return 0.5f * BounceEaseIn(p*2); } else { return 0.5f * BounceEaseOut(p * 2 - 1) + 0.5f; } } }
mit
freezing/angular2-tutorial
dev/attribute-directives/structural-directives.component.ts
263
import {Component} from "@angular/core"; import {HighlightDirective} from "./highlight.directive"; @Component({ selector: 'my-structural-directives', template: ` `, directives: [HighlightDirective] }) export class MyStructuralDirectivesComponent { }
mit
kubatyszko/gitea
routers/api/v1/api.go
27744
// Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2016 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. // Package v1 Gitea API. // // This documentation describes the Gitea API. // // Schemes: http, https // BasePath: /api/v1 // Version: 1.1.1 // License: MIT http://opensource.org/licenses/MIT // // Consumes: // - application/json // - text/plain // // Produces: // - application/json // - text/html // // Security: // - BasicAuth : // - Token : // - AccessToken : // - AuthorizationHeaderToken : // - SudoParam : // - SudoHeader : // // SecurityDefinitions: // BasicAuth: // type: basic // Token: // type: apiKey // name: token // in: query // AccessToken: // type: apiKey // name: access_token // in: query // AuthorizationHeaderToken: // type: apiKey // name: Authorization // in: header // description: API tokens must be prepended with "token" followed by a space. // SudoParam: // type: apiKey // name: sudo // in: query // description: Sudo API request as the user provided as the key. Admin privileges are required. // SudoHeader: // type: apiKey // name: Sudo // in: header // description: Sudo API request as the user provided as the key. Admin privileges are required. // // swagger:meta package v1 import ( "strings" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/routers/api/v1/admin" "code.gitea.io/gitea/routers/api/v1/misc" "code.gitea.io/gitea/routers/api/v1/org" "code.gitea.io/gitea/routers/api/v1/repo" _ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation "code.gitea.io/gitea/routers/api/v1/user" "gitea.com/macaron/binding" "gitea.com/macaron/macaron" ) func sudo() macaron.Handler { return func(ctx *context.APIContext) { sudo := ctx.Query("sudo") if len(sudo) == 0 { sudo = ctx.Req.Header.Get("Sudo") } if len(sudo) > 0 { if ctx.IsSigned && ctx.User.IsAdmin { user, err := models.GetUserByName(sudo) if err != nil { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { ctx.Error(500, "GetUserByName", err) } return } log.Trace("Sudo from (%s) to: %s", ctx.User.Name, user.Name) ctx.User = user } else { ctx.JSON(403, map[string]string{ "message": "Only administrators allowed to sudo.", }) return } } } } func repoAssignment() macaron.Handler { return func(ctx *context.APIContext) { userName := ctx.Params(":username") repoName := ctx.Params(":reponame") var ( owner *models.User err error ) // Check if the user is the same as the repository owner. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { owner = ctx.User } else { owner, err = models.GetUserByName(userName) if err != nil { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { ctx.Error(500, "GetUserByName", err) } return } } ctx.Repo.Owner = owner // Get repository. repo, err := models.GetRepositoryByName(owner.ID, repoName) if err != nil { if models.IsErrRepoNotExist(err) { redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName) if err == nil { context.RedirectToRepo(ctx.Context, redirectRepoID) } else if models.IsErrRepoRedirectNotExist(err) { ctx.NotFound() } else { ctx.Error(500, "LookupRepoRedirect", err) } } else { ctx.Error(500, "GetRepositoryByName", err) } return } repo.Owner = owner ctx.Repo.Repository = repo ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User) if err != nil { ctx.Error(500, "GetUserRepoPermission", err) return } if !ctx.Repo.HasAccess() { ctx.NotFound() return } } } // Contexter middleware already checks token for user sign in process. func reqToken() macaron.Handler { return func(ctx *context.APIContext) { if true == ctx.Data["IsApiToken"] { return } if ctx.Context.IsBasicAuth { ctx.CheckForOTP() return } if ctx.IsSigned { ctx.RequireCSRF() return } ctx.Context.Error(401) } } func reqBasicAuth() macaron.Handler { return func(ctx *context.APIContext) { if !ctx.Context.IsBasicAuth { ctx.Context.Error(401) return } ctx.CheckForOTP() } } // reqSiteAdmin user should be the site admin func reqSiteAdmin() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserSiteAdmin() { ctx.Error(403) return } } } // reqOwner user should be the owner of the repo or site admin. func reqOwner() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoOwner() && !ctx.IsUserSiteAdmin() { ctx.Error(403) return } } } // reqAdmin user should be an owner or a collaborator with admin write of a repository, or site admin func reqAdmin() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() { ctx.Error(403) return } } } // reqRepoWriter user should have a permission to write to a repo, or be a site admin func reqRepoWriter(unitTypes ...models.UnitType) macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoWriter(unitTypes) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() { ctx.Error(403) return } } } // reqRepoReader user should have specific read permission or be a repo admin or a site admin func reqRepoReader(unitType models.UnitType) macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoReaderSpecific(unitType) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() { ctx.Error(403) return } } } // reqAnyRepoReader user should have any permission to read repository or permissions of site admin func reqAnyRepoReader() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoReaderAny() && !ctx.IsUserSiteAdmin() { ctx.Error(403) return } } } // reqOrgOwnership user should be an organization owner, or a site admin func reqOrgOwnership() macaron.Handler { return func(ctx *context.APIContext) { if ctx.Context.IsUserSiteAdmin() { return } var orgID int64 if ctx.Org.Organization != nil { orgID = ctx.Org.Organization.ID } else if ctx.Org.Team != nil { orgID = ctx.Org.Team.OrgID } else { ctx.Error(500, "", "reqOrgOwnership: unprepared context") return } isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID) if err != nil { ctx.Error(500, "IsOrganizationOwner", err) return } else if !isOwner { if ctx.Org.Organization != nil { ctx.Error(403, "", "Must be an organization owner") } else { ctx.NotFound() } return } } } // reqTeamMembership user should be an team member, or a site admin func reqTeamMembership() macaron.Handler { return func(ctx *context.APIContext) { if ctx.Context.IsUserSiteAdmin() { return } if ctx.Org.Team == nil { ctx.Error(500, "", "reqTeamMembership: unprepared context") return } var orgID = ctx.Org.Team.OrgID isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID) if err != nil { ctx.Error(500, "IsOrganizationOwner", err) return } else if isOwner { return } if isTeamMember, err := models.IsTeamMember(orgID, ctx.Org.Team.ID, ctx.User.ID); err != nil { ctx.Error(500, "IsTeamMember", err) return } else if !isTeamMember { isOrgMember, err := models.IsOrganizationMember(orgID, ctx.User.ID) if err != nil { ctx.Error(500, "IsOrganizationMember", err) } else if isOrgMember { ctx.Error(403, "", "Must be a team member") } else { ctx.NotFound() } return } } } // reqOrgMembership user should be an organization member, or a site admin func reqOrgMembership() macaron.Handler { return func(ctx *context.APIContext) { if ctx.Context.IsUserSiteAdmin() { return } var orgID int64 if ctx.Org.Organization != nil { orgID = ctx.Org.Organization.ID } else if ctx.Org.Team != nil { orgID = ctx.Org.Team.OrgID } else { ctx.Error(500, "", "reqOrgMembership: unprepared context") return } if isMember, err := models.IsOrganizationMember(orgID, ctx.User.ID); err != nil { ctx.Error(500, "IsOrganizationMember", err) return } else if !isMember { if ctx.Org.Organization != nil { ctx.Error(403, "", "Must be an organization member") } else { ctx.NotFound() } return } } } func reqGitHook() macaron.Handler { return func(ctx *context.APIContext) { if !ctx.User.CanEditGitHook() { ctx.Error(403, "", "must be allowed to edit Git hooks") return } } } func orgAssignment(args ...bool) macaron.Handler { var ( assignOrg bool assignTeam bool ) if len(args) > 0 { assignOrg = args[0] } if len(args) > 1 { assignTeam = args[1] } return func(ctx *context.APIContext) { ctx.Org = new(context.APIOrganization) var err error if assignOrg { ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":orgname")) if err != nil { if models.IsErrOrgNotExist(err) { ctx.NotFound() } else { ctx.Error(500, "GetOrgByName", err) } return } } if assignTeam { ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid")) if err != nil { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { ctx.Error(500, "GetTeamById", err) } return } } } } func mustEnableIssues(ctx *context.APIContext) { if !ctx.Repo.CanRead(models.UnitTypeIssues) { if log.IsTrace() { if ctx.IsSigned { log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+ "User in Repo has Permissions: %-+v", ctx.User, models.UnitTypeIssues, ctx.Repo.Repository, ctx.Repo.Permission) } else { log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+ "Anonymous user in Repo has Permissions: %-+v", models.UnitTypeIssues, ctx.Repo.Repository, ctx.Repo.Permission) } } ctx.NotFound() return } } func mustAllowPulls(ctx *context.APIContext) { if !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(models.UnitTypePullRequests)) { if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() { if ctx.IsSigned { log.Trace("Permission Denied: User %-v cannot read %-v in Repo %-v\n"+ "User in Repo has Permissions: %-+v", ctx.User, models.UnitTypePullRequests, ctx.Repo.Repository, ctx.Repo.Permission) } else { log.Trace("Permission Denied: Anonymous user cannot read %-v in Repo %-v\n"+ "Anonymous user in Repo has Permissions: %-+v", models.UnitTypePullRequests, ctx.Repo.Repository, ctx.Repo.Permission) } } ctx.NotFound() return } } func mustEnableIssuesOrPulls(ctx *context.APIContext) { if !ctx.Repo.CanRead(models.UnitTypeIssues) && !(ctx.Repo.Repository.CanEnablePulls() && ctx.Repo.CanRead(models.UnitTypePullRequests)) { if ctx.Repo.Repository.CanEnablePulls() && log.IsTrace() { if ctx.IsSigned { log.Trace("Permission Denied: User %-v cannot read %-v and %-v in Repo %-v\n"+ "User in Repo has Permissions: %-+v", ctx.User, models.UnitTypeIssues, models.UnitTypePullRequests, ctx.Repo.Repository, ctx.Repo.Permission) } else { log.Trace("Permission Denied: Anonymous user cannot read %-v and %-v in Repo %-v\n"+ "Anonymous user in Repo has Permissions: %-+v", models.UnitTypeIssues, models.UnitTypePullRequests, ctx.Repo.Repository, ctx.Repo.Permission) } } ctx.NotFound() return } } func mustEnableUserHeatmap(ctx *context.APIContext) { if !setting.Service.EnableUserHeatmap { ctx.NotFound() return } } func mustNotBeArchived(ctx *context.APIContext) { if ctx.Repo.Repository.IsArchived { ctx.NotFound() return } } // RegisterRoutes registers all v1 APIs routes to web application. // FIXME: custom form error response func RegisterRoutes(m *macaron.Macaron) { bind := binding.Bind if setting.API.EnableSwagger { m.Get("/swagger", misc.Swagger) //Render V1 by default } m.Group("/v1", func() { // Miscellaneous if setting.API.EnableSwagger { m.Get("/swagger", misc.Swagger) } m.Get("/version", misc.Version) m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) m.Post("/markdown/raw", misc.MarkdownRaw) // Users m.Group("/users", func() { m.Get("/search", user.Search) m.Group("/:username", func() { m.Get("", user.GetInfo) m.Get("/heatmap", mustEnableUserHeatmap, user.GetUserHeatmapData) m.Get("/repos", user.ListUserRepos) m.Group("/tokens", func() { m.Combo("").Get(user.ListAccessTokens). Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken) m.Combo("/:id").Delete(user.DeleteAccessToken) }, reqBasicAuth()) }) }) m.Group("/users", func() { m.Group("/:username", func() { m.Get("/keys", user.ListPublicKeys) m.Get("/gpg_keys", user.ListGPGKeys) m.Get("/followers", user.ListFollowers) m.Group("/following", func() { m.Get("", user.ListFollowing) m.Get("/:target", user.CheckFollowing) }) m.Get("/starred", user.GetStarredRepos) m.Get("/subscriptions", user.GetWatchedRepos) }) }, reqToken()) m.Group("/user", func() { m.Get("", user.GetAuthenticatedUser) m.Combo("/emails").Get(user.ListEmails). Post(bind(api.CreateEmailOption{}), user.AddEmail). Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail) m.Get("/followers", user.ListMyFollowers) m.Group("/following", func() { m.Get("", user.ListMyFollowing) m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow) }) m.Group("/keys", func() { m.Combo("").Get(user.ListMyPublicKeys). Post(bind(api.CreateKeyOption{}), user.CreatePublicKey) m.Combo("/:id").Get(user.GetPublicKey). Delete(user.DeletePublicKey) }) m.Group("/gpg_keys", func() { m.Combo("").Get(user.ListMyGPGKeys). Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey) m.Combo("/:id").Get(user.GetGPGKey). Delete(user.DeleteGPGKey) }) m.Combo("/repos").Get(user.ListMyRepos). Post(bind(api.CreateRepoOption{}), repo.Create) m.Group("/starred", func() { m.Get("", user.GetMyStarredRepos) m.Group("/:username/:reponame", func() { m.Get("", user.IsStarring) m.Put("", user.Star) m.Delete("", user.Unstar) }, repoAssignment()) }) m.Get("/times", repo.ListMyTrackedTimes) m.Get("/subscriptions", user.GetMyWatchedRepos) m.Get("/teams", org.ListUserTeams) }, reqToken()) // Repositories m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Group("/repos", func() { m.Get("/search", repo.Search) }) m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID) m.Group("/repos", func() { m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate) m.Group("/:username/:reponame", func() { m.Combo("").Get(reqAnyRepoReader(), repo.Get). Delete(reqToken(), reqOwner(), repo.Delete). Patch(reqToken(), reqAdmin(), bind(api.EditRepoOption{}), repo.Edit) m.Group("/hooks", func() { m.Combo("").Get(repo.ListHooks). Post(bind(api.CreateHookOption{}), repo.CreateHook) m.Group("/:id", func() { m.Combo("").Get(repo.GetHook). Patch(bind(api.EditHookOption{}), repo.EditHook). Delete(repo.DeleteHook) m.Post("/tests", context.RepoRef(), repo.TestHook) }) m.Group("/git", func() { m.Combo("").Get(repo.ListGitHooks) m.Group("/:id", func() { m.Combo("").Get(repo.GetGitHook). Patch(bind(api.EditGitHookOption{}), repo.EditGitHook). Delete(repo.DeleteGitHook) }) }, reqGitHook(), context.ReferencesGitRepo(true)) }, reqToken(), reqAdmin()) m.Group("/collaborators", func() { m.Get("", repo.ListCollaborators) m.Combo("/:collaborator").Get(repo.IsCollaborator). Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator). Delete(repo.DeleteCollaborator) }, reqToken(), reqAdmin()) m.Get("/raw/*", context.RepoRefByType(context.RepoRefAny), reqRepoReader(models.UnitTypeCode), repo.GetRawFile) m.Get("/archive/*", reqRepoReader(models.UnitTypeCode), repo.GetArchive) m.Combo("/forks").Get(repo.ListForks). Post(reqToken(), reqRepoReader(models.UnitTypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", context.RepoRefByType(context.RepoRefBranch), repo.GetBranch) }, reqRepoReader(models.UnitTypeCode)) m.Group("/tags", func() { m.Get("", repo.ListTags) }, reqRepoReader(models.UnitTypeCode)) m.Group("/keys", func() { m.Combo("").Get(repo.ListDeployKeys). Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) m.Combo("/:id").Get(repo.GetDeployKey). Delete(repo.DeleteDeploykey) }, reqToken(), reqAdmin()) m.Group("/times", func() { m.Combo("").Get(repo.ListTrackedTimesByRepository) m.Combo("/:timetrackingusername").Get(repo.ListTrackedTimesByUser) }, mustEnableIssues) m.Group("/issues", func() { m.Combo("").Get(repo.ListIssues). Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueOption{}), repo.CreateIssue) m.Group("/comments", func() { m.Get("", repo.ListRepoIssueComments) m.Combo("/:id", reqToken()). Patch(mustNotBeArchived, bind(api.EditIssueCommentOption{}), repo.EditIssueComment). Delete(repo.DeleteIssueComment) }) m.Group("/:index", func() { m.Combo("").Get(repo.GetIssue). Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue) m.Group("/comments", func() { m.Combo("").Get(repo.ListIssueComments). Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueCommentDeprecated). Delete(repo.DeleteIssueCommentDeprecated) }) m.Group("/labels", func() { m.Combo("").Get(repo.ListIssueLabels). Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels). Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). Delete(reqToken(), repo.ClearIssueLabels) m.Delete("/:id", reqToken(), repo.DeleteIssueLabel) }) m.Group("/times", func() { m.Combo("").Get(repo.ListTrackedTimes). Post(reqToken(), bind(api.AddTimeOption{}), repo.AddTime) }) m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) m.Group("/stopwatch", func() { m.Post("/start", reqToken(), repo.StartIssueStopwatch) m.Post("/stop", reqToken(), repo.StopIssueStopwatch) }) }) }, mustEnableIssuesOrPulls) m.Group("/labels", func() { m.Combo("").Get(repo.ListLabels). Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateLabelOption{}), repo.CreateLabel) m.Combo("/:id").Get(repo.GetLabel). Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditLabelOption{}), repo.EditLabel). Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteLabel) }) m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) m.Post("/markdown/raw", misc.MarkdownRaw) m.Group("/milestones", func() { m.Combo("").Get(repo.ListMilestones). Post(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.CreateMilestoneOption{}), repo.CreateMilestone) m.Combo("/:id").Get(repo.GetMilestone). Patch(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). Delete(reqToken(), reqRepoWriter(models.UnitTypeIssues, models.UnitTypePullRequests), repo.DeleteMilestone) }) m.Get("/stargazers", repo.ListStargazers) m.Get("/subscribers", repo.ListSubscribers) m.Group("/subscription", func() { m.Get("", user.IsWatching) m.Put("", reqToken(), user.Watch) m.Delete("", reqToken(), user.Unwatch) }) m.Group("/releases", func() { m.Combo("").Get(repo.ListReleases). Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.CreateReleaseOption{}), repo.CreateRelease) m.Group("/:id", func() { m.Combo("").Get(repo.GetRelease). Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), context.ReferencesGitRepo(false), bind(api.EditReleaseOption{}), repo.EditRelease). Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteRelease) m.Group("/assets", func() { m.Combo("").Get(repo.ListReleaseAttachments). Post(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.CreateReleaseAttachment) m.Combo("/:asset").Get(repo.GetReleaseAttachment). Patch(reqToken(), reqRepoWriter(models.UnitTypeReleases), bind(api.EditAttachmentOptions{}), repo.EditReleaseAttachment). Delete(reqToken(), reqRepoWriter(models.UnitTypeReleases), repo.DeleteReleaseAttachment) }) }) }, reqRepoReader(models.UnitTypeReleases)) m.Post("/mirror-sync", reqToken(), reqRepoWriter(models.UnitTypeCode), repo.MirrorSync) m.Get("/editorconfig/:filename", context.RepoRef(), reqRepoReader(models.UnitTypeCode), repo.GetEditorconfig) m.Group("/pulls", func() { m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests). Post(reqToken(), mustNotBeArchived, bind(api.CreatePullRequestOption{}), repo.CreatePullRequest) m.Group("/:index", func() { m.Combo("").Get(repo.GetPullRequest). Patch(reqToken(), reqRepoWriter(models.UnitTypePullRequests), bind(api.EditPullRequestOption{}), repo.EditPullRequest) m.Combo("/merge").Get(repo.IsPullRequestMerged). Post(reqToken(), mustNotBeArchived, reqRepoWriter(models.UnitTypePullRequests), bind(auth.MergePullRequestForm{}), repo.MergePullRequest) }) }, mustAllowPulls, reqRepoReader(models.UnitTypeCode), context.ReferencesGitRepo(false)) m.Group("/statuses", func() { m.Combo("/:sha").Get(repo.GetCommitStatuses). Post(reqToken(), bind(api.CreateStatusOption{}), repo.NewCommitStatus) }, reqRepoReader(models.UnitTypeCode)) m.Group("/commits", func() { m.Get("", repo.GetAllCommits) m.Group("/:ref", func() { // TODO: Add m.Get("") for single commit (https://developer.github.com/v3/repos/commits/#get-a-single-commit) m.Get("/status", repo.GetCombinedCommitStatusByRef) m.Get("/statuses", repo.GetCommitStatusesByRef) }) }, reqRepoReader(models.UnitTypeCode)) m.Group("/git", func() { m.Group("/commits", func() { m.Get("/:sha", repo.GetSingleCommit) }) m.Get("/refs", repo.GetGitAllRefs) m.Get("/refs/*", repo.GetGitRefs) m.Get("/trees/:sha", context.RepoRef(), repo.GetTree) m.Get("/blobs/:sha", context.RepoRef(), repo.GetBlob) m.Get("/tags/:sha", context.RepoRef(), repo.GetTag) }, reqRepoReader(models.UnitTypeCode)) m.Group("/contents", func() { m.Get("", repo.GetContentsList) m.Get("/*", repo.GetContents) m.Group("/*", func() { m.Post("", bind(api.CreateFileOptions{}), repo.CreateFile) m.Put("", bind(api.UpdateFileOptions{}), repo.UpdateFile) m.Delete("", bind(api.DeleteFileOptions{}), repo.DeleteFile) }, reqRepoWriter(models.UnitTypeCode), reqToken()) }, reqRepoReader(models.UnitTypeCode)) m.Group("/topics", func() { m.Combo("").Get(repo.ListTopics). Put(reqToken(), reqAdmin(), bind(api.RepoTopicOptions{}), repo.UpdateTopics) m.Group("/:topic", func() { m.Combo("").Put(reqToken(), repo.AddTopic). Delete(reqToken(), repo.DeleteTopic) }, reqAdmin()) }, reqAnyRepoReader()) }, repoAssignment()) }) // Organizations m.Get("/user/orgs", reqToken(), org.ListMyOrgs) m.Get("/users/:username/orgs", org.ListUserOrgs) m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create) m.Group("/orgs/:orgname", func() { m.Get("/repos", user.ListOrgRepos) m.Combo("").Get(org.Get). Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit). Delete(reqToken(), reqOrgOwnership(), org.Delete) m.Group("/members", func() { m.Get("", org.ListMembers) m.Combo("/:username").Get(org.IsMember). Delete(reqToken(), reqOrgOwnership(), org.DeleteMember) }) m.Group("/public_members", func() { m.Get("", org.ListPublicMembers) m.Combo("/:username").Get(org.IsPublicMember). Put(reqToken(), reqOrgMembership(), org.PublicizeMember). Delete(reqToken(), reqOrgMembership(), org.ConcealMember) }) m.Combo("/teams", reqToken(), reqOrgMembership()).Get(org.ListTeams). Post(reqOrgOwnership(), bind(api.CreateTeamOption{}), org.CreateTeam) m.Group("/hooks", func() { m.Combo("").Get(org.ListHooks). Post(bind(api.CreateHookOption{}), org.CreateHook) m.Combo("/:id").Get(org.GetHook). Patch(bind(api.EditHookOption{}), org.EditHook). Delete(org.DeleteHook) }, reqToken(), reqOrgOwnership()) }, orgAssignment(true)) m.Group("/teams/:teamid", func() { m.Combo("").Get(org.GetTeam). Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam). Delete(reqOrgOwnership(), org.DeleteTeam) m.Group("/members", func() { m.Get("", org.GetTeamMembers) m.Combo("/:username"). Get(org.GetTeamMember). Put(reqOrgOwnership(), org.AddTeamMember). Delete(reqOrgOwnership(), org.RemoveTeamMember) }) m.Group("/repos", func() { m.Get("", org.GetTeamRepos) m.Combo("/:orgname/:reponame"). Put(org.AddTeamRepository). Delete(org.RemoveTeamRepository) }) }, orgAssignment(false, true), reqToken(), reqTeamMembership()) m.Any("/*", func(ctx *context.APIContext) { ctx.NotFound() }) m.Group("/admin", func() { m.Get("/orgs", admin.GetAllOrgs) m.Group("/users", func() { m.Get("", admin.GetAllUsers) m.Post("", bind(api.CreateUserOption{}), admin.CreateUser) m.Group("/:username", func() { m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser). Delete(admin.DeleteUser) m.Group("/keys", func() { m.Post("", bind(api.CreateKeyOption{}), admin.CreatePublicKey) m.Delete("/:id", admin.DeleteUserPublicKey) }) m.Get("/orgs", org.ListUserOrgs) m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg) m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo) }) }) }, reqToken(), reqSiteAdmin()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) }) }, securityHeaders(), context.APIContexter(), sudo()) } func securityHeaders() macaron.Handler { return func(ctx *macaron.Context) { ctx.Resp.Before(func(w macaron.ResponseWriter) { // CORB: https://www.chromium.org/Home/chromium-security/corb-for-developers // http://stackoverflow.com/a/3146618/244009 w.Header().Set("x-content-type-options", "nosniff") }) } }
mit
Lafriakh/kira
helpers/size.go
627
package helpers import ( "unicode/utf8" ) // Size return size of string or float64 or float32 or slice func Size(value interface{}) float64 { switch value.(type) { // convert string value to integer case string: return float64(utf8.RuneCountInString(value.(string))) case float32: return float64(value.(float32)) case int: return float64(value.(int)) case []string: return float64(len(value.([]string))) case []int: return float64(len(value.([]int))) case []float32: return float64(len(value.([]float32))) case []float64: return float64(len(value.([]float64))) default: return value.(float64) } }
mit
sreepadbhagwat/aplos
aplos/src/main/java/com/github/sreepadbhagwat/aplos/api/Button.java
132
package com.github.sreepadbhagwat.aplos.api; public interface Button { public void click(String identifier, String locator); }
mit
sadrayan/coraltec
src/WS/CoraltecBundle/WSCoraltecBundle.php
128
<?php namespace WS\CoraltecBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class WSCoraltecBundle extends Bundle { }
mit
diirt/diirt
graphene/graphene/src/main/java/org/diirt/graphene/LineTimeGraph2DRendererUpdate.java
921
/** * Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.graphene; /** * * @author carcassi */ public class LineTimeGraph2DRendererUpdate extends TemporalGraph2DRendererUpdate<LineTimeGraph2DRendererUpdate> { private InterpolationScheme interpolation; public LineTimeGraph2DRendererUpdate interpolation(InterpolationScheme scheme) { if (scheme == null) { throw new NullPointerException("Interpolation scheme can't be null"); } if (!LineTimeGraph2DRenderer.supportedInterpolationScheme.contains(scheme)) { throw new IllegalArgumentException("Interpolation " + scheme + " is not supported"); } this.interpolation = scheme; return this; } public InterpolationScheme getInterpolation() { return interpolation; } }
mit
phpstan/phpstan
e2e/excludePaths2/src/foo.php
47
<?php $t = new \ThirdpartyClass(); $t->test();
mit
Azure/azure-sdk-for-go
sdk/resourcemanager/devops/armdevops/zz_generated_pipelines_client.go
17829
//go:build go1.16 // +build go1.16 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. package armdevops import ( "context" "errors" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "net/http" "net/url" "strings" ) // PipelinesClient contains the methods for the Pipelines group. // Don't use this type directly, use NewPipelinesClient() instead. type PipelinesClient struct { host string subscriptionID string pl runtime.Pipeline } // NewPipelinesClient creates a new instance of PipelinesClient with the specified values. // subscriptionID - Unique identifier of the Azure subscription. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). // credential - used to authorize requests. Usually a credential from azidentity. // options - pass nil to accept the default values. func NewPipelinesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *PipelinesClient { cp := arm.ClientOptions{} if options != nil { cp = *options } if len(cp.Endpoint) == 0 { cp.Endpoint = arm.AzurePublicCloud } client := &PipelinesClient{ subscriptionID: subscriptionID, host: string(cp.Endpoint), pl: armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, &cp), } return client } // BeginCreateOrUpdate - Creates or updates an Azure Pipeline. // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - Name of the resource group within the Azure subscription. // pipelineName - The name of the Azure Pipeline resource in ARM. // createOperationParameters - The request payload to create the Azure Pipeline. // options - PipelinesClientBeginCreateOrUpdateOptions contains the optional parameters for the PipelinesClient.BeginCreateOrUpdate // method. func (client *PipelinesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, pipelineName string, createOperationParameters Pipeline, options *PipelinesClientBeginCreateOrUpdateOptions) (PipelinesClientCreateOrUpdatePollerResponse, error) { resp, err := client.createOrUpdate(ctx, resourceGroupName, pipelineName, createOperationParameters, options) if err != nil { return PipelinesClientCreateOrUpdatePollerResponse{}, err } result := PipelinesClientCreateOrUpdatePollerResponse{ RawResponse: resp, } pt, err := armruntime.NewPoller("PipelinesClient.CreateOrUpdate", "", resp, client.pl) if err != nil { return PipelinesClientCreateOrUpdatePollerResponse{}, err } result.Poller = &PipelinesClientCreateOrUpdatePoller{ pt: pt, } return result, nil } // CreateOrUpdate - Creates or updates an Azure Pipeline. // If the operation fails it returns an *azcore.ResponseError type. func (client *PipelinesClient) createOrUpdate(ctx context.Context, resourceGroupName string, pipelineName string, createOperationParameters Pipeline, options *PipelinesClientBeginCreateOrUpdateOptions) (*http.Response, error) { req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, pipelineName, createOperationParameters, options) if err != nil { return nil, err } resp, err := client.pl.Do(req) if err != nil { return nil, err } if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { return nil, runtime.NewResponseError(resp) } return resp, nil } // createOrUpdateCreateRequest creates the CreateOrUpdate request. func (client *PipelinesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, pipelineName string, createOperationParameters Pipeline, options *PipelinesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOps/pipelines/{pipelineName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if pipelineName == "" { return nil, errors.New("parameter pipelineName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{pipelineName}", url.PathEscape(pipelineName)) req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2019-07-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, runtime.MarshalAsJSON(req, createOperationParameters) } // Delete - Deletes an Azure Pipeline. // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - Name of the resource group within the Azure subscription. // pipelineName - The name of the Azure Pipeline resource. // options - PipelinesClientDeleteOptions contains the optional parameters for the PipelinesClient.Delete method. func (client *PipelinesClient) Delete(ctx context.Context, resourceGroupName string, pipelineName string, options *PipelinesClientDeleteOptions) (PipelinesClientDeleteResponse, error) { req, err := client.deleteCreateRequest(ctx, resourceGroupName, pipelineName, options) if err != nil { return PipelinesClientDeleteResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return PipelinesClientDeleteResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { return PipelinesClientDeleteResponse{}, runtime.NewResponseError(resp) } return PipelinesClientDeleteResponse{RawResponse: resp}, nil } // deleteCreateRequest creates the Delete request. func (client *PipelinesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, pipelineName string, options *PipelinesClientDeleteOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOps/pipelines/{pipelineName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if pipelineName == "" { return nil, errors.New("parameter pipelineName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{pipelineName}", url.PathEscape(pipelineName)) req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2019-07-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, nil } // Get - Gets an existing Azure Pipeline. // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - Name of the resource group within the Azure subscription. // pipelineName - The name of the Azure Pipeline resource in ARM. // options - PipelinesClientGetOptions contains the optional parameters for the PipelinesClient.Get method. func (client *PipelinesClient) Get(ctx context.Context, resourceGroupName string, pipelineName string, options *PipelinesClientGetOptions) (PipelinesClientGetResponse, error) { req, err := client.getCreateRequest(ctx, resourceGroupName, pipelineName, options) if err != nil { return PipelinesClientGetResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return PipelinesClientGetResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return PipelinesClientGetResponse{}, runtime.NewResponseError(resp) } return client.getHandleResponse(resp) } // getCreateRequest creates the Get request. func (client *PipelinesClient) getCreateRequest(ctx context.Context, resourceGroupName string, pipelineName string, options *PipelinesClientGetOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOps/pipelines/{pipelineName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if pipelineName == "" { return nil, errors.New("parameter pipelineName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{pipelineName}", url.PathEscape(pipelineName)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2019-07-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, nil } // getHandleResponse handles the Get response. func (client *PipelinesClient) getHandleResponse(resp *http.Response) (PipelinesClientGetResponse, error) { result := PipelinesClientGetResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.Pipeline); err != nil { return PipelinesClientGetResponse{}, err } return result, nil } // ListByResourceGroup - Lists all Azure Pipelines under the specified resource group. // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - Name of the resource group within the Azure subscription. // options - PipelinesClientListByResourceGroupOptions contains the optional parameters for the PipelinesClient.ListByResourceGroup // method. func (client *PipelinesClient) ListByResourceGroup(resourceGroupName string, options *PipelinesClientListByResourceGroupOptions) *PipelinesClientListByResourceGroupPager { return &PipelinesClientListByResourceGroupPager{ client: client, requester: func(ctx context.Context) (*policy.Request, error) { return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) }, advancer: func(ctx context.Context, resp PipelinesClientListByResourceGroupResponse) (*policy.Request, error) { return runtime.NewRequest(ctx, http.MethodGet, *resp.PipelineListResult.NextLink) }, } } // listByResourceGroupCreateRequest creates the ListByResourceGroup request. func (client *PipelinesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *PipelinesClientListByResourceGroupOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOps/pipelines" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2019-07-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, nil } // listByResourceGroupHandleResponse handles the ListByResourceGroup response. func (client *PipelinesClient) listByResourceGroupHandleResponse(resp *http.Response) (PipelinesClientListByResourceGroupResponse, error) { result := PipelinesClientListByResourceGroupResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.PipelineListResult); err != nil { return PipelinesClientListByResourceGroupResponse{}, err } return result, nil } // ListBySubscription - Lists all Azure Pipelines under the specified subscription. // If the operation fails it returns an *azcore.ResponseError type. // options - PipelinesClientListBySubscriptionOptions contains the optional parameters for the PipelinesClient.ListBySubscription // method. func (client *PipelinesClient) ListBySubscription(options *PipelinesClientListBySubscriptionOptions) *PipelinesClientListBySubscriptionPager { return &PipelinesClientListBySubscriptionPager{ client: client, requester: func(ctx context.Context) (*policy.Request, error) { return client.listBySubscriptionCreateRequest(ctx, options) }, advancer: func(ctx context.Context, resp PipelinesClientListBySubscriptionResponse) (*policy.Request, error) { return runtime.NewRequest(ctx, http.MethodGet, *resp.PipelineListResult.NextLink) }, } } // listBySubscriptionCreateRequest creates the ListBySubscription request. func (client *PipelinesClient) listBySubscriptionCreateRequest(ctx context.Context, options *PipelinesClientListBySubscriptionOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DevOps/pipelines" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2019-07-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, nil } // listBySubscriptionHandleResponse handles the ListBySubscription response. func (client *PipelinesClient) listBySubscriptionHandleResponse(resp *http.Response) (PipelinesClientListBySubscriptionResponse, error) { result := PipelinesClientListBySubscriptionResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.PipelineListResult); err != nil { return PipelinesClientListBySubscriptionResponse{}, err } return result, nil } // Update - Updates the properties of an Azure Pipeline. Currently, only tags can be updated. // If the operation fails it returns an *azcore.ResponseError type. // resourceGroupName - Name of the resource group within the Azure subscription. // pipelineName - The name of the Azure Pipeline resource. // updateOperationParameters - The request payload containing the properties to update in the Azure Pipeline. // options - PipelinesClientUpdateOptions contains the optional parameters for the PipelinesClient.Update method. func (client *PipelinesClient) Update(ctx context.Context, resourceGroupName string, pipelineName string, updateOperationParameters PipelineUpdateParameters, options *PipelinesClientUpdateOptions) (PipelinesClientUpdateResponse, error) { req, err := client.updateCreateRequest(ctx, resourceGroupName, pipelineName, updateOperationParameters, options) if err != nil { return PipelinesClientUpdateResponse{}, err } resp, err := client.pl.Do(req) if err != nil { return PipelinesClientUpdateResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return PipelinesClientUpdateResponse{}, runtime.NewResponseError(resp) } return client.updateHandleResponse(resp) } // updateCreateRequest creates the Update request. func (client *PipelinesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, pipelineName string, updateOperationParameters PipelineUpdateParameters, options *PipelinesClientUpdateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOps/pipelines/{pipelineName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if pipelineName == "" { return nil, errors.New("parameter pipelineName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{pipelineName}", url.PathEscape(pipelineName)) req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.host, urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2019-07-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header.Set("Accept", "application/json") return req, runtime.MarshalAsJSON(req, updateOperationParameters) } // updateHandleResponse handles the Update response. func (client *PipelinesClient) updateHandleResponse(resp *http.Response) (PipelinesClientUpdateResponse, error) { result := PipelinesClientUpdateResponse{RawResponse: resp} if err := runtime.UnmarshalAsJSON(resp, &result.Pipeline); err != nil { return PipelinesClientUpdateResponse{}, err } return result, nil }
mit
elitmus/autocomplete_locations
app/controllers/autocomplete_locations/application_controller.rb
136
module AutocompleteLocations class ApplicationController < ActionController::Base protect_from_forgery with: :exception end end
mit
yutin1987/dingtaxi
www/js/app.js
1501
// Ionic Starter App angular.module('starter', ['ionic', 'starter.services', 'starter.controllers']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('menu', { url: "/menu", abstract: true, templateUrl: "templates/menu.html" }) .state('menu.workday', { url: '/workday', views: { 'main-view': { templateUrl: 'templates/workday.html' } } }) .state('menu.order', { url: '/order', views: { 'main-view': { templateUrl: 'templates/order.html', } } }) .state('menu.order.wait', { url: '/wait', views: { 'wait-tab': { templateUrl: 'templates/order_wait.html', } } }) .state('menu.order.sent', { url: '/sent', views: { 'sent-tab': { templateUrl: 'templates/order_sent.html', } } }) .state('menu.order.expired', { url: '/expired', views: { 'expired-tab': { templateUrl: 'templates/order_expired.html', } } }) .state('menu.setting', { url: '/setting', views: { 'main-view': { templateUrl: 'templates/setting.html' } } }) .state('login', { url: '/login', templateUrl: 'templates/login.html' }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/login'); });
mit
idlewinn/playground
webpack.config.js
565
const path = require("path"); const HtmlWebpackPluginConfig = require("html-webpack-plugin"); module.exports = { entry: "./dev/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname, "dist") }, module: { loaders: [ { test: /\.jsx?/, loader: "babel-loader", exclude: /node_modules/ } ] }, resolve: { extensions: [".js", ".jsx"] }, plugins: [ new HtmlWebpackPluginConfig({ title: "Playground", hash: true, template: "./dev/index.html" }) ], devServer: { port: 3000 } };
mit
twigyard/twigyard
src/TwigYard/Middleware/Header/HeaderMiddleware.php
4433
<?php namespace TwigYard\Middleware\Header; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use TwigYard\Component\AppState; use TwigYard\Middleware\MiddlewareInterface; class HeaderMiddleware implements MiddlewareInterface { const HEADER_CONFIG = 'header'; const HEADER_CONTENT_SECURITY_POLICY = 'Content-Security-Policy'; const HEADER_REFERRER_POLICY = 'Referrer-Policy'; const HEADER_X_CONTENT_TYPE_OPTIONS = 'X-Content-Type-Options'; const HEADER_DEFAULT_PARAMS = [ self::HEADER_CONTENT_SECURITY_POLICY => 'default-src * \'unsafe-inline\' \'unsafe-eval\';', self::HEADER_REFERRER_POLICY => 'strict-origin', self::HEADER_X_CONTENT_TYPE_OPTIONS => 'nosniff', ]; const HEADER_DEFAULT_SECURE_PARAMS = [ self::HEADER_CONTENT_SECURITY_POLICY => 'default-src https: \'unsafe-inline\' \'unsafe-eval\';', ]; /** * @var AppState */ private $appState; /** * HeaderMiddleware constructor. */ public function __construct(AppState $appState) { $this->appState = $appState; } /** * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $config = $this->appState->getMiddlewareConfig(); $headers = self::HEADER_DEFAULT_PARAMS; if ($this->appState->getScheme() === 'https') { $headers = array_merge($headers, self::HEADER_DEFAULT_SECURE_PARAMS); } if (is_array($config) && array_key_exists(self::HEADER_CONFIG, $config)) { if (is_array($config[self::HEADER_CONFIG])) { $headers = $this->setContentSecurityPolicyHeader($headers, $config[self::HEADER_CONFIG]); $headers = $this->setRefererPolicyHeader($headers, $config[self::HEADER_CONFIG]); $headers = $this->setXContentTypeOptionsHeader($headers, $config[self::HEADER_CONFIG]); } else { $headers = $this->resetHeaders($headers); } } foreach ($headers as $name => $value) { if ($value) { $response = $response->withHeader($name, $value); } } return $next($request, $response); } private function setContentSecurityPolicyHeader(array $headers, array $headerConfig): array { if (array_key_exists(self::HEADER_CONTENT_SECURITY_POLICY, $headerConfig)) { $headers[self::HEADER_CONTENT_SECURITY_POLICY] = ''; if (is_array($headerConfig[self::HEADER_CONTENT_SECURITY_POLICY])) { foreach ($headerConfig[self::HEADER_CONTENT_SECURITY_POLICY] as $name => $value) { if (is_array($value)) { $headers[self::HEADER_CONTENT_SECURITY_POLICY] .= sprintf( '%s %s; ', $name, implode(' ', $value) ); } } $headers[self::HEADER_CONTENT_SECURITY_POLICY] = rtrim($headers[self::HEADER_CONTENT_SECURITY_POLICY]); } if (!mb_strlen($headers[self::HEADER_CONTENT_SECURITY_POLICY])) { unset($headers[self::HEADER_CONTENT_SECURITY_POLICY]); } } if (array_key_exists(self::HEADER_REFERRER_POLICY, $headerConfig)) { $headers[self::HEADER_REFERRER_POLICY] = $headerConfig[self::HEADER_REFERRER_POLICY]; } return $headers; } private function setRefererPolicyHeader(array $headers, array $headerConfig): array { if (array_key_exists(self::HEADER_REFERRER_POLICY, $headerConfig)) { $headers[self::HEADER_REFERRER_POLICY] = $headerConfig[self::HEADER_REFERRER_POLICY]; } return $headers; } private function setXContentTypeOptionsHeader(array $headers, array $headerConfig): array { if (array_key_exists(self::HEADER_X_CONTENT_TYPE_OPTIONS, $headerConfig)) { $headers[self::HEADER_X_CONTENT_TYPE_OPTIONS] = $headerConfig[self::HEADER_X_CONTENT_TYPE_OPTIONS]; } return $headers; } private function resetHeaders(array $headers): array { foreach ($headers as $name => $value) { unset($headers[$name]); } return $headers; } }
mit
ser910/Exam
Zip/Properties/AssemblyInfo.cs
1382
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zip")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zip")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d33eda55-ea68-4005-aef4-a65ce14f0411")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
Peppa-Peddler/users
users/routes/clearUser.js
748
var express = require('express'); var router = express.Router(); var knex = require('../db/connection'); var User = require('../models/user'); var passport = require('passport'); /* POST clear user account. */ router.post('/', isLoggedInAdmin, function(req, res) { if (req.body.user_id != "58ec0b8f68be5a12c30da409") { User.remove({"local.username":req.body.user_name}).exec(function (err, result) { console.log('Removed: ' + req.body.user_name); res.redirect('/signup'); }); } else { console.log(req.body.user_id); } }); module.exports = router; function isLoggedInAdmin(req,res,next){ if(req.isAuthenticated() && req.user.local.tipo == "0" ){ console.log("authenticated as Admin!"); return next(); } res.redirect('/'); }
mit
DragonSpark/Framework
DragonSpark/Reflection/AccountForUnassignedType.cs
487
using DragonSpark.Model.Selection.Alterations; using System; using System.Reflection; namespace DragonSpark.Reflection; sealed class AccountForUnassignedType : IAlteration<TypeInfo> { public static AccountForUnassignedType Default { get; } = new AccountForUnassignedType(); AccountForUnassignedType() {} public TypeInfo Get(TypeInfo parameter) => Nullable.GetUnderlyingType(parameter.AsType()) ?.GetTypeInfo() ?? parameter; }
mit
boada/vpCluster
data/boada/august_2012/analysis/parseResults.py
1327
import glob from numpy import genfromtxt, asarray, savetxt files = glob.glob('*_results/*.results') r = [] for f in files: print f cluster, field, dither = f.split('/')[1].split('_') data = genfromtxt(f, delimiter='\t', names=True, dtype=None) try: for fiber, z, Q, z_err in zip(data['Fiber'], data['Redshift'], data['Quality'], data['RedshiftError']): #if Q == 0 or Q == 1: r.append((cluster, field, dither.split('.')[0], fiber, Q, z, z_err)) except TypeError: fiber = int(data['Fiber']) z = float(data['Redshift']) Q = int(data['Quality']) z_err = float(data['RedshiftError']) if Q == 0 or Q == 1: r.append( (cluster, field, dither.split('.')[0], fiber, Q, z, z_err)) print len(r), 'objects read' #print r r = asarray(r) #data = zeros((r.shape[0],), dtype=[('cluster', 'a13'), ('field', 'a2'), ('dither', # '>i4'), ('fiber', '>i4'), ('redshift', '>f4')]) #data['cluster'] = r[:,0] #data['field'] = r[:,1] #data['dither'] = r[:,2] #data['fiber'] = r[:,3] #data['redshift'] = r[:,4] savetxt('results_august12', r, delimiter=' ', fmt='%s', header=r'#cluster, tile, dither, fiber, Q, redshift, redshift_err')
mit
willstepp/reliefdb
test/unit/history_test.rb
284
require File.dirname(__FILE__) + '/../test_helper' class HistoryTest < Test::Unit::TestCase fixtures :histories def setup @history = History.find(1) end # Replace this with your real tests. def test_truth assert_kind_of History, @history end end
mit
mobilecart/mobilecartadminbundle
Resources/public/js/html5imageuploader/image-table.js
1656
var ImageTable = function(info) { this.bodyEl = info.bodyEl; } ImageTable.prototype = { add: function(obj) { this.bodyEl.append(this.buildRow(obj)); }, buildRow: function(obj) { var html = ''; html += '<tr data-id="' + obj.id + '">' + '<td><a target="_blank" href="/'+ obj.relative_path +'">View</a></td>' + '<td>' + obj.width + ' x ' + obj.height + '</td>' + '<td>' + obj.code + '</td>' + '<td><input type="number" class="form-control image-sort-order" value="1" /></td>' + '<td><input type="checkbox" class="image-is-default" value="1" /></td>' + '<td><textarea class="form-control image-alt-text"></textarea></td>' + '<td><a href="#" class="btn btn-default image-remove-btn"><i class="glyphicon glyphicon-remove"> </i></a></td>' + '</tr>'; return html; }, serialize: function() { //rebuild json string before submitting form var images = []; this.bodyEl.find('tr').each(function(){ var self = $(this); var id = self.attr('data-id'); var sortOrder = self.find('input.image-sort-order').val(); var isDefault = self.find('input.image-is-default').is(':checked'); var altText = self.find('textarea.image-alt-text').val(); var image = { id: id, sort_order: sortOrder, is_default: isDefault, alt_text: altText }; images.push(image); }); $('input#images_json').val(JSON.stringify(images)); } };
mit
shore-gmbh/shore-ruby-client
spec/shore/v1/short_url_spec.rb
181
# frozen_string_literal: true RSpec.describe Shore::V1::ShortURL do include_examples 'shore json api client' do let(:url) { 'https://api.shore.com/v1/short_urls' } end end
mit
jericks/wkg
src/main/java/org/cugos/wkg/GeoJSONReader.java
12774
package org.cugos.wkg; import org.antlr.v4.runtime.*; import org.cugos.wkg.internal.JSONBaseListener; import org.cugos.wkg.internal.JSONLexer; import org.cugos.wkg.internal.JSONParser; import java.util.*; /** * Read a Geometry from a GeoJSON String * @author Jared Erickson */ public class GeoJSONReader implements Reader<String> { /** * The default SRID for GeoJSON is EPSG:4326 */ private final String srid = "4326"; /** * Read a Geometry from a GeoJSON String * @param jsonStr The GeoJSON String * @return The Geometry or null */ @Override public Geometry read(String jsonStr) { JSON json = parse(jsonStr); Geometry geometry = null; if (json instanceof JSONObject) { JSONObject jsonObject = (JSONObject) json; String type = jsonObject.get("type").toString(); if (type.equalsIgnoreCase("feature")) { geometry = readGeometry((JSONObject) jsonObject.get("geometry")).setData(((JSONObject) jsonObject.get("properties")).values()); } else if (type.equalsIgnoreCase("featurecollection")) { JSONArray jsonArray = (JSONArray) jsonObject.get("features"); List<Geometry> geometries = new ArrayList<>(); for (Object feature : jsonArray.values()) { JSONObject featureJSONObject = (JSONObject) feature; JSONObject geometryJSONObject = (JSONObject) (featureJSONObject.get("geometry")); geometries.add(readGeometry(geometryJSONObject).setData(((JSONObject) featureJSONObject.get("properties")).values())); } geometry = new GeometryCollection(geometries, geometries.isEmpty() ? Dimension.Two : geometries.get(0).getDimension(), srid); } else { geometry = readGeometry(jsonObject); } } return geometry; } @Override public String getName() { return "GeoJSON"; } private Point readPoint(JSONObject jsonObject) { Coordinate coordinate = getCoordinate((JSONArray) jsonObject.get("coordinates")); return new Point(coordinate, coordinate.getDimension(), srid); } private LineString readLineString(JSONObject jsonObject) { List<Coordinate>coordinates = getCoordinates((JSONArray) jsonObject.get("coordinates")); return new LineString(coordinates, coordinates.size() > 0 ? coordinates.get(0).getDimension() : Dimension.Two, srid); } private Polygon readPolygon(JSONObject jsonObject) { List<List<Coordinate>> coordinateSets = getCoordinateSets((JSONArray) jsonObject.get("coordinates")); if (coordinateSets.size() > 0) { LinearRing exteriorRing = getLinearRing(coordinateSets.get(0)); List<LinearRing> interiorRings = new ArrayList<>(); for (List<Coordinate> coordinates : coordinateSets.subList(1, coordinateSets.size())) { interiorRings.add(getLinearRing(coordinates)); } return new Polygon(exteriorRing, interiorRings, exteriorRing.getDimension(), srid); } else { return Polygon.createEmpty(); } } private MultiPoint readMultiPoint(JSONObject jsonObject) { List<Point> points = getPoints((JSONArray) jsonObject.get("coordinates")); return new MultiPoint(points, points.size() > 0 ? points.get(0).getDimension() : Dimension.Two, srid); } private MultiLineString readMultiLineString(JSONObject jsonObject) { JSONArray coordinates = (JSONArray) jsonObject.get("coordinates"); List<LineString> lineStrings = new ArrayList<>(); for(Object coords : coordinates.values()) { List<Coordinate> c = getCoordinates((JSONArray) coords); lineStrings.add(new LineString(c, c.size() > 0 ? c.get(0).getDimension() : Dimension.Two, srid)); } return new MultiLineString(lineStrings, lineStrings.size() > 0 ? lineStrings.get(0).getDimension() : Dimension.Two, srid); } private MultiPolygon readMultiPolygon(JSONObject jsonObject) { JSONArray coordinates = (JSONArray) jsonObject.get("coordinates"); List<Polygon> polygons = new ArrayList<>(); for(Object polygonsCoords : coordinates.values()) { List<List<Coordinate>> coordinateSets = getCoordinateSets((JSONArray) polygonsCoords); if (coordinateSets.size() > 0) { LinearRing exteriorRing = getLinearRing(coordinateSets.get(0)); List<LinearRing> interiorRings = new ArrayList<>(); for (List<Coordinate> coords : coordinateSets.subList(1, coordinateSets.size())) { interiorRings.add(getLinearRing(coords)); } polygons.add(new Polygon(exteriorRing, interiorRings, exteriorRing.getDimension(), srid)); } else { polygons.add(Polygon.createEmpty()); } } return new MultiPolygon(polygons, polygons.size() > 0 ? polygons.get(0).getDimension() : Dimension.Two, srid); } private GeometryCollection readGeometryCollection(JSONObject jsonObject) { JSONArray geometriesJsonArray = (JSONArray) jsonObject.get("geometries"); List<Geometry> geometries = new ArrayList<>(); for(Object geometryJsonObject : geometriesJsonArray.values()) { geometries.add(readGeometry((JSONObject) geometryJsonObject)); } return new GeometryCollection(geometries, geometries.size() > 0 ? geometries.get(0).getDimension() : Dimension.Two, srid); } private Geometry readGeometry(JSONObject jsonObject) { String type = (String) jsonObject.get("type"); Geometry geometry = null; if (type != null) { if (type.equalsIgnoreCase("point")) { geometry = readPoint(jsonObject); } else if (type.equalsIgnoreCase("LineString")) { geometry = readLineString(jsonObject); } else if (type.equalsIgnoreCase("Polygon")) { geometry = readPolygon(jsonObject); } else if (type.equalsIgnoreCase("MultiPoint")) { geometry = readMultiPoint(jsonObject); } else if (type.equalsIgnoreCase("MultiLineString")) { geometry = readMultiLineString(jsonObject); } else if (type.equalsIgnoreCase("MultiPolygon")) { geometry = readMultiPolygon(jsonObject); } else if (type.equalsIgnoreCase("GeometryCollection")) { geometry = readGeometryCollection(jsonObject); } } return geometry; } private LinearRing getLinearRing(List<Coordinate> coordinates) { return new LinearRing(coordinates, coordinates.size() > 0 ? coordinates.get(0).getDimension() : Dimension.Two, srid); } private Coordinate getCoordinate(JSONArray jsonArray) { if (jsonArray.values().size() > 2) { return Coordinate.create3D(getDouble(jsonArray.get(0)), getDouble(jsonArray.get(1)), getDouble(jsonArray.get(2))); } else if (jsonArray.values().size() == 2) { return Coordinate.create2D(getDouble(jsonArray.get(0)), getDouble(jsonArray.get(1))); } else { return Coordinate.createEmpty(); } } private Double getDouble(Object value) { if (value instanceof Double) { return (Double) value; } else if (value instanceof Integer) { return ((Integer) value).doubleValue(); } else if (value != null) { return Double.parseDouble(value.toString()); } else { return Double.NaN; } } private List<Coordinate> getCoordinates(JSONArray jsonArray) { List<Coordinate> coordinates = new ArrayList<>(); for(Object value : jsonArray.values()) { if (value instanceof JSONArray) { coordinates.add(getCoordinate((JSONArray)value)); } } return coordinates; } private List<Point> getPoints(JSONArray jsonArray) { List<Point> points = new ArrayList<>(); for(Object value : jsonArray.values()) { if (value instanceof JSONArray) { Coordinate coordinate = getCoordinate((JSONArray)value); points.add(new Point(coordinate, coordinate.getDimension())); } } return points; } private List<List<Coordinate>> getCoordinateSets(JSONArray jsonArray) { List<List<Coordinate>> coordinateSets = new ArrayList<>(); for(Object value : jsonArray.values()) { if (value instanceof JSONArray) { coordinateSets.add(getCoordinates((JSONArray)value)); } } return coordinateSets; } private JSON parse(String jsonStr) { JSONLexer lexer = new JSONLexer(new ANTLRInputStream(jsonStr)); JSONParser parser = new JSONParser(new CommonTokenStream(lexer)); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e); } }); final Stack<JSON> json = new Stack<>(); parser.addParseListener(new JSONBaseListener() { @Override public void enterObj(JSONParser.ObjContext ctx) { json.push(new JSONObject()); } @Override public void exitPair(JSONParser.PairContext ctx) { Object value = getValueFromValueContent(ctx.value()); JSONObject jsonObject = (JSONObject) json.peek(); jsonObject.values().put(removeDoubleQuotes(ctx.STRING().getText()), value); } @Override public void enterArray(JSONParser.ArrayContext ctx) { json.push(new JSONArray()); } @Override public void exitArray(JSONParser.ArrayContext ctx) { List<Object> values = new ArrayList<>(); for(JSONParser.ValueContext valueContext : ctx.value()) { Object value = getValueFromValueContent(valueContext); if (value instanceof JSON) { values.add(0, value); } else { values.add(value); } } JSONArray jsonArray = (JSONArray) json.peek(); jsonArray.values().addAll(values); } private String removeDoubleQuotes(String str) { if (str != null) { return str.replaceAll("\"", ""); } else { return null; } } private Number parseNumber(String value) { if (value.contains(".")) { return Double.parseDouble(value); } else { return Integer.parseInt(value); } } private Object getValueFromValueContent(JSONParser.ValueContext ctx) { if (ctx.obj() != null) { return json.pop(); } else if (ctx.array() != null) { return json.pop(); } else if (ctx.STRING() != null) { return removeDoubleQuotes(ctx.STRING().getText()); } else if (ctx.NUMBER() != null) { return parseNumber(removeDoubleQuotes(ctx.NUMBER().getText())); } else { return null; } } }); parser.json(); return json.pop(); } private static interface JSON { } private static class JSONObject implements JSON { private Map<String,Object> values = new LinkedHashMap<>(); public Map<String,Object> values() { return values; } public Object get(String key) { return values.get(key); } @Override public String toString() { return values.toString(); } } private static class JSONArray implements JSON { private List<Object> values = new ArrayList<>(); public List<Object> values() { return values; } public Object get(int index) { return values.get(index); } @Override public String toString() { return values.toString(); } } }
mit
Supamiu/ffxiv-teamcraft
apps/client/src/app/pipes/pipes/character-avatar.pipe.ts
516
import { Pipe, PipeTransform } from '@angular/core'; import { CharacterService } from '../../core/api/character.service'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Pipe({ name: 'characterAvatar' }) export class CharacterAvatarPipe implements PipeTransform { constructor(private service: CharacterService) { } transform(userId: string): Observable<string> { return this.service.getCharacter(userId).pipe( map(character => character.character.Avatar) ); } }
mit
myrkur/CR
app/cache/dev/twig/eb/56/d2266fb2b0eea1e46ff3c4a390c2597cbd04979be3c494ca51ce51a92abb.php
2450
<?php /* TwigBundle:Exception:exception.txt.twig */ class __TwigTemplate_eb56d2266fb2b0eea1e46ff3c4a390c2597cbd04979be3c494ca51ce51a92abb extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "[exception] "; echo (((((isset($context["status_code"]) ? $context["status_code"] : $this->getContext($context, "status_code")) . " | ") . (isset($context["status_text"]) ? $context["status_text"] : $this->getContext($context, "status_text"))) . " | ") . $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class", array())); echo " [message] "; // line 2 echo $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message", array()); echo " "; // line 3 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "toarray", array())); foreach ($context['_seq'] as $context["i"] => $context["e"]) { // line 4 echo "["; echo ($context["i"] + 1); echo "] "; echo $this->getAttribute($context["e"], "class", array()); echo ": "; echo $this->getAttribute($context["e"], "message", array()); echo " "; // line 5 $this->env->loadTemplate("TwigBundle:Exception:traces.txt.twig")->display(array("exception" => $context["e"])); // line 6 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['i'], $context['e'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } public function getTemplateName() { return "TwigBundle:Exception:exception.txt.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 6, 41 => 5, 32 => 4, 28 => 3, 24 => 2, 19 => 1,); } }
mit
gpawru/furry-framework-database
Tests/QueryBuilder/SQLite/SetUp.php
1983
<?php namespace Tests\QueryBuilder\SQLite; use Furry\Database; use Furry\Database\Connection\SQLite; trait SetUp { /** * connection setup */ public function setUp() { [$this->connection, $this->db] = $this->connect(); } /** * connecting to server using settings from dbconfig.json * returns connection & database class instance * or [null, null] * * @return array */ protected function connect() { try { $connection = new SQLite( __DIR__ . '/../test.db' ); $database = new Database($connection); } catch (\Exception $e) { return [null, null]; } return [$connection, $database]; } /** * test tables */ protected function setupTables() { /** @var \Furry\Database\Connection $connection */ $connection = $this->connection; $connection->query('DROP TABLE IF EXISTS `testTable`;'); $connection->query('CREATE TABLE IF NOT EXISTS `testTable` (' . '"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" TEXT, "value" INTEGER);'); $connection->query('DROP TABLE IF EXISTS `testTable2`;'); $connection->query('CREATE TABLE IF NOT EXISTS `testTable2` (' . '"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "test_id" INTEGER, "desc" TEXT);'); } /** * drop tables */ protected function dropTables() { /** @var \Furry\Database\Connection $connection */ $connection = $this->connection; $connection->query('DROP TABLE IF EXISTS `testTable`;'); $connection->query('DROP TABLE IF EXISTS `testTable2`;'); } /** * delete created tables */ public function tearDown() { $this->dropTables(); unset($this->db); if (is_file(__DIR__ . '/../test.db')) unlink(__DIR__ . '/../test.db'); } }
mit
jpspace/Android-NMEA-Parser
androidnmeaparser/src/main/java/kr/jpspace/androidnmeaparser/gps/GPGGA.java
180
package kr.jpspace.androidnmeaparser.gps; /** * Created by uiseok on 2016-08-25. */ public class GPGGA extends GGA { public GPGGA(String gga) { super(gga); } }
mit
evanrs/redux-namespace
test/create.spec.js
3340
import expect from 'expect'; import { createStore, combineReducers } from 'redux'; import { create } from '../src/create'; import { namespaceReducer } from '../src/reducer'; function createTest () { const store = createStore(combineReducers({ namespace: namespaceReducer })) return { store, ns: create('test', store) } } describe('create', () => { it('should assign values', () => { const { ns, store } = createTest() ns.assign('foo', 'bar') expect(store.getState().namespace.test.foo).toEqual('bar') }) it('should select values', () => { const { ns } = createTest() ns.assign('foo.bar', { baz: 'bop'}) expect(ns.select('foo.bar.baz')).toEqual('bop') }) it('should create cursors', () => { const { ns, store } = createTest() const cursor = ns.cursor('cursed') cursor.assign('foo.bar', { baz: 'bop'}) cursor.assign('some.array[0]', { and: [{ nested: 'value' }]}) cursor.assign('some.array[1]', { or: 'not' }) cursor.assign('some.array', []) expect(ns.select('cursed.foo.bar.baz')).toEqual('bop') expect(cursor.select('foo.bar.baz')).toEqual('bop') ns.assign('cursed.bar', 'baz') expect(cursor.select('bar')).toEqual('baz') }) it('should version along path', () => { const { ns } = createTest() expect(ns.version()).toEqual(0) ns.assign('foo', {}) expect(ns.version()).toEqual(1) expect(ns.version('foo')).toEqual(1) expect(ns.cursor('foo').version()).toEqual(1) ns.assign('foo.bar', true) expect(ns.version()).toEqual(2) expect(ns.version('foo')).toEqual(2) expect(ns.version('foo.bar')).toEqual(1) expect(ns.cursor('foo').version()).toEqual(2) expect(ns.cursor('foo').version('bar')).toEqual(1) ns.assign('foo', {}) expect(ns.version()).toEqual(3) expect(ns.version('foo')).toEqual(3) expect(ns.version('foo.bar')).toEqual(0) ns.assign('foo', { bar: true }); expect(ns.version('foo')).toEqual(4) expect(ns.version('foo.bar')).toEqual(0) }) it('should be touched along path', () => { const { ns } = createTest() expect(ns.touched()).toEqual(0) ns.assign('foo.bar', true) expect(ns.touched()).toEqual(1) expect(ns.touched('foo')).toEqual(1) expect(ns.touched('foo.bar')).toEqual(1) ns.assign('foo', {}) expect(ns.touched('foo')).toEqual(2) expect(ns.touched('foo.bar')).toEqual(0) }) it('should reset', () => { const { ns, store } = createTest(); ns.assign('foo', {}); ns.assign('foo.bar', {}); ns.reset('foo'); expect(ns.version('foo')).toEqual(0); ns.assign('foo', {}); expect(ns.version('foo')).toEqual(1); expect(ns.touched('foo')).toEqual(1); }) it('should set defaults', () => { const { ns, store } = createTest(); ns.defaults('foo', {}); expect(ns.touched('foo')).toEqual(0); expect(ns.version('foo')).toEqual(1); ns.defaults('foo.bar', {}); expect(ns.touched('foo')).toEqual(0); expect(ns.version('foo')).toEqual(2); expect(ns.touched('foo.bar')).toEqual(0); expect(ns.version('foo.bar')).toEqual(1); }) it('should map over an object', () => { const { ns, store } = createTest(); ns.assign({ 'bop': 1, 'baz': 2 }); expect(ns.version('bop')).toEqual(1) expect(ns.touched('baz')).toEqual(1) }) })
mit
squared9/Robotics
Follow_Me-Semantic_Segmentation/code/preprocess_ims.py
5719
# Copyright (c) 2017, Udacity # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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. # # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of the FreeBSD Project # Author: Devin Anzelmo import glob import os import shutil import sys import numpy as np from scipy import misc def make_dir_if_not_exist(path): if not os.path.exists(path): os.makedirs(path) def get_mask_files(image_files): is_cam2 = lambda x: x.find('cam2_') != -1 is_cam3 = lambda x: x.find('cam3_') != -1 is_cam4 = lambda x: x.find('cam4_') != -1 cam2 = sorted(list(filter(is_cam2, image_files))) cam3 = sorted(list(filter(is_cam3, image_files))) cam4 = sorted(list(filter(is_cam4, image_files))) return cam2, cam3, cam4 def move_labels(input_folder, output_folder, fold_id): files = glob.glob(os.path.join(input_folder, '*', '*.png')) output_folder = os.path.join(output_folder, 'masks') make_dir_if_not_exist(output_folder) cam2, cam3, cam4 = get_mask_files(files) for e,i in enumerate(cam2): fname_parts = i.split(os.sep) # Thanks @Nitish for these fixes:) cam2_base = str(fold_id) + '_' + fname_parts[-3] +'_' + fname_parts[-1] fname_parts = cam3[e].split(os.sep) cam3_base = str(fold_id) + '_' + fname_parts[-3] +'_' + fname_parts[-1] fname_parts = cam4[e].split(os.sep) cam4_base = str(fold_id) + '_' + fname_parts[-3] +'_' + fname_parts[-1] shutil.copy(i, os.path.join(output_folder,cam2_base)) shutil.copy(cam3[e], os.path.join(output_folder,cam3_base)) shutil.copy(cam4[e], os.path.join(output_folder,cam4_base)) def move_png_to_jpeg(input_folder, output_folder, fold_id): files = glob.glob(os.path.join(input_folder, '*', '*.png')) is_cam1 = lambda x: x.find('cam1_') != -1 cam1_files = sorted(list(filter(is_cam1, files))) output_folder = os.path.join(output_folder, 'images') make_dir_if_not_exist(output_folder) for i in cam1_files: cam1 = misc.imread(i) fname_parts = i.split(os.sep) cam1_base = str(fold_id) + '_' +fname_parts[-3] + '_' + fname_parts[-1].split('.')[0] + '.jpeg' misc.imsave(os.path.join(output_folder, cam1_base), cam1, format='jpeg') def combine_masks(processed_folder): processed_mask_folder = os.path.join(processed_folder, 'masks') files = glob.glob(os.path.join(processed_mask_folder, '*.png')) cam2, cam3, cam4 = get_mask_files(files) for e,i in enumerate(cam2): im2 = misc.imread(i)[:,:,0] im3 = misc.imread(cam3[e])[:,:,0] im4 = misc.imread(cam4[e])[:,:,0] stacked = np.stack((im4-1, im2, im3), 2) argmin = np.argmin(stacked, axis=-1) im = np.stack((argmin==0, argmin==1, argmin==2), 2) base_name = os.path.basename(i) ind = base_name.find('cam') new_fname = base_name[:ind] + 'mask'+ base_name[ind+4:] dir_base = str(os.sep).join(i.split(str(os.sep))[:-1]) misc.imsave(os.path.join(dir_base, new_fname), im) os.remove(i) os.remove(cam3[e]) os.remove(cam4[e]) def get_im_data(base_path): folds = glob.glob(os.path.join(base_path, '*', '*')) indicator_dict = dict() is_val = lambda x: x.find('validation') != -1 for f in folds: files = glob.glob(os.path.join(f, '*','*.png')) if len(files) == 0: indicator_dict[f] = (False, is_val(f)) else: indicator_dict[f] = (True, is_val(f)) return indicator_dict if __name__ == '__main__': raw_data = os.path.join('..', 'data', 'raw_sim_data') proc_data = os.path.join('..', 'data', 'processed_sim_data') indicator_dict = get_im_data(raw_data) out_val_dir = os.path.join(proc_data, 'validation') out_train_dir = os.path.join(proc_data, 'train') for e, i in enumerate(indicator_dict.items()): # no data in the folder so skip it if not i[1][0]: continue # validation if i[1][1]: move_png_to_jpeg(i[0], out_val_dir, e) move_labels(i[0], out_val_dir, e) # train else: move_png_to_jpeg(i[0], out_train_dir, e) move_labels(i[0], out_train_dir, e) combine_masks(out_val_dir) combine_masks(out_train_dir)
mit
marksize/lowered
src/rpcrawtransaction.cpp
20294
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "bitcoinrpc.h" #include "txdb.h" #include "init.h" #include "main.h" #include "net.h" #include "wallet.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (boost::int64_t)tx.nTime)); entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (boost::int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, false); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid babesandnerd address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64_t nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid babesandnerd address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript <hex string>\n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node CTxDB txdb("r"); if (!tx.AcceptToMemoryPool(txdb)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); SyncWithWallets(tx, NULL, true); } RelayTransaction(tx, hashTx); return hashTx.GetHex(); }
mit
Aldarov/StudentEmployment
Server/Controllers/AccountController.cs
3745
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using Microsoft.AspNetCore.Mvc; using Auth; using Server.Models; using Microsoft.EntityFrameworkCore; using System.Net.Http; using System.Xml.Linq; using System.Threading.Tasks; using System.IO; using Server.Models.University; namespace Server.Controllers { public class AccountController : Controller { private UniversityContext db; private IJwt jwt; public AccountController(UniversityContext context, IJwt token) { jwt = token; db = context; } private ClaimsIdentity GetClaimsIdentity(string employmentId) { var claims = new List<Claim> { new Claim("EmploymentId", employmentId) }; ClaimsIdentity identity = new ClaimsIdentity(claims, "Token"); return identity; } [HttpPost("api/login")] public async Task<ActionResult> Login([FromBody]AuthProps props) { string sessionId = props != null ? props.SessionId : null; if (sessionId == null) { return BadRequest("Необходимо авторизоваться"); } Http­Client client = new Http­Client (); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml")); var response = client.GetAsync("http://my.bsu.ru/auth.php?id=" + sessionId).Result; if (response.IsSuccessStatusCode) { var stringAuth = await response.Content.ReadAsStringAsync(); XDocument xdoc = XDocument.Parse(stringAuth); XElement res = xdoc.Descendants("result").FirstOrDefault(); if (res != null) { string state = res.Attributes().Where(q => q.Name == "state").Select(q => q.Value).FirstOrDefault(); if (state == "1") { var check = db.Placements .FromSql<Placement>("select * from dbo.pg_access_to_specialities({0})", props.EmploymentId) .Any(); if (check) { var identity = GetClaimsIdentity(props.EmploymentId); return Ok(jwt.GetToken(identity)); } else { return BadRequest("Ваше подразделение не добавлено в список разрешенных, обратитесь в ЦИТиДО"); } } else return StatusCode(403, Json("Access denied")); } } return Unauthorized(); } [HttpPost("api/token")] public IActionResult RefreshToken([FromBody]Token token) { var refresh_token = token.refresh_token; if (refresh_token == null) { return BadRequest(); } try { ClaimsPrincipal principal = jwt.DecodeToken(refresh_token); string employmentId = principal.FindFirst("EmploymentId").Value; var identity = GetClaimsIdentity(employmentId); Token newToken = jwt.GetToken(identity); return Ok(newToken); } catch { return StatusCode(403, Json("Invalid refresh token")); } } } }
mit
AndrewKeig/react-speech
webpack.build.config.js
703
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: './src/speech', output: { path: path.join(__dirname, './dist'), library: 'ReactSpeech', filename: 'react-speech.min.js', libraryTarget: 'umd' }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, externals: [ { react: { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } } ], plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }) ] };
mit
HESGE/twitter-harvest
lib/twitter-harvest.js
5001
/*eslint no-console: 0*/ var log = require('./mylog').log(); var cfg = require('./cfg').cfg(); var fs = require('fs'); //var Twitter = require('Twitter'); var Twit = require('twit'); var FsInterface = require('./fs-interface'); var nodemailer = require('nodemailer'); var Validator = require('jsonschema').Validator; var schemaAgent = require('../schema/schema-agent.json'); var schemaCfg = require('../schema/schema-cfg.json'); var fsInterface = new FsInterface(cfg.data_dir); //init fs output var v = new Validator(); //init json schema validator var agents = []; // list of agents var transporter; // mail transporter for alert system log.info('start twitter-harvest log system'); // alertMail to send a mail alert following the configuration var alertMail = function (subject, text) { if (cfg.mail_alert) { transporter.sendMail({ from : cfg.mail_from, to : cfg.mail_to, subject : subject, text : text }, function (error, info){ if (error) { log.error(error); } else { log.info('Message sent: ' + info.response); } }); } }; // launch a twitter agent var runAgent = function (agent, nbTweets) { if (agent.enable) { log.info('start twitter agent :' + agent.name); var T = new Twit({ consumer_key : agent.consumer_key, consumer_secret : agent.consumer_secret, access_token : agent.access_token_key, access_token_secret : agent.access_token_secret }); if (agent.type_api === 'stream') { var stream = T.stream('statuses/' + agent.stream, agent.filter); log.info('start listen Stream'); stream.on('connect', function () { log.info('twitter connect '); alertMail('alert mail started for get-sample for twitter', 'connect'); }); stream.on('disconnect', function (disconnectMessage) { log.error('twitter disconnect code: ' + disconnectMessage.code); log.error('twitter disconnect reason: ' + disconnectMessage.reason); alertMail('alert mail disconnect ', disconnectMessage.reason); }); stream.on('limit', function (limitMessage) { log.info('twitter limit track: ' + limitMessage.track); alertMail('alert mail for get-sample:', 'twitter limit track: ' + limitMessage.track); }); stream.on('tweet', function (tweet) { //console.log(tweet); log.info(agent.name + ': ' + 'tweet received, ' + tweet.text + ' at' + tweet.created_at + ' for ' + agent.name); //console.log(tweet); //var tweetJSON = JSON.parse(tweet); if (cfg.fs_out) { fsInterface.write(tweet, cfg.todo_out, function (){}); } if (cfg.std_out) { console.log(JSON.stringify(tweet)); } if (nbTweets !== undefined && nbTweets-- < 1) { stream.destroy(); } }); stream.on('end', function () { log.info(agent.name + ': ' + 'end of twitter stream'); }); stream.on('error', function (error) { log.fatal(agent.name + ': ' + error); if (cfg.mail_alert) { alertMail(agent.name, 'ERROR=' + error); } throw error; }); // listenStream(stream, agent, nbTweets); } else {// else if (agent.type_api === 'query') { log.info('query agent'); } } }; // init, read the cfg and the list of twitter agents on several JSON fs var init = function (nbTweets) { //check if cfg is a valide json from a schema var r1 = v.validate(cfg, schemaCfg); if (r1.errors.length > 0) { throw new Error(r1.errors[0].stack + ' in cfg.json'); } // init of the mailer for alerting if (cfg.mail_alert) { transporter = nodemailer.createTransport({ service: cfg.mail_service, auth: { user: cfg.mail_auth_user, pass: cfg.mail_auth_path } }); // just to send an email at the startup alertMail('alert mail started for twitter-harvest', 'no error'); } // read the agents directory var dir = cfg.agents_dir; fs.readdir(dir, function (err1, files){ if (err1) { throw err1; } // loop the files files.forEach(function (file){ fs.readFile(dir + file, 'utf-8', function (err2, json){ if (err2) { throw err2; } // check if the json of agent is valide var r2 = v.validate(JSON.parse(json), schemaAgent); if (r2.errors.length > 0) { throw new Error(r2.errors[0].stack + ' in ' + file); } var agent = JSON.parse(json); if (agent.enable) { agents.push(agent); } // start agent one by one runAgent(agent, nbTweets); }); }); }); }; /******************* main *************************/ module.exports.init = init; module.exports.cfg = function () { return cfg; }; module.exports.agents = function () { return agents; };
mit
Senither/AvaIre
app/bot/commands/utility/LeaderboardCommand.js
4833
/** @ignore */ const Command = require('./../Command'); /** @ignore */ const UserTransformer = require('./../../../database/transformers/UserTransformer'); class LeaderboardCommand extends Command { /** * Sets up the command by providing the prefix, command trigger, any * aliases the command might have and additional options that * might be usfull for the abstract command class. */ constructor() { super('leaderboard', ['top'], { allowDM: false, middleware: [ 'throttle.user:1,5' ] }); } /** * Executes the given command. * * @param {IUser} sender The Discordie user object that ran the command. * @param {IMessage} message The Discordie message object that triggered the command. * @param {Array} args The arguments that was parsed to the command. * @return {mixed} */ onCommand(sender, message, args) { let guild = app.cache.get(`database.${app.getGuildIdFrom(message)}`, null, 'memory'); if (guild === null || guild.get('levels', 0) === 0) { return app.envoyer.sendWarn(message, 'This command requires the `Levels & Experience` feature to be enabled for the server, you can ask a server admin if they want to enable it with `.level`'); } return this.loadTop100From(message).then(users => { let pageNumber = 1; if (args.length > 0) { pageNumber = parseInt(args[0], 10); } if (isNaN(pageNumber) || pageNumber < 1) { pageNumber = 1; } let pages = Math.ceil(users.length / 10); if (pageNumber > pages) { pageNumber = pages; } let formattedUsers = []; let start = 10 * (pageNumber - 1); for (let i = start; i < start + 10; i++) { if (users.length <= i) { break; } let user = users[i]; let xp = user.get('experience'); let username = user.get('username'); if (username.indexOf('\\u') > -1) { let guildUser = message.guild.members.find(u => { return u.id === user.get('user_id'); }); if (!(guildUser === undefined || guildUser === null)) { username = guildUser.username; } } formattedUsers.push(`\`${i + 1}\` **${username}** is level **${app.bot.features.level.getLevelFromXp(xp)}** with **${xp - 100}** xp.`); } return app.envoyer.sendEmbededMessage(message, { color: 0xE91E63, title: `${message.guild.name} Leaderboard`, url: `https://avairebot.com/leaderboard/${app.getGuildIdFrom(message)}`, description: formattedUsers.join('\n'), footer: { text: `Showing page ${pageNumber} out of ${pages} pages` } }); }); } /** * Loads the top 100 users from cache if they exists, otherwise query * the database to get the top 100 users for the current server. * * @param {IMessage} message The Discordie message object that triggered the command. * @return {Promise} */ loadTop100From(message) { let cacheToken = `database-xp-leaderbord.${app.getGuildIdFrom(message)}`; return new Promise((resolve, reject) => { if (app.cache.has(cacheToken)) { let users = app.cache.get(cacheToken); let transformedUsers = []; for (let i in users) { transformedUsers.push(new UserTransformer(users[i])); } return resolve(transformedUsers); } app.bot.statistics.databaseQueries++; return app.database.getClient() .table(app.constants.USER_EXPERIENCE_TABLE_NAME) .where('guild_id', app.getGuildIdFrom(message)) .orderBy('experience', 'desc') .limit(100) .then(users => { let transformedUsers = []; for (let i in users) { transformedUsers.push(new UserTransformer(users[i])); } app.cache.put(cacheToken, users, 120); return resolve(transformedUsers); }); }); } } module.exports = LeaderboardCommand;
mit
andrewswan/tally-ho
src/test/java/tallyho/model/tile/DuckTest.java
2047
/* * Created on 21/08/2004 */ package tallyho.model.tile; import tallyho.model.Team; import junit.framework.TestCase; /** * Tests the duck model */ public class DuckTest extends TestCase { // Fixture private Bear bear; private Duck duck; private Fox fox; private Hunter hunter; private Lumberjack lumberjack; private Pheasant pheasant; private Tree tree; /* * @see TestCase#setUp() */ protected void setUp() { bear = new Bear(); duck = new Duck(); fox = new Fox(); hunter = new Hunter(); lumberjack = new Lumberjack(); pheasant = new Pheasant(); tree = new Tree(); } /** * Tests that a duck has the correct range */ public void testGetRange() { assertEquals(Integer.MAX_VALUE, duck.getRange()); } /** * Makes sure a duck can capture the correct tiles */ public void testCanCapture() { assertFalse("Shouldn't be able to capture a null Tile", duck.canCapture(null)); assertFalse("Shouldn't be able to capture a bear", duck.canCapture(bear)); assertFalse("Shouldn't be able to capture a duck", duck.canCapture(new Duck())); assertFalse("Shouldn't be able to capture a fox", duck.canCapture(fox)); assertFalse("Shouldn't be able to capture a hunter", duck.canCapture(hunter)); assertFalse("Shouldn't be able to capture a lumberjack", duck.canCapture(lumberjack)); assertFalse("Shouldn't be able to capture a pheasant", duck.canCapture(pheasant)); assertFalse("Shouldn't be able to capture a tree", duck.canCapture(tree)); } /** * Tests that ducks have the correct name */ public void testGetName() { assertEquals("Duck", duck.getName()); } /** * Tests that ducks report the correct prey types */ public void testGetPrey() { Class[] prey = duck.getPrey(); assertNotNull("Prey array shouldn't be null", prey); assertEquals(0, prey.length); } /** * Tests that ducks are on the right team */ public void testGetTeam() { assertEquals(Team.NEUTRAL, duck.getTeam()); } }
mit
hovsepm/azure-libraries-for-net
src/ResourceManagement/AppService/Generated/Models/DnsVerificationTestResult.cs
2054
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.AppService.Fluent.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for DnsVerificationTestResult. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum DnsVerificationTestResult { [EnumMember(Value = "Passed")] Passed, [EnumMember(Value = "Failed")] Failed, [EnumMember(Value = "Skipped")] Skipped } internal static class DnsVerificationTestResultEnumExtension { internal static string ToSerializedValue(this DnsVerificationTestResult? value) { return value == null ? null : ((DnsVerificationTestResult)value).ToSerializedValue(); } internal static string ToSerializedValue(this DnsVerificationTestResult value) { switch( value ) { case DnsVerificationTestResult.Passed: return "Passed"; case DnsVerificationTestResult.Failed: return "Failed"; case DnsVerificationTestResult.Skipped: return "Skipped"; } return null; } internal static DnsVerificationTestResult? ParseDnsVerificationTestResult(this string value) { switch( value ) { case "Passed": return DnsVerificationTestResult.Passed; case "Failed": return DnsVerificationTestResult.Failed; case "Skipped": return DnsVerificationTestResult.Skipped; } return null; } } }
mit
frickiericker/learn-go
03-goroutine/query.go
866
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) func QueryStory(storyId uint64) (string, error) { url := fmt.Sprintf("https://hacker-news.firebaseio.com/v0/item/%d.json", storyId) var storyData map[string]interface{} err := RequestJson(url, &storyData) title := storyData["title"].(string) return title, err } func QueryNewStoryIds() ([]uint64, error) { url := "https://hacker-news.firebaseio.com/v0/newstories.json" var storyIds []uint64 err := RequestJson(url, &storyIds) return storyIds, err } func RequestJson(url string, data interface{}) error { resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { return fmt.Errorf("HTTP request failed") } body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } return json.Unmarshal(body, data) }
mit
kris1226/clymer-metal-crafts
index.js
559
import 'babel-core/polyfill'; import React from 'react'; import { render } from 'react-dom'; import Root from './containers/Root'; import ReactReduxRouterRoot from './containers/ReactReduxRouterRoot'; //import configureStore from './store/configureStore'; import configureStore from './store/reactReduxRouterConfigureStore'; import './public/css/styleBlue.css'; import './public/css/bootstrap.css'; import './public/js/bootstrap.min.js'; const store = configureStore(); render( <ReactReduxRouterRoot store={store} />, document.getElementById('root') );
mit
anurag-ks/eden
modules/templates/SAMBRO/controllers.py
35574
# -*- coding: utf-8 -*- from datetime import datetime, timedelta try: import json # try stdlib (Python 2.6) except ImportError: try: import simplejson as json # try external module except: import gluon.contrib.simplejson as json # fallback to pure-Python module from gluon import current from gluon.html import * from gluon.storage import Storage from s3 import FS, S3CustomController, S3FilterForm, S3DateFilter, S3LocationFilter, S3OptionsFilter THEME = "SAMBRO" # ============================================================================= class index(S3CustomController): """ Custom home page for the Public """ # ------------------------------------------------------------------------- def __call__(self): """ Main entry point, configuration """ logged_in = current.auth.s3_logged_in() if logged_in: fn = "alert" else: fn = "public" T = current.T s3db = current.s3db request = current.request output = {} # Map ftable = s3db.gis_layer_feature query = (ftable.controller == "cap") & \ (ftable.function == fn) layer = current.db(query).select(ftable.layer_id, limitby=(0, 1) ).first() try: layer_id = layer.layer_id except: from s3 import s3_debug s3_debug("Cannot find Layer for Map") layer_id = None feature_resources = [{"name" : T("Alerts"), "id" : "search_results", "layer_id" : layer_id, "tablename" : "cap_alert", "url" : URL(c="cap", f=fn, extension="geojson"), # We activate in callback after ensuring URL is updated for current filter status "active" : False, }] _map = current.gis.show_map(callback='''S3.search.s3map()''', catalogue_layers=True, collapsed=True, feature_resources=feature_resources, save=False, search=True, toolbar=True, ) output["_map"] = _map # Filterable List of Alerts # - most recent first resource = s3db.resource("cap_alert") # Don't show Templates resource.add_filter(FS("is_template") == False) if not logged_in: # Only show Public Alerts resource.add_filter(FS("scope") == "Public") # Only show Alerts which haven't expired resource.add_filter(FS("info.expires") >= request.utcnow) list_id = "cap_alert_datalist" list_fields = ["msg_type", "info.headline", "area.name", #"info.description", "info.sender_name", "info.priority", "status", "scope", "info.event_type_id", "info.severity", "info.certainty", "info.urgency", "sent", ] # Order with most recent Alert first orderby = "cap_info.expires desc" datalist, numrows, ids = resource.datalist(fields = list_fields, #start = None, limit = None, list_id = list_id, orderby = orderby, layout = s3db.cap_alert_list_layout ) ajax_url = URL(c="cap", f=fn, args="datalist.dl", vars={"list_id": list_id}) output[list_id] = datalist.html(ajaxurl = ajax_url, pagesize = None, ) # @ToDo: Options are currently built from the full-set rather than the filtered set filter_widgets = [#S3LocationFilter("location.location_id", # label=T("Location"), # levels=("L0",), # widget="multiselect", # ), S3OptionsFilter("info.priority", #label=T("Priority"), ), S3OptionsFilter("info.event_type_id", #label=T("Event Type"), ), S3OptionsFilter("scope", #label=T("Scope"), ), S3DateFilter("info.expires", label = "", #label=T("Expiry Date"), hide_time=True, ), ] filter_form = S3FilterForm(filter_widgets, ajax=True, submit=True, url=ajax_url, ) output["alert_filter_form"] = filter_form.html(resource, request.get_vars, list_id) # Filterable News Feed # - most recent first resource = s3db.resource("cms_post") # Only show News posts (differentiate from e.g. online user guide) resource.add_filter(FS("series_id$name") == "News") list_id = "cms_post_datalist" list_fields = [#"series_id", "location_id", "date", "body", #"created_by", #"created_by$organisation_id", #"document.file", ] # Order with most recent Post first orderby = "cms_post.date desc" datalist, numrows, ids = resource.datalist(fields = list_fields, #start = None, limit = 5, list_id = list_id, orderby = orderby, # @ToDo: Custom layout with more button to expand content block layout = s3db.cms_post_list_layout ) ajax_url = URL(c="cms", f="post", args="datalist.dl", vars={"list_id": list_id}) output[list_id] = datalist.html(ajaxurl = ajax_url, pagesize = 5 ) # Truncate body #from s3 import s3_trunk8 #s3_trunk8(lines=8) #filter_widgets = [#S3LocationFilter("location_id", # # label="", # # levels=("L0",), # # widget="multiselect", # # ), # # @ToDo: Source (Series? Tag?) # #S3OptionsFilter(), # ] #filter_form = S3FilterForm(filter_widgets, # ajax=True, # submit=True, # url=ajax_url, # ) #output["news_filter_form"] = filter_form.html(resource, request.get_vars, list_id) # Title and view output["title"] = current.deployment_settings.get_system_name() self._view(THEME, "index.html") s3 = current.response.s3 # Custom CSS s3.stylesheets.append("../themes/SAMBRO/style.css") # Custom JS s3.scripts.append("/%s/static/themes/SAMBRO/js/homepage.js" % request.application) return output # ============================================================================= class subscriptions(S3CustomController): """ Custom page to manage subscriptions """ # ------------------------------------------------------------------------- def __call__(self): """ Main entry point, configuration """ T = current.T # Must be logged in auth = current.auth if not auth.s3_logged_in(): auth.permission.fail() # Available resources resources = [dict(resource="cap_alert", url="cap/alert", label=T("Updates")), ] # Filter widgets # @note: subscription manager has no resource context, so # must configure fixed options or lookup resources # for filter widgets which need it. filters = [S3OptionsFilter("event_type_id", label = T("Event Type"), options=self._options("event_type_id"), widget="multiselect", resource = "cap_info", _name = "event-filter", ), S3OptionsFilter("priority", label = T("Priority"), options=self._options("priority"), widget="multiselect", resource = "cap_info", _name = "priority-filter", ), S3LocationFilter("location_id", label = T("Location(s)"), resource = "cap_area_location", options = self._options("location_id"), _name = "location-filter", ), S3OptionsFilter("language", label = T("Language"), options = current.deployment_settings.get_cap_languages(), represent = "%(name)s", resource = "cap_info", _name = "language-filter", ), ] # Title and view title = T("Subscriptions") self._view(THEME, "subscriptions.html") # Form form = self._manage_subscriptions(resources, filters) return dict(title = title, form = form, ) # ------------------------------------------------------------------------- @staticmethod def _options(fieldname): """ Lookup the full set of options for a Filter Widget - for Subscriptions we don't want to see just the options available in current data """ if fieldname == "event_type_id": T = current.T etable = current.s3db.event_event_type rows = current.db(etable.deleted == False).select(etable.id, etable.name) options = {} for row in rows: options[row.id] = T(row.name) elif fieldname == "priority": T = current.T wptable = current.s3db.cap_warning_priority rows = current.db(wptable.deleted == False).select(wptable.id, wptable.name) options = {} for row in rows: options[row.id] = T(row.name) elif fieldname == "location_id": ltable = current.s3db.gis_location query = (ltable.deleted == False) # IDs converted inside widget's _options() function rows = current.db(query).select(ltable.id) options = [row.id for row in rows] return options # ------------------------------------------------------------------------- def _manage_subscriptions(self, resources, filters): """ Custom form to manage subscriptions @param resources: available resources config @param filters: filter widgets """ # Uses Default Eden formstyle from s3theme import formstyle_foundation as formstyle from gluon.validators import IS_IN_SET from s3.s3widgets import S3GroupedOptionsWidget, S3MultiSelectWidget from s3layouts import S3PopupLink # L10n T = current.T db = current.db s3db = current.s3db response = current.response labels = Storage( #RESOURCES = T("Subscribe To"), #NOTIFY_ON = T("Notify On"), #FREQUENCY = T("Frequency"), NOTIFY_BY = T("Notify By"), #MORE = T("More Options"), #LESS = T("Less Options"), ) messages = Storage( ERROR = T("Error: could not update notification settings"), SUCCESS = T("Notification settings updated"), ) # Get current subscription settings resp. form defaults subscription = self._get_subscription() # Initialize form form = FORM(_id="subscription-form", hidden={"subscription-filters": ""}) # Filters filter_form = S3FilterForm(filters, clear=False) fieldset = FIELDSET(filter_form.fields(None, subscription["get_vars"]), _id="subscription-filter-form") form.append(fieldset) # Notification options rows = [] stable = s3db.pr_subscription selector = S3GroupedOptionsWidget(cols=1) # Deactivated trigger selector #rows.append(("trigger_selector__row", # "%s:" % labels.NOTIFY_ON, # selector(stable.notify_on, # subscription["notify_on"], # _id="trigger_selector"), # "")) #switch = S3GroupedOptionsWidget(cols=1, multiple=False, sort=False) # Deactivated: frequency selector #rows.append(("frequency_selector__row", # "%s:" % labels.FREQUENCY, # switch(stable.frequency, # subscription["frequency"], # _id="frequency_selector"), # "")) methods = [("EMAIL", T("Email")), ("SMS", T("SMS")), ("Sync", T("FTP")), ] method_options = Storage(name = "method", requires = IS_IN_SET(methods)) rows.append(("method_selector__row", "%s:" % labels.NOTIFY_BY, selector(method_options, subscription["method"], _id="method_selector"), "")) # Sync Row properties = subscription["comments"] if properties: properties = json.loads(properties) synctable = s3db.sync_repository query = (synctable.apitype == "ftp") & \ (synctable.deleted != True) & \ (synctable.owned_by_user == current.auth.user.id) ftp_rows = db(query).select(synctable.id, synctable.name, orderby = synctable.id) multiselect = S3MultiSelectWidget(header = False, multiple = False, create = {"c": "sync", "f": "repository", "label": "Create Repository", }, ) if ftp_rows: if properties: user_repository_id = properties["repository_id"] else: user_repository_id = ftp_rows.first().id if current.auth.s3_has_permission("update", "sync_repository", record_id = user_repository_id): repository_comment = S3PopupLink(c = "sync", f = "repository", m = "update", args = [user_repository_id], title = T("Update Repository"), tooltip = T("You can edit your FTP repository here"), ) field = s3db.sync_task.repository_id ftp_ids = [(r.id, T(r.name)) for r in ftp_rows] field.requires = IS_IN_SET(ftp_ids) rows.append(("sync_task_repository_id__row", "", multiselect(field, user_repository_id, _id="sync_task_repository_id"), repository_comment)) else: if current.auth.s3_has_permission("create", "sync_repository"): repository_comment = S3PopupLink(c = "sync", f = "repository", title = T("Create Repository"), tooltip = T("Click on the link to begin creating your FTP repository"), ) rows.append(("sync_task_repository_id__row", "", "", repository_comment)) parent = FIELDSET() for row in rows: parent.append(formstyle(form, [row])) # Deactivated Toggle #parent.insert(0, # DIV(SPAN([I(_class="icon-reorder"), labels.MORE], # _class="toggle-text", # _style="display:none"), # SPAN([I(_class="icon-reorder"), labels.LESS], # _class="toggle-text"), # _id="notification-options", # _class="control-group")) form.append(parent) # Submit button submit_fieldset = FIELDSET(DIV("", INPUT(_type="submit", _value="Update Settings"), _id = "submit__row")) form.append(submit_fieldset) # Script (to extract filters on submit and toggle options visibility) script = URL(c="static", f="scripts", args=["S3", "s3.subscriptions.js"]) response.s3.scripts.append(script) # Script to show/hide the ftp repo row for FTP checkbox on/off repository_script = ''' if($('#method_selector option[value=Sync]').is(':selected')){ $('#sync_task_repository_id__row').show(); } else { $('#sync_task_repository_id__row').hide(); } $('#method_selector').change(function(){ if($(this).val().indexOf('Sync') != -1){ $('#sync_task_repository_id__row').show(); } else { $('#sync_task_repository_id__row').hide(); } }) ''' response.s3.jquery_ready.append(repository_script) # Accept form if form.accepts(current.request.post_vars, current.session, formname="subscription", keepvalues=True): formvars = form.vars listify = lambda x: None if not x else x if type(x) is list else [x] # Fixed resource selection: subscription["subscribe"] = [resources[0]] # Alternatively, with resource selector: #subscribe = listify(formvars.resources) #if subscribe: #subscription["subscribe"] = \ #[r for idx, r in enumerate(resources) #if str(idx) in subscribe] subscription["filters"] = form.request_vars \ .get("subscription-filters", None) # Fixed method subscription["method"] = formvars.method # Fixed Notify On and Frequency subscription["notify_on"] = ["new"] subscription["frequency"] = "immediately" # Alternatively, with notify and frequency selector #subscription["notify_on"] = listify(formvars.notify_on #subscription["frequency"] = formvars.frequency success_subscription = self._update_subscription(subscription) if "Sync" in subscription["method"] and formvars.repository_id: properties = self._update_sync(subscription["subscribe"][0]['resource'], subscription.get("filters"), int(formvars.repository_id), properties) properties = json.dumps(properties) db(stable.pe_id == current.auth.user.pe_id).update(comments=properties) else: self._remove_sync(properties) db(stable.pe_id == current.auth.user.pe_id).update(comments=None) if success_subscription: response.confirmation = messages.SUCCESS else: response.error = messages.ERROR return form # ------------------------------------------------------------------------- def _get_subscription(self): """ Get current subscription settings """ db = current.db s3db = current.s3db pe_id = current.auth.user.pe_id stable = s3db.pr_subscription ftable = s3db.pr_filter query = (stable.pe_id == pe_id) & \ (stable.deleted != True) left = ftable.on(ftable.id == stable.filter_id) row = db(query).select(stable.id, #stable.notify_on, #stable.frequency, stable.method, #stable.repository_id, #stable.representation, stable.comments, ftable.id, ftable.query, left=left, limitby=(0, 1)).first() output = {"pe_id": pe_id} get_vars = {} if row: # Existing settings s = getattr(row, "pr_subscription") f = getattr(row, "pr_filter") rtable = s3db.pr_subscription_resource query = (rtable.subscription_id == s.id) & \ (rtable.deleted != True) rows = db(query).select(rtable.id, rtable.resource, rtable.url, rtable.last_check_time, rtable.next_check_time) if f.query: filters = json.loads(f.query) for k, v in filters: if v is None: continue if k in get_vars: if type(get_vars[k]) is list: get_vars[k].append(v) else: get_vars[k] = [get_vars[k], v] else: get_vars[k] = v output.update({"id": s.id, "filter_id": f.id, "get_vars" : get_vars, "resources": rows, "notify_on": ["new"],#s.notify_on "frequency": "immediately",#s.frequency "method": s.method, "comments": s.comments, }) else: # Form defaults output.update({"id": None, "filter_id": None, "get_vars" : get_vars, "resources": None, "notify_on": ["new"],#stable.notify_on.default, "frequency": "immediately",#stable.frequency.default, "method": stable.method.default, "comments": None, }) return output # ------------------------------------------------------------------------- def _update_subscription(self, subscription): """ Update subscription settings """ db = current.db s3db = current.s3db pe_id = subscription["pe_id"] # Save filters filter_id = subscription["filter_id"] filters = subscription.get("filters") if filters: ftable = s3db.pr_filter if not filter_id: success = ftable.insert(pe_id=pe_id, query=filters) filter_id = success else: success = db(ftable.id == filter_id).update(query=filters) if not success: return None # Save subscription settings stable = s3db.pr_subscription subscription_id = subscription["id"] frequency = subscription["frequency"] if not subscription_id: success = stable.insert(pe_id=pe_id, filter_id=filter_id, notify_on=subscription["notify_on"], frequency=frequency, method=subscription["method"]) subscription_id = success else: success = db(stable.id == subscription_id).update( pe_id=pe_id, filter_id=filter_id, notify_on=subscription["notify_on"], frequency=frequency, method=subscription["method"]) if not success: return None # Save subscriptions rtable = s3db.pr_subscription_resource subscribe = subscription.get("subscribe") if subscribe: now = datetime.utcnow() resources = subscription["resources"] print "Get resources", resources subscribed = {} timestamps = {} if resources: for r in resources: subscribed[(r.resource, r.url)] = r.id timestamps[r.id] = (r.last_check_time, r.next_check_time) intervals = s3db.pr_subscription_check_intervals interval = timedelta(minutes=intervals.get(frequency, 0)) keep = set() fk = '''{"subscription_id": %s}''' % subscription_id for new in subscribe: resource, url = new["resource"], new["url"] if (resource, url) not in subscribed: # Restore subscription if previously unsubscribed, else # insert new record unsubscribed = {"deleted": True, "deleted_fk": fk, "resource": resource, "url": url} rtable.update_or_insert(_key=unsubscribed, deleted=False, deleted_fk=None, subscription_id=subscription_id, resource=resource, url=url, last_check_time=now, next_check_time=None) else: # Keep it record_id = subscribed[(resource, url)] last_check_time, next_check_time = timestamps[record_id] data = {} if not last_check_time: # Someone has tampered with the timestamps, so # we need to reset them and start over last_check_time = now data["last_check_time"] = last_check_time due = last_check_time + interval if next_check_time != due: # Time interval has changed data["next_check_time"] = due if data: db(rtable.id == record_id).update(**data) keep.add(record_id) # Unsubscribe all others unsubscribe = set(subscribed.values()) - keep db(rtable.id.belongs(unsubscribe)).update(deleted=True, deleted_fk=fk, subscription_id=None) # Update subscription subscription["id"] = subscription_id subscription["filter_id"] = filter_id return subscription # ------------------------------------------------------------------------- def _update_sync(self, resource, filters, selected_repository_id, properties): """ Update synchronization settings @param resource: available resources config @param filters: filter applied on the resource @param selected_repository_id: repository that is under current selection @param properties: comment field of the pr_subscription; used to store the ids of FTP Sync """ db = current.db s3db = current.s3db auth = current.auth user_id = auth.user.id utcnow = current.request.utcnow if properties: old_repository_id = properties["repository_id"] if old_repository_id != selected_repository_id: # Update properties["repository_id"] = selected_repository_id else: # First Run properties = {"repository_id": selected_repository_id} old_repository_id = selected_repository_id # Sync Task sync_task_table = s3db.sync_task # Check if task already exists query = (sync_task_table.deleted != True) & \ (sync_task_table.owned_by_user == user_id) & \ (sync_task_table.repository_id == old_repository_id) row = db(query).select(sync_task_table.id, sync_task_table.repository_id, limitby=(0, 1)).first() if row: old_sync_id = properties["sync_task_id"] # Check if update? if row.repository_id != selected_repository_id: # Update db(sync_task_table.repository_id == old_repository_id).\ update(repository_id = selected_repository_id) sync_task_id = properties["sync_task_id"] = row.id else: # First Run sync_task_data = {"repository_id": selected_repository_id, "resource_name": resource, "mode": 2, #Push "strategy": ["create"], # Alert updates are done # as extra info elements "representation": "cap", "multiple_file": True, "last_push": utcnow, # since used for notifications, # so don't send old alerts } sync_task_id = sync_task_table.insert(**sync_task_data) auth.s3_set_record_owner(sync_task_table, sync_task_id) old_sync_id = properties["sync_task_id"] = sync_task_id # Sync Resource Filter # Remove Old Filter and create new query = (FS("task_id") == old_sync_id) s3db.resource("sync_resource_filter", filter=query).delete() # Normally a filter looks like this # [["priority__belongs","24,3"],[u'location_id$L0__belongs', u'Nepal'], # [u'location_id$L1__belongs', u'Central']] # Get only those that have value and ignore null one filters = json.loads(filters) filters = [filter_ for filter_ in filters if filter_[1] is not None] sync_resource_filter_table = s3db.sync_resource_filter if len(filters) > 0: for filter_ in filters: # Get the prefix prefix = str(filter_[0]).strip("[]") # Get the value for prefix values = str(filter_[1]) # Set the Components if prefix in ["event_type_id__belongs", "priority__belongs", "language__belongs"]: component = "info" else: component = "area_location" filter_string = "%s.%s=%s" % (component, prefix, values) resource_filter_data = {"task_id": sync_task_id, "tablename": resource, "filter_string": filter_string, "modified_on": utcnow, } resource_filter_id = sync_resource_filter_table. \ insert(**resource_filter_data) row = db(sync_resource_filter_table.id == resource_filter_id).\ select(limitby=(0, 1)).first() auth.s3_set_record_owner(sync_resource_filter_table, resource_filter_id) s3db.onaccept(sync_resource_filter_table, row) return properties # ------------------------------------------------------------------------- def _remove_sync(self, properties): """ Remove synchronization settings """ if properties: current.s3db.resource("sync_repository", id=properties["repository_id"]).delete() # END =========================================================================
mit
the-zebulan/CodeWars
tests/kyu_7_tests/test_array_info.py
634
import unittest from katas.kyu_7.array_info import array_info class ArrayInfoTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(array_info( [1, 2, 3.33, 4, 5.01, 'bass', 'kick', ' '] ), [[8], [3], [2], [2], [1]]) def test_equal_2(self): self.assertEqual(array_info([0.001, 2, ' ']), [[3], [1], [1], [None], [1]]) def test_equal_3(self): self.assertEqual(array_info([]), 'Nothing in the array!') def test_equal_4(self): self.assertEqual(array_info([' ']), [[1], [None], [None], [None], [1]])
mit
educ-hack/wifi-data-viewer
src/EducHack/Repository/CDNHitRepository.php
327
<?php namespace EducHack\Repository; use Doctrine\ORM\EntityRepository; class CDNHitRepository extends EntityRepository { public function fetchLast() { return $this->createQueryBuilder('c') ->select('c') ->setMaxResults(10) ->getQuery() ->getResult(); } }
mit
Samuel-Oliveira/Java-Efd-Contribuicoes
src/main/java/br/com/swconsultoria/efd/contribuicoes/bo/blocoM/GerarRegistroM205.java
706
/** * */ package br.com.swconsultoria.efd.contribuicoes.bo.blocoM; import br.com.swconsultoria.efd.contribuicoes.registros.blocoM.RegistroM205; import br.com.swconsultoria.efd.contribuicoes.util.Util; /** * @author Yuri Lemes * */ public class GerarRegistroM205 { public static StringBuilder gerar(RegistroM205 registroM205, StringBuilder sb) { sb.append("|").append(Util.preencheRegistro(registroM205.getReg())); sb.append("|").append(Util.preencheRegistro(registroM205.getNum_campo())); sb.append("|").append(Util.preencheRegistro(registroM205.getCod_rec())); sb.append("|").append(Util.preencheRegistro(registroM205.getVl_debito())); sb.append("|").append('\n'); return sb; } }
mit
Shopify/shipit-engine
db/migrate/20200706145406_add_review_stacks.rb
428
class AddReviewStacks < ActiveRecord::Migration[6.0] def change add_column :stacks, :provision_status, :string, null: false, default: :deprovisioned add_index :stacks, :provision_status add_column :stacks, :type, :string, default: "Shipit::Stack" add_index :stacks, :type add_column :stacks, :awaiting_provision, :boolean, null: false, default: false add_index :stacks, :awaiting_provision end end
mit
dunncl15/weathrly
lib/components/Hourly.js
696
import React from 'react'; const Hourly = ({ weather }) => { const hourly = weather[0].hourly_forecast; const nextSeven = hourly.filter((hour, i) => { return i < 7; }); return ( <section className="hourly-section"> <h4 className="title">Hourly Forecast</h4> <ul className="hourly-forecast"> {nextSeven.map((hour, i) => { return ( <li className="hour" key={i}> <div className="time">{hour.FCTTIME.civil}</div> <img className="icon-hour" src={hour.icon_url} alt='weather icon'/> {hour.temp.english}° </li> ); })} </ul> </section> ); }; export default Hourly;
mit
SocialiteProviders/Providers
src/Monday/MondayExtendSocialite.php
415
<?php namespace SocialiteProviders\Monday; use SocialiteProviders\Manager\SocialiteWasCalled; class MondayExtendSocialite { /** * Register the provider. * * @param \SocialiteProviders\Manager\SocialiteWasCalled $socialiteWasCalled */ public function handle(SocialiteWasCalled $socialiteWasCalled) { $socialiteWasCalled->extendSocialite('monday', Provider::class); } }
mit
nakamura-to/KageDB
test/objectstore_test.js
19416
module("objectstore_test", { setup: function () { var myDB = this.myDB = new KageDB({ name: "myDB", migration: { 1: function (ctx, next) { var db = ctx.db; var tx = ctx.tx; var person = db.createObjectStore("person", {autoIncrement: true}); person.createIndex("name", "name", {unique: true}); var address = db.createObjectStore("address", {autoIncrement: true}); address.createIndex("street", "street", {unique: true}); tx.join([ person.put({name: "aaa", age: 10}), person.put({name: "bbb", age: 20}), address.put({street: "aaa"}), address.put({street: "bbb"}), address.put({street: "ccc"}), address.put({street: "ddd"}), address.put({street: "eee"}) ], next); } }, onerror: function (event) { throw new Error(event.kage_message); } }); stop(); KageDB.indexedDB.open(myDB.name).onsuccess = function (event) { var db = event.target.result; db.close(); KageDB.indexedDB.deleteDatabase(myDB.name).onsuccess = function () { start(); }; }; } }); asyncTest("put", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.put({name: "xxx", age: 99}, function (result) { strictEqual(result, 3); myDB.all(function (values) { deepEqual(values.person, [ {name: "aaa", age: 10}, {name: "bbb", age: 20}, {name: "xxx", age: 99} ]); start(); }); }); }); }); asyncTest("put with kye", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.put({name: "xxx", age: 99}, 1, function (result) { strictEqual(result, 1); myDB.all(function (values) { deepEqual(values.person, [ {name: "xxx", age: 99}, {name: "bbb", age: 20} ]); start(); }); }); }); }); asyncTest("add", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.add({name: "xxx", age: 99}, function (result) { strictEqual(result, 3); myDB.all(function (values) { deepEqual(values.person, [ {name: "aaa", age: 10}, {name: "bbb", age: 20}, {name: "xxx", age: 99} ]); start(); }); }); }); }); asyncTest("add with key", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.add({name: "xxx", age: 99}, 1, null, function (event) { if (event.target.error) { ok(event.target.error, event.target.error); } else { strictEqual(event.target.errorCode, 4); } event.preventDefault(); // it is necessary to stopPropagation in FireFox event.stopPropagation(); start(); }); }); }); asyncTest("add constraint error", function () { expect(4); var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.add({name: "aaa", age: 99}, function () {}, function (event) { if (event.target.error) { ok(event.target.error, event.target.error); } else { strictEqual(event.target.errorCode, 4); } ok(event.kage_message, event.kage_message); }); }, function (event) { if (event.target.error) { ok(event.target.error, event.target.error); } else { strictEqual(event.target.errorCode, 4); } ok(event.kage_message, event.kage_message); event.preventDefault(); // it is necessary to make test success in FireFox start(); }); }); asyncTest("delete", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.delete(2, function () { myDB.all(function (values) { deepEqual(values.person, [ {name: "aaa", age: 10} ]); start(); }); }); }); }); asyncTest("delete with key range", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.delete({ge: 1, le: 2}, function () { myDB.all(function (values) { deepEqual(values.person, []); start(); }); }); }); }); asyncTest("del", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.del(2, function () { myDB.all(function (values) { deepEqual(values.person, [ {name: "aaa", age: 10} ]); start(); }); }); }); }); asyncTest("del with key range", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.del({ge: 1, le: 2}, function () { myDB.all(function (values) { deepEqual(values.person, []); start(); }); }); }); }); asyncTest("bulkPut", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.bulkPut([ {name: "xxx", age: 99}, {name: "yyy", age: 100} ], function (result) { deepEqual(result, [3, 4]); myDB.all(function (values) { deepEqual(values.person, [ {name: "aaa", age: 10}, {name: "bbb", age: 20}, {name: "xxx", age: 99}, {name: "yyy", age: 100} ]); start(); }); }); }); }); asyncTest("bulkPut with keys", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.bulkPut([ {name: "xxx", age: 99}, {name: "yyy", age: 100} ], [ 1, 2 ],function (result) { deepEqual(result, [1, 2]); myDB.all(function (values) { deepEqual(values.person, [ {name: "xxx", age: 99}, {name: "yyy", age: 100} ]); start(); }); }); }); }); asyncTest("bulkAdd", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.bulkAdd([ {name: "xxx", age: 99}, {name: "yyy", age: 100} ], function (result) { deepEqual(result, [3, 4]); myDB.all(function (values) { deepEqual(values.person, [ {name: "aaa", age: 10}, {name: "bbb", age: 20}, {name: "xxx", age: 99}, {name: "yyy", age: 100} ]); start(); }); }); }); }); asyncTest("bulkAdd with keys", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.bulkAdd([ {name: "xxx", age: 99}, {name: "yyy", age: 100} ], [ 3, 4 ],function (result) { deepEqual(result, [3, 4]); myDB.all(function (values) { deepEqual(values.person, [ {name: "aaa", age: 10}, {name: "bbb", age: 20}, {name: "xxx", age: 99}, {name: "yyy", age: 100} ]); start(); }); }); }); }); asyncTest("bulkDelete", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.bulkDelete([1, 2], function () { myDB.all(function (values) { deepEqual(values.person, []); start(); }); }); }); }); asyncTest("get", function () { var myDB = this.myDB; myDB.tx(["person"], function (tx, person) { person.get(2, function (value) { deepEqual(value, {name: "bbb", age: 20}); start(); }); }); }); // Chrome doesn't support `get(keyRange)` if (typeof webkitIndexedDB === "undefined") { asyncTest("get with key", function () { var myDB = this.myDB; myDB.tx(["person"], function (tx, person) { person.get({gt:1, le:10}, function (value) { deepEqual(value, {name: "bbb", age: 20}); start(); }); }); }); } asyncTest("clear", function () { var myDB = this.myDB; myDB.tx(["person"], "readwrite", function (tx, person) { person.clear(function () { myDB.all(function (values) { deepEqual(values.person, []); start(); }); }); }); }); asyncTest("openCursor", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor(function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "aaa"}, {street: "bbb"}, {street: "ccc"}, {street: "ddd"}, {street: "eee"} ]); start(); } }); }); }); asyncTest("openCursor eq", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({eq: 2}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "bbb"} ]); start(); } }); }); }); asyncTest("openCursor gt", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({gt: 2}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "ccc"}, {street: "ddd"}, {street: "eee"} ]); start(); } }); }); }); asyncTest("openCursor ge", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({ge: 2}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "bbb"}, {street: "ccc"}, {street: "ddd"}, {street: "eee"} ]); start(); } }); }); }); asyncTest("openCursor lt", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({lt: 4}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "aaa"}, {street: "bbb"}, {street: "ccc"} ]); start(); } }); }); }); asyncTest("openCursor le", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({le: 4}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "aaa"}, {street: "bbb"}, {street: "ccc"}, {street: "ddd"} ]); start(); } }); }); }); asyncTest("openCursor ge le", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({ge: 2, le: 4}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "bbb"}, {street: "ccc"}, {street: "ddd"} ]); start(); } }); }); }); asyncTest("openCursor gt lt", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({gt: 2, lt: 4}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "ccc"} ]); start(); } }); }); }); asyncTest("openCursor next", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({direction: "next"}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "aaa"}, {street: "bbb"}, {street: "ccc"}, {street: "ddd"}, {street: "eee"} ]); start(); } }); }); }); asyncTest("openCursor prev", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({direction: "prev"}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "eee"}, {street: "ddd"}, {street: "ccc"}, {street: "bbb"}, {street: "aaa"} ]); start(); } }); }); }); asyncTest("openCursor gt prev", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({gt: 2, direction: "prev"}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "eee"}, {street: "ddd"}, {street: "ccc"} ]); start(); } }); }); }); asyncTest("openCursor ge prev", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { var results = []; address.openCursor({ge: 2, direction: "prev"}, function (cursor) { if (cursor) { results.push(cursor.value); cursor.continue(); } else { deepEqual(results, [ {street: "eee"}, {street: "ddd"}, {street: "ccc"}, {street: "bbb"} ]); start(); } }); }); }); asyncTest("fetch gt prev", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.fetch({gt: 2, direction: "prev"}, function (results) { deepEqual(results, [ {street: "eee"}, {street: "ddd"}, {street: "ccc"} ]); start(); }); }); }); asyncTest("fetch gt prev filter", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.fetch({gt: 2, filter: filter, direction: "prev"}, function (results) { deepEqual(results, [ {street: "ddd"} ]); start(); }); }); function filter(address, i) { return address.street === "ddd" && i == 1; } }); asyncTest("fetch offset limit", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.fetch({offset: 1, limit: 3}, function (results) { deepEqual(results, [ {street: "bbb"}, {street: "ccc"}, {street: "ddd"} ]); start(); }); }); }); asyncTest("fetch reduce", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.fetch({offset: 1, limit: 3, reduce: reduce}, function (result) { strictEqual(result.val, "bbbcccddd"); start(); }); }); function reduce(prev, curr) { return {val: (prev.val ? prev.val : prev.street) + curr.street}; } }); asyncTest("fetch reduce initialValue", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.fetch({offset: 1, limit: 3, reduce: reduce, initialValue: ""}, function (result) { strictEqual(result, "bbbcccddd"); start(); }); }); function reduce(prev, curr) { return prev + curr.street; } }); asyncTest("fetch keyOnly", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.fetch({offset: 1, limit: 3, reduce: reduce, keyOnly: true}, function (result) { strictEqual(result, 9); start(); }); }); function reduce(prev, curr) { return prev + curr; } }); asyncTest("count", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.count(function (value) { strictEqual(value, 5); start(); }); }); }); asyncTest("count with key range", function () { var myDB = this.myDB; myDB.tx(["address"], function (tx, address) { address.count({gt: 3}, function (value) { strictEqual(value, 2); start(); }); }); });
mit
yzhao583/webchecker
config/demo.js
307
// demo.js module.exports = { mongodb: { user: process.env.MONGOLAB_USERNAME, password: process.env.MONGOLAB_PASSWORD, database: process.env.MONGOLAB_DATABASE, server: process.env.MONGOLAB_SERVER }, monitor: { apiUrl: process.env.UPTIME_API_URL }, verbose: false }
mit
reqres-modules/bootstrap-fields
src/View.php
4492
<?php namespace Reqres\Module\FieldsBootstrap; use Reqres\Response; use Reqres\Form; use Reqres\Field; trait View { /** * * Прописываем набор настроек для полей * * Эти настройки можно будет применять к конкретному полю или к группе полей в форме * * @param require_module_path - передаем путь к папке которая будет подгружать JS модули оживляющие эти поля * */ static function mod_fields_bootstrap($require_module_path) { // настройки полей, для JS классов полей Form::styleAdd('bootstrap', $require_module_path, function(Field $field, $settings = []) use($require_module_path){ $prefix = 'mod_bootstrap_field_'; foreach(['root', 'error_indicator', 'error_container', 'readonly_container', 'edit_container'] as $tag) $field-> tag($tag)-> tagAddClass($prefix.$tag); $field // устанавливаем папку для шаблонов -> template('module-bootstrap/field') // прописываем папку откуда грузить можудь оживления поля -> tag() -> tagAttr('data-field-module', $require_module_path) // верхний тег -> tag('root') -> tagAddClass('form-group') // элементы, отвечающие за значение null -> tag('null_button') -> tagAttr('nullbutton', 'true') // элемент для значения ридонли -> tag('readonly_container') -> tagAddClass('form-control-static') // -> tag('input_group') -> tagAddClass('input-group') // -> tag('input') -> tagAddClass('form-control '.$prefix.'error_container') // -> tag('label_container') -> tagAddClass('control-label') ; // индикатор обязательности заполнения элементы if($field-> notempty()) $field-> tag('notempty_indicator')-> tagAddClass('text-danger'); // устанавливаем размер if(array_key_exists('size', $settings)) $field -> tag('input_group') -> tagAddClass('input-group-'.$settings['size']) -> tag('input') -> tagAddClass('input-'.$settings['size']) ; // устанавливаем размер сетки if(array_key_exists('grid', $settings)) { if(!is_array($settings['grid'])) $settings['grid'] = ['md' => $settings['grid']]; foreach($settings['grid'] as $size => $value) $field -> tag('content_container') -> tagAddClass('col-'.$size.'-'.$value) -> tag('label_container') -> tagAddClass('col-'.$size.'-'.($value == 12 ? 12 : 12-$value)) ; } }); // настройки полей для табличной части Form::styleAdd('bootstrap.table', $require_module_path, function(Field $field){ $field -> tag('root') -> tagAttr('readonly', 'true') -> tagRemoveClass('form-group') -> tag('label_container') -> tagAddClass('hidden') ; ; foreach(['md','sm','xs','lg'] as $size) $field -> tag('cont') -> tagAddClass('row') -> tag('content_container') -> tagAddClass('col-'.$size.'-12') -> tag('label_container') -> tagAddClass('col-'.$size.'-12') ; }); } }
mit
chhingchhing/boutique_cambo
application/language/french/giftcards_lang.php
5838
<?php $lang['giftcards_giftcard_number']='numero carte fidélité';//The good translation $lang['giftcards_card_value']='Valeur'; $lang['giftcards_basic_information']='Informations carte fidélité';//The good translation $lang['giftcards_number_required']='numero du carte est un champ requis';//The good translation $lang['giftcards_value_required']='valeur du carte est un champ requis';//The good translation $lang['giftcards_number']='numero de la carte doit être un chiffre';//The good translation $lang['giftcards_value']='valeur de la carte doit être un chiffre';//The good translation $lang['giftcards_retrive_giftcard_info']='Info carte retirée';//The good translation $lang['giftcards_description']='Description'; $lang['giftcards_amazon']='Amazone'; $lang['giftcards_upc_database']='base de données UPC';//The good translation $lang['giftcards_cannot_find_giftcard']='Impossible de trouver des informations sur la carte fidélité';//The good translation $lang['giftcards_info_provided_by']='Information fournie par'; $lang['giftcards_number_information']='numero carte';//The good translation $lang['giftcards_new']='nouvelle carte';//The good translation $lang['giftcards_update']='mise à jour de la carte';//The good translation $lang['giftcards_giftcard']='carte fidélité'; $lang['giftcards_edit_multiple_giftcards']='éditer plusieur cartes';//The good translation $lang['giftcards_category']='Catégorie';//The good translation $lang['giftcards_cost_price']='Prix achat'; $lang['giftcards_unit_price']='Prix vente'; $lang['giftcards_tax_1']='Taxe 1'; $lang['giftcards_tax_2']='Taxe 2'; $lang['giftcards_sales_tax_1'] = 'Taxe de vente'; $lang['giftcards_sales_tax_2'] = 'Taxe de vente 2'; $lang['giftcards_tax_percent']='Pourcentage Taxe'; $lang['giftcards_tax_percents']='Pourcentage Taxe(s)'; $lang['giftcards_reorder_level']='réorganiser niveau'; $lang['giftcards_quantity']='Quantité';//The good translation $lang['giftcards_no_giftcards_to_display']='Aucune carte fidélité à afficher';//The good translation $lang['giftcards_bulk_edit']='Modifier en bloc'; $lang['giftcards_confirm_delete']='Etes-vous sûr de vouloir supprimer les cartes fidélité sélectionnées?';//The good translation $lang['giftcards_none_selected']='Vous avez n\'sélectionné aucune carte fidélité à modifier';//The good translation $lang['giftcards_confirm_bulk_edit']='Etes-vous sûr de vouloir modifier toutes les cartes de fidélité sélectionnées?';//The good translation $lang['giftcards_successful_bulk_edit']='Vous avez mis à jour le carte fidélité selectionnée';//The good translation $lang['giftcards_error_updating_multiple']='Erreur mise à jour des cartes';//The good translation $lang['giftcards_edit_fields_you_want_to_update']='Editez les champs que vous souhaitez modifier pour tous les cartes sélectionnées';//The good translation $lang['giftcards_error_adding_updating'] = 'Erreur en ajoutant/ en mettant à jour la carte fidélité';//The good translation $lang['giftcards_successful_adding']='vous avez ajouté avec succèss une carte fidélité';//The good translation $lang['giftcards_successful_updating']='vous avez mis à jour avec success une carte fidélité';//The good translation $lang['giftcards_successful_deleted']='vous avez supprimé avec succèss la carte fidélité';//The good translation $lang['giftcards_one_or_multiple']='cartes fidélité';//The good translation $lang['giftcards_cannot_be_deleted']='Impossible de supprimer les cartes sélectionnées, un ou plusieurs des carte en cours d\'utilisation.';//The good translation $lang['giftcards_none'] = 'aucune';//The good translation $lang['giftcards_supplier'] = 'Fournisseur'; $lang['giftcards_generate_barcodes'] = 'générer des codes à barres';//The good translation $lang['giftcards_must_select_giftcard_for_barcode'] = 'Vous devez sélectionner au moins une carte pour générer le code à barre';//The good translation $lang['giftcards_excel_import_failed'] = 'Echec Importation Excel'; $lang['giftcards_allow_alt_desciption'] = 'Autoriser Description de Alt'; $lang['giftcards_is_serialized'] = 'la carte de fidélité a un numéro de série'; $lang['giftcards_low_inventory_giftcards'] = 'faible Inventaire des cartes fidélité';//The good translation $lang['giftcards_serialized_giftcards'] = 'les cartes fidélité en série';//The good translation $lang['giftcards_no_description_giftcards'] = 'la carte fidélité n\'a pas de description';//The good translation $lang['giftcards_inventory_comments']='Commentaires'; $lang['giftcards_count']='Inventaire mis à jour';//The good translation $lang['giftcards_details_count']='Détails inventaire des stocks';//The good translation $lang['giftcards_add_minus']='Inventaire à ajouter / soustraire';//The good translation $lang['giftcards_current_quantity']='Quantité actuelle';//The good translation $lang['giftcards_quantity_required']='La quantité est un champ obligatoire. S\'il vous plaît Fermer (X) pour annuler';//The good translation $lang['giftcards_do_nothing'] = 'ne rien faire'; $lang['giftcards_change_all_to_serialized'] = 'Remplacer tout en série';//The good translation $lang['giftcards_change_all_to_unserialized'] = 'Remplacer tout pour non linéaire';//The good translation $lang['giftcards_change_all_to_allow_alt_desc'] = ' Autoriser Alt Desc Pour Tous'; $lang['giftcards_change_all_to_not_allow_allow_desc'] = 'Ne pas Autoriser Alt Desc Pour Tous'; $lang['giftcards_use_inventory_menu'] = 'Utiliser Inv. menu';//The good translation $lang['giftcards_manually_editing_of_quantity'] = 'Edition manuelle des quantités';//The good translation $lang['giftcards_customer_name'] = 'Nom du client'; $lang['giftcards_exists']='Etes-vous sûr que vous voulez nettoyer TOUS les employés supprimés?'; $lang['giftcards_id'] = 'Giftcard ID'; ?>
mit
SparkRebel/sparkrebel.com
src/PW/CategoryBundle/DataFixtures/MongoDB/LoadExampleData.php
3050
<?php namespace PW\CategoryBundle\DataFixtures\MongoDB; use Doctrine\Common\DataFixtures\AbstractFixture, Doctrine\Common\DataFixtures\OrderedFixtureInterface, Doctrine\Common\Persistence\ObjectManager, PW\CategoryBundle\Document\Category; /** * LoadExampleData */ class LoadExampleData extends AbstractFixture implements OrderedFixtureInterface { /** * getOrder * * Has no pre-load dependencies * * @return int */ public function getOrder() { return 10; } /** * load some example data * * @param mixed $manager instance */ public function load(ObjectManager $manager) { for ($i = 1; $i <= 10; $i++) { $document = new Category(); $document->setName("channel $i"); $document->setType('user'); $this->addReference("Category-$i", $document); $manager->persist($document); for ($j = 1; $j <= 10; $j++) { $child = new Category(); $child->setName("channel $i.$j"); $child->setType('user'); $child->setParent($document); $this->addReference("Category-$i-$j", $child); $manager->persist($child); } } for ($i = 1; $i <= 10; $i++) { $document = new Category(); $document->setName("item channel $i"); $document->setType('item'); $this->addReference("ItemCategory-$i", $document); $manager->persist($document); } $itemCats = array( 'tops' => array( 'hoodies & sweatshirts', 'shirts & blouses', 'sweaters', 'tanks & camis', 't-shirts & polos', ), 'Bottoms' => array( 'jeans', 'Trousers' ), 'dresses' => array( ), 'outerwear' => array( ), 'swimwear' => array( ), 'shoes' => array( ), 'accessories' => array( 'belts' ), 'jewelry' => array( ), 'makeup' => array( ), ); foreach ($itemCats as $name => $subCats) { $document = new Category(); $document->setName($name); $document->setType('item'); $this->addReference("item-cat-$name", $document); $manager->persist($document); if (count($subCats) > 0) { foreach ($subCats as $subName) { $subDoc = new Category(); $subDoc->setName($subName); $subDoc->setType('item'); $subDoc->setParent($document); $this->addReference("item-cat-$name-$subName", $subDoc); $manager->persist($subDoc); } } } $manager->flush(); } }
mit
meibegger/me-dialog
dist/me-dialog.bundle.ie9.js
93071
/** * @license me-dialog 3.0.2 Copyright (c) Mandana Eibegger <scripts@schoener.at> * Available via the MIT license. * see: https://github.com/meibegger/me-dialog for details */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.meDialog = factory(); } }(this, function () { /** * @license almond 0.3.2 Copyright jQuery Foundation and other contributors. * Released under MIT license, http://github.com/requirejs/almond/LICENSE */ //Going sloppy to avoid 'use strict' string cost, but strict practices should //be followed. /*global setTimeout: false */ var requirejs, require, define; (function (undef) { var main, req, makeMap, handlers, defined = {}, waiting = {}, config = {}, defining = {}, hasOwn = Object.prototype.hasOwnProperty, aps = [].slice, jsSuffixRegExp = /\.js$/; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var nameParts, nameSegment, mapValue, foundMap, lastIndex, foundI, foundStarMap, starI, i, j, part, normalizedBaseParts, baseParts = baseName && baseName.split("/"), map = config.map, starMap = (map && map['*']) || {}; //Adjust any relative paths. if (name) { name = name.split('/'); lastIndex = name.length - 1; // If wanting node ID compatibility, strip .js from end // of IDs. Have to do this here, and not in nameToUrl // because node allows either .js or non .js to map // to same file. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } // Starts with a '.' so need the baseName if (name[0].charAt(0) === '.' && baseParts) { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); name = normalizedBaseParts.concat(name); } //start trimDots for (i = 0; i < name.length; i++) { part = name[i]; if (part === '.') { name.splice(i, 1); i -= 1; } else if (part === '..') { // If at the start, or previous value is still .., // keep them so that when converted to a path it may // still work when converted to a path, even though // as an ID it is less than ideal. In larger point // releases, may be better to just kick out an error. if (i === 0 || (i === 1 && name[2] === '..') || name[i - 1] === '..') { continue; } else if (i > 0) { name.splice(i - 1, 2); i -= 2; } } } //end trimDots name = name.join('/'); } //Apply map config if available. if ((baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join("/"); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function makeRequire(relName, forceSync) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName var args = aps.call(arguments, 0); //If first arg is not require('string'), and there is only //one arg, it is the array form without a callback. Insert //a null so that the following concat is correct. if (typeof args[0] !== 'string' && args.length === 1) { args.push(null); } return req.apply(undef, args.concat([relName, forceSync])); }; } function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(depName) { return function (value) { defined[depName] = value; }; } function callDep(name) { if (hasProp(waiting, name)) { var args = waiting[name]; delete waiting[name]; defining[name] = true; main.apply(undef, args); } if (!hasProp(defined, name) && !hasProp(defining, name)) { throw new Error('No ' + name); } return defined[name]; } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName) { var plugin, parts = splitPrefix(name), prefix = parts[0]; name = parts[1]; if (prefix) { prefix = normalize(prefix, relName); plugin = callDep(prefix); } //Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); } else { name = normalize(name, relName); } } else { name = normalize(name, relName); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (prefix) { plugin = callDep(prefix); } } //Using ridiculous property names for space reasons return { f: prefix ? prefix + '!' + name : name, //fullName n: name, pr: prefix, p: plugin }; }; function makeConfig(name) { return function () { return (config && config.config && config.config[name]) || {}; }; } handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name) { return { id: name, uri: '', exports: defined[name], config: makeConfig(name) }; } }; main = function (name, deps, callback, relName) { var cjsModule, depName, ret, map, i, args = [], callbackType = typeof callback, usingExports; //Use name if no relName relName = relName || name; //Call the callback to define the module, if necessary. if (callbackType === 'undefined' || callbackType === 'function') { //Pull out the defined dependencies and pass the ordered //values to the callback. //Default to [require, exports, module] if no deps deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; for (i = 0; i < deps.length; i += 1) { map = makeMap(deps[i], relName); depName = map.f; //Fast path CommonJS standard dependencies. if (depName === "require") { args[i] = handlers.require(name); } else if (depName === "exports") { //CommonJS module spec 1.1 args[i] = handlers.exports(name); usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 cjsModule = args[i] = handlers.module(name); } else if (hasProp(defined, depName) || hasProp(waiting, depName) || hasProp(defining, depName)) { args[i] = callDep(depName); } else if (map.p) { map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); args[i] = defined[depName]; } else { throw new Error(name + ' missing ' + depName); } } ret = callback ? callback.apply(defined[name], args) : undefined; if (name) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. if (cjsModule && cjsModule.exports !== undef && cjsModule.exports !== defined[name]) { defined[name] = cjsModule.exports; } else if (ret !== undef || !usingExports) { //Use the return value from the function. defined[name] = ret; } } } else if (name) { //May just be an object definition for the module. Only //worry about defining if have a module name. defined[name] = callback; } }; requirejs = require = req = function (deps, callback, relName, forceSync, alt) { if (typeof deps === "string") { if (handlers[deps]) { //callback in this case is really relName return handlers[deps](callback); } //Just return the module wanted. In this scenario, the //deps arg is the module name, and second arg (if passed) //is just the relName. //Normalize module name, if it contains . or .. return callDep(makeMap(deps, callback).f); } else if (!deps.splice) { //deps is a config object, not an array. config = deps; if (config.deps) { req(config.deps, config.callback); } if (!callback) { return; } if (callback.splice) { //callback is an array, which means it is a dependency list. //Adjust args if there are dependencies deps = callback; callback = relName; relName = null; } else { deps = undef; } } //Support require(['a']) callback = callback || function () {}; //If relName is a function, it is an errback handler, //so remove it. if (typeof relName === 'function') { relName = forceSync; forceSync = alt; } //Simulate async callback; if (forceSync) { main(undef, deps, callback, relName); } else { //Using a non-zero value because of concern for what old browsers //do, and latest browsers "upgrade" to 4 if lower value is used: //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: //If want a value immediately, use require('id') instead -- something //that works in almond on the global level, but not guaranteed and //unlikely to work in other AMD implementations. setTimeout(function () { main(undef, deps, callback, relName); }, 4); } return req; }; /** * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { return req(cfg); }; /** * Expose module registry for debugging and tooling */ requirejs._defined = defined; define = function (name, deps, callback) { if (typeof name !== 'string') { throw new Error('See almond README: incorrect module build, no module name'); } //This module may not have dependencies if (!deps.splice) { //deps is not an array, so probably means //an object literal or factory function for //the value. Adjust args. callback = deps; deps = []; } if (!hasProp(defined, name) && !hasProp(waiting, name)) { waiting[name] = [name, deps, callback]; } }; define.amd = { jQuery: true }; }()); define("almond", function(){}); /** * @license me-tools 3.0.0 Copyright (c) Mandana Eibegger <scripts@schoener.at> * Available via the MIT license. * see: https://github.com/meibegger/me-tools for details */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define('meTools.fn.variable', [ ], factory); } else if(typeof exports === 'object') { if (typeof module === 'object') { module.exports = factory(); } else { exports['meTools.fn.variable'] = factory(); } } else { root.meTools = root.meTools || {}; root.meTools.fn = root.meTools.fn || {}; root.meTools.fn.variable = factory(); } }(this, function () { /* --------------- functions --------------- */ /** * Create a copy of a variable. * * copyValues(vals [, deep]) * * @param vals mixed * @param deep bool; optional; deep-copy; default is true * @returns {*} mixed; a copy of the passed value */ function copyValues(vals, deep) { deep = (typeof(deep) === 'undefined') || deep; var copy, val; if (Array.isArray(vals)) { copy = []; for (var i in vals) { val = vals[i]; copy.push((deep && typeof val === 'object') ? copyValues(val) : val); } } else if (vals && typeof(vals) === 'object' && typeof(vals.tagName) === 'undefined' && vals !== window && vals !== document) { copy = {}; for (var key in vals) { val = vals[key]; copy[key] = (deep && typeof val === 'object') ? copyValues(val) : val; } } else { copy = vals; } return copy; } /** * Merge 2 Objects and return a copy. * * mergeObjects(object1, object2) * * @param object1 Object * @param object2 Object * @returns {{}} New merged Object */ function mergeObjects(object1, object2) { object1 = object1 || {}; object2 = object2 || {}; var result = {}; for (var key1 in object1) { var option1 = object1[key1]; if (object2.hasOwnProperty(key1)) { var option2 = object2[key1]; if (Array.isArray(option2) || typeof(option2) !== 'object' || typeof(option1) !== 'object') { result[key1] = copyValues(option2); } else { result[key1] = mergeObjects(option1, option2); } } else { result[key1] = copyValues(option1); } } for (var key2 in object2) { if (!result.hasOwnProperty(key2)) { result[key2] = copyValues(object2[key2]); } } return result; } /** * Check if an object is empty. * * isEmptyObject(object) * * @param object Object * @returns {boolean} */ function isEmptyObject(object) { for (var i in object) { return false; } return true; } /* --------------- api --------------- */ return { copyValues: copyValues, mergeObjects: mergeObjects, isEmptyObject: isEmptyObject }; })); (function (root, factory) { if (typeof define === 'function' && define.amd) { define('meTools.fn.element', [ ], factory); } else if(typeof exports === 'object') { if (typeof module === 'object') { module.exports = factory(); } else { exports['meTools.fn.element'] = factory(); } } else { root.meTools = root.meTools || {}; root.meTools.fn = root.meTools.fn || {}; root.meTools.fn.element = factory(); } }(this, function () { /* --------------- functions --------------- */ /** * Get the specified element. * * getElementById(elementSpec) * * @param elementSpec mixed; string (id) or element; * @returns {*} element or null */ function getElementById(elementSpec) { if (typeof(elementSpec) === 'object' && typeof(elementSpec.tagName) !== 'undefined') { return elementSpec; } else if (typeof(elementSpec) === 'string') { return document.getElementById(elementSpec); } else { return null; } } /** * Get the ID of an element. If the element has no ID, it will be assigned a random ID. * * getId(element [, prefix]) * * @param element DOM element * @param prefix string; optional; A prefix for generated IDs; default is 'id-' * @returns {string} ID */ function getId(element, prefix) { var id = element.getAttribute('id'); if (!id) { // assign an ID prefix = prefix || 'id-'; do { var date = new Date(); id = prefix + Math.ceil(date.valueOf() % 10000 * Math.random()); } while (document.getElementById(id)); element.setAttribute('id', id); } return id; } /** * Get all ancestors of an element, possibly matching a selector, up to an optional container. * * Note: this function uses matches(selector), so you need to include a polyfill for all IEs! * * getAncestors(element [, selector] [, container] [, single]) * * @param element DOM-Element; * @param selector String; optional; selector to match the parents against * @param container DOM-Element; optional; max parent to check; default is body * @param single Boolean; optional; return only the next matching ancestor * @return mixed; array or false/element if single===true */ function getAncestors(element, selector, container, single) { // prepare arguments var argSelector = false, argContainer = false, argSingle = false; for (var i = 1; i < arguments.length; i++) { switch (typeof(arguments[i])) { case 'string': argSelector = arguments[i]; break; case 'object': argContainer = arguments[i]; break; case 'boolean': argSingle = arguments[i]; break; } } selector = argSelector; container = argContainer || document.body; single = argSingle; var parents = [], getAncestors = function (element) { var parent = element.parentElement; if (!selector || parent.matches(selector)) { if (single) { return parent; } else { parents.push(parent); } } if (parent === container) { return single ? false : parents; } return getAncestors(parent); } ; return getAncestors(element); } /** * Check if an element is the parent of another element. * * isParent(parent, child) * * @param parent DOM-element * @param child DOM-element * @returns {boolean} */ function isParent(parent, child) { var node = child.parentNode; while (node !== null) { if (node === parent) { return true; } node = node.parentNode; } return false; } /** * Add 1 or more values to an attribute. * * addAttributeValues(element, attributeName, values) * * @param element DOM-element * @param attributeName string * @param values mixed; string or array of strings */ function addAttributeValues(element, attributeName, values) { values = Array.isArray(values) ? values : [values]; var attributeVal = element.getAttribute(attributeName), currentVals = attributeVal ? attributeVal.split(' ') : []; for (var i = 0; i < values.length; i++) { var value = values[i]; if (currentVals.indexOf(value) === -1) { currentVals.push(value); } } element.setAttribute(attributeName, currentVals.join(' ')); } /** * Remove one or more values from an attribute. * * removeAttributeValues(element, attributeName, values, keepEmptyAttribute) * * @param element DOM-element * @param attributeName string * @param values mixed; string or array of strings * @param keepEmptyAttribute bool */ function removeAttributeValues(element, attributeName, values, keepEmptyAttribute) { var attributeVal = element.getAttribute(attributeName); if (attributeVal) { var expStart = '((^| )', expEnd = '(?= |$))'; attributeVal = attributeVal.replace(new RegExp(Array.isArray(values) ? expStart + values.join(expEnd + '|' + expStart) + expEnd : expStart + values + expEnd, 'g'), ''); if (keepEmptyAttribute || attributeVal) { element.setAttribute(attributeName, attributeVal); } else { element.removeAttribute(attributeName); } } } /** * Checks if an attribute has a value (word). * * hasAttributeValue(element, attributeName, value) * * @param element DOM-element * @param attributeName string * @param value string * @returns {boolean} */ function hasAttributeValue(element, attributeName, value) { var attributeVal = element.getAttribute(attributeName); if (attributeVal) { var expStart = '((^| )', expEnd = '(?= |$))'; return !!attributeVal.match(new RegExp(expStart + value + expEnd, 'g')); } return false; } /** * Get all radio-buttons belonging to a radio-button's group * @param radio DOM-Element radio element * @returns [] */ function getRadioGroup(radio) { // get the form for the radiobutton var form = getAncestors(radio, 'form', true) || // radiobutton is contained in a form document, name = radio.getAttribute('name'); return [].slice.call(form.querySelectorAll('input[type="radio"][name="' + name + '"]')); } /** * Returns all focusable elements, ordered by tabindex * @param container DOM-Element; required * @param selector String selector for elements which are focusable; optionsl; default is 'a,frame,iframe,input:not([type=hidden]),select,textarea,button,*[tabindex]' * @returns {Array} */ function fetchFocusables (container, selector) { selector = selector || 'a,frame,iframe,input:not([type=hidden]),select,textarea,button,*[tabindex]:not([tabindex="-1"])'; return orderByTabindex(container.querySelectorAll(selector)); } /** * @param focusables Array of Dom-Elements * @returns {Array} */ function orderByTabindex (focusables) { var byTabindex = [], ordered = []; for (var i = 0; i < focusables.length; i++) { var focusable = focusables[i], tabindex = Math.max(0, focusable.getAttribute('tabindex') || 0); byTabindex[tabindex] = byTabindex[tabindex] || []; byTabindex[tabindex].push(focusable); } for (var j in byTabindex) { for (var k in byTabindex[j]) { ordered.push(byTabindex[j][k]); } } return ordered; } /** * Return not disabled, visible, tabable-radio ordered by the specified tab-direction * @param focusables Array of DOM-Elements; required * @param tabDirection int; optional; tab-direction (-1 or 1); default is 1 * @returns {Array} or false */ function getFocusables (focusables, tabDirection) { // prepare argument tabDirection = typeof(tabDirection) === 'undefined' ? 1 : tabDirection; var filtered = [], doneRadios = []; // already processed radio-buttons function evalCandidate(candidate) { if (candidate.matches(':not([disabled])') && (candidate.offsetWidth || candidate.offsetHeight)) { // not disabled & visible if (candidate.matches('input[type="radio"]')) { // remove all radio buttons which are not tabable if (doneRadios.indexOf(candidate) === -1) { // group of this radio not processed yet // get radio-group var radioGroup = getRadioGroup(candidate), focusableRadio = null; doneRadios = doneRadios.concat(radioGroup); // get tabable radios of the group (checked or first&last of group) for (var j = 0; j < radioGroup.length; j++) { var radio = radioGroup[j]; if (radio.checked) { focusableRadio = radio; break; } } if (!focusableRadio) { focusableRadio = tabDirection === -1 ? radioGroup[radioGroup.length-1] : radioGroup[0]; // default is tabable in tab-direction!!! } return focusableRadio; } } else { return candidate; } return false; } } // remove all elements which are not tabable if (tabDirection === 1) { for (var i = 0; i < focusables.length; i++) { var tabable = evalCandidate(focusables[i]); if (tabable) { filtered.push(tabable); } } } else { for (var j = focusables.length-1; j >= 0; j--) { var backwardTabable = evalCandidate(focusables[j]); if (backwardTabable) { filtered.push(backwardTabable); } } } return filtered; } /** * * @param container DOM-Element * @param fn(container, focusables) Function returning the element to focus */ function focusInside(container, fn) { var toFocus = null, focusables = getFocusables(fetchFocusables(container)); if (typeof fn === 'function') { toFocus = fn(container, focusables); } if (!toFocus && focusables.length) { toFocus = focusables[0]; } if (!toFocus) { var containerTabindex = container.getAttribute('tabindex'); if (!containerTabindex) { container.setAttribute('tabindex', '-1'); } toFocus = container; } toFocus.focus(); } /* --------------- api --------------- */ return { getElementById: getElementById, getId: getId, getAncestors: getAncestors, isParent: isParent, addAttributeValues: addAttributeValues, removeAttributeValues: removeAttributeValues, hasAttributeValue: hasAttributeValue, fetchFocusables: fetchFocusables, orderByTabindex: orderByTabindex, getFocusables: getFocusables, focusInside: focusInside }; })); (function (root, factory) { if (typeof define === 'function' && define.amd) { define('meTools.fn.event', [ 'meTools.fn.variable' ], factory); } else if(typeof exports === 'object') { var fnVariable = require('./variable'); if (typeof module === 'object') { module.exports = factory(fnVariable); } else { exports['meTools.fn.event'] = factory(fnVariable); } } else { root.meTools = root.meTools || {}; root.meTools.fn = root.meTools.fn || {}; root.meTools.fn.event = factory(root.meTools.fn.variable); } }(this, function (fnVariable) { /* --------------- functions --------------- */ /** * Add an event-listener and register it to an instance. * The instance will get a property 'registeredEvents' storing the registered events. * * registerEvent(scope, target, type, fn [, capture]) * * @param scope object; instance to register the event to * @param target DOM object; event target * @param type string; event name * @param fn function; event handler * @param capture boolean; optional; capture the event; default is false */ function registerEvent(scope, target, type, fn, capture) { capture = capture || false; var registeredEvents = scope.registeredEvents = scope.registeredEvents || {}, typeListeners = registeredEvents[type] = registeredEvents[type] || [], targetTypeHandlers = false ; for (var i in typeListeners) { var typeHandlers = typeListeners[i]; if (typeHandlers.tg === target) { targetTypeHandlers = typeHandlers; break; } } if (!targetTypeHandlers) { targetTypeHandlers = { tg: target, fns: [] }; typeListeners.push(targetTypeHandlers); } targetTypeHandlers.fns.push([fn, capture]); target.addEventListener(type, fn, capture); } /** * Remove (an) event-listener(s), previously registered to an instance. * * unregisterEvent(scope [, target] [, type] [, fn] [, capture]) * * @param scope object; instance the event was registered to * @param target DOM object; optional; event target; if not set, matching events will be removed on all targets * @param type string; optional; event name; if not set, all event-types will be removed * @param fn function; optional; event handler; if not set, all event-handlers will be removed * @param capture boolean; optional; if not set, captured & not-captured events are removed, if true only captured events are removed, if false only not-captured events are removed */ function unregisterEvent(scope, target, type, fn, capture) { if (!scope.registeredEvents) { return; } var registeredEvents = scope.registeredEvents; if (!type) { for (type in registeredEvents) { unregisterEvent(scope, target, type, fn, capture); } return; } if (!registeredEvents.hasOwnProperty(type)) { return; } var typeListeners = registeredEvents[type]; if (!target) { var cTypeListeners = fnVariable.copyValues(typeListeners); while (cTypeListeners.length) { var typeListener = cTypeListeners.shift(); unregisterEvent(scope, typeListener.tg, type, fn, capture); } return; } var fns = false, typeHandlers; for (var j in typeListeners) { typeHandlers = typeListeners[j]; if (typeHandlers.tg === target) { fns = typeHandlers.fns; break; } } if (!fns) { return; } for (var k = 0; k < fns.length; k++) { var fnDef = fns[k]; if ((typeof(fn) === 'undefined' || !fn || fn === fnDef[0]) && (typeof(capture) === 'undefined' || capture === fnDef[1])) { fns.splice(k, 1); target.removeEventListener(type, fnDef[0], fnDef[1]); k--; } } // remove unused info if (!fns.length) { typeListeners.splice(j, 1); } if (!typeListeners.length) { delete registeredEvents[type]; } } /** * Rate-limit the execution of a function (e.g. for events like resize and scroll). * Returns a new function, that when called repetitively, executes the original function no more than once every delay milliseconds. * (based on https://remysharp.com/2010/07/21/throttling-function-calls) * * throttle(fn [, threshhold] [, trailing] [, scope]) * * @param fn function; original function to call * @param threshhold int; optional; delay (ms) - execute fn no more than once every delay milliseconds; default is 250 * @param trailing boolean; optional; execute fn after the calls stopped; default is true * @param scope object; optional; instance the function should be applied to * @returns {Function} */ function throttle(fn, threshhold, trailing, scope) { // prepare arguments threshhold = threshhold || 250; trailing = typeof(trailing) === 'undefined' ? true:trailing; scope = scope || this; var last, deferTimer = null; return function () { var now = +new Date(), args = arguments; if (last && now < last + threshhold) { if (trailing) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(scope, args); }, threshhold); } } else { last = now; clearTimeout(deferTimer); fn.apply(scope, args); } }; } /** * Coalesce multiple sequential calls into a single execution at either the beginning or end (e.g. for events like keydown). * Returns a new function, that when called repetitively, executes the original function just once per “bunch” of calls. * * debounce(fn [, pause] [, beginning] [, scope]) * * @param fn function; original function to call * @param pause int; optional; min pause (ms) between bunches of calls; default is 250 * @param beginning boolean; execute at the beginning of the call-bunch; default is false * @param scope object; optional; instance the function should be applied to * @returns {Function} */ function debounce(fn, pause, beginning, scope) { // prepare arguments pause = pause || 250; scope = scope || this; var last, pauseTimer = null; return function () { var now = +new Date(), args = arguments; if (!beginning) { // defer a possible function call clearTimeout(pauseTimer); pauseTimer = setTimeout(function () { fn.apply(scope, args); }, pause); } else if (!last || now > last + pause) { fn.apply(scope, args); } last = now; }; } /* --------------- api --------------- */ return { registerEvent: registerEvent, unregisterEvent: unregisterEvent, throttle: throttle, debounce: debounce }; })); (function (root, factory) { if (typeof define === 'function' && define.amd) { define('me-tools',[ 'meTools.fn.variable', 'meTools.fn.element', 'meTools.fn.event' ], factory); } else if(typeof exports === 'object') { var fnVariable = require('./fn/variable'), fnElement = require('./fn/element'), fnEvent = require('./fn/event'); if (typeof module === 'object') { module.exports = factory(fnVariable, fnElement, fnEvent); } else { exports.meTools = factory(fnVariable, fnElement, fnEvent); } } else { var meTools = root.meTools; root.meTools = factory(meTools.fn.variable, meTools.fn.element, meTools.fn.event); for (var i in meTools) { root.meTools[i] = meTools[i]; } } }(this, function (fnVariable, fnElement, fnEvent) { var api = {}; for (var i in arguments) { for (var j in arguments[i]) { api[j] = arguments[i][j]; } } return api; })); (function (root, factory) { if (typeof define === 'function' && define.amd) { define('me-lock-view',[], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.meLockView = factory(); } }(this, function () { 'use strict'; /** * me-lock-view - A utility script to "lock" the main content of the page to prevent scrolling of the content in the * background if you, for instance, open a modal dialog on top of the page * * @link https://github.com/meibegger/me-lock-view * @license MIT */ var /* --------------- settings --------------- */ // name of the attribute set on an element to mark it as the view-wrapper viewAttribute = 'data-me-view', // value set to the view-attribute if the view is locked lockValue = 'locked', // value set to the view-attribute if the view isn't locked unlockValue = '', /* --------------- variables --------------- */ // remember how many "open" locks exist openLocks = 0, // cache the body element body, // cache the documentElement documentElement, // cache the view-wrapper viewWrapper, // before-lock subscriptions beforeLockSubscriptions = {}, afterUnlockSubscriptions = {} ; /* --------------- functions --------------- */ /** * Subscribe a function to be called before locking the screen * @param id String; id of the fn - used for unsubscribing * @param fn Function; fn(windowScrollLeft, windowScrollTop) called before locking the screen */ function subscribeBeforeLock(id, fn) { beforeLockSubscriptions[id] = fn; } /** * Subscribe a function to be called after unlocking the screen * @param id String; id of the fn - used for unsubscribing * @param fn Function; fn(windowScrollLeft, windowScrollTop) called after unlocking the screen */ function subscribeAfterUnlock(id, fn) { afterUnlockSubscriptions[id] = fn; } /** * Lock the view */ function lock() { if (viewWrapper) { if (!openLocks) { // view is not locked yet // get the current scroll values var scrollLeft = body.scrollLeft || documentElement.scrollLeft, scrollTop = body.scrollTop || documentElement.scrollTop; // call the subscribed functions for (var id in beforeLockSubscriptions) { beforeLockSubscriptions[id](scrollLeft, scrollTop); } // mark the view-wrapper as locked viewWrapper.setAttribute(viewAttribute, lockValue); // scroll the view-wrapper (instead of the body) viewWrapper.scrollTop = scrollTop; viewWrapper.scrollLeft = scrollLeft; // scroll the body to the upper left window.scrollTo(0, 0); } // remember the lock request openLocks++; } } /** * Unlock the view * @param real bool; optional; default true; if false, only remove the lock from the count, but keep the view locked */ function unlock(real) { if (viewWrapper) { if (typeof real === 'undefined') { real = true; } if (real && openLocks === 1) { // last unlock request // get the current scroll values var scrollLeft = viewWrapper.scrollLeft, scrollTop = viewWrapper.scrollTop; // mark the view-wrapper as unlocked viewWrapper.setAttribute(viewAttribute, unlockValue); // reset the scroll ot the view-wrapper viewWrapper.scrollTop = 0; viewWrapper.scrollLeft = 0; // scroll the body to the initial scroll position window.scrollTo(scrollLeft, scrollTop); // call the subscribed functions for (var id in afterUnlockSubscriptions) { afterUnlockSubscriptions[id](scrollLeft, scrollTop); } } // remember the unlock request if (openLocks) { openLocks--; } } } function isLocked() { return !!openLocks; } /* --------------- initialization --------------- */ function init() { // get the elements holding the document scroll body = document.body; documentElement = document.documentElement; // get the view wrapper viewWrapper = document.querySelector('[' + viewAttribute + ']'); if (!viewWrapper) { console.error('meLockView: view-wrapper not found'); } } // initialize the utility as soon as the document has finished loading. We can now access the DOM elements. if (document.readyState !== 'loading') { init(); } else { window.addEventListener('DOMContentLoaded', function loaded() { window.removeEventListener('DOMContentLoaded', loaded); init(); }); } /* --------------- api --------------- */ return { lock: lock, unlock: unlock, isLocked: isLocked, subscribeBeforeLock: subscribeBeforeLock, subscribeAfterUnlock: subscribeAfterUnlock }; })); /** * Uses classList - possibly use a polyfill for older browsers (http://caniuse.com/#feat=classlist) * Uses animationFrame - possibly use a polyfill for older browsers (http://caniuse.com/#feat=requestanimationframe) */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define('me-show-transition',['me-tools'], factory); } else if (typeof exports === 'object') { var meTools = require('me-tools'); if (typeof module === 'object') { module.exports = factory(meTools); } else { exports.meShowTransition = factory(meTools); } } else { root.meShowTransition = factory(root.meTools); } }(this, function (meTools) { var /* --------------- settings --------------- */ defaultOptions = { callbacks: { // false or fn(params); params = {container: CONTAINER,immediate:BOOL (immediate show/hide call - no transition)} beforeShow: false, beforeShowTransition: false, afterShowTransition: false, afterShow: false, beforeHide: false, beforeHideTransition: false, afterHideTransition: false, afterHide: false }, transitionEndElement: false, // element to listen to the transitionend event on (default is the container); use this if you use transitions on more than 1 element on show/hide to define the element which ends the transitions ignoreChildTransitions: false, // transitionEnd event bubbles - only listen to transitionEnd directly on the container (or transitionEndElement) transitionMaxTime: 500, // ms; timeout to end the show/hide transition states in case the transitionEnd event doesn't fire; set to 0 to not support transition indicators: { // classes added to mark states shown: 'me-shown', // set to the container as long as it is shown show: 'me-show', // set to the container during the show-transition hide: 'me-hide' // set to the container during the hide-transition } } ; /* --------------- meShowTransition --------------- */ /** * Create a new instance * * meShowTransition(container [,show] [,options]) * * @param container mixed; id or element; the container to show/hide * @param show boolean; optional; show the container immediately (without transitions) onInit; default is false * @param options object; optional; overwrite the default options */ function meShowTransition(container, show, options) { var that = this; // prepare arguments if (typeof(show) !== 'boolean') { options = show; show = false; } // init container var containerElement = container && meTools.getElementById(container); if (!containerElement) { throw new Error('meShowTransition: Container element not found'); } // merge options initProperties.call(that).options = meTools.mergeObjects(defaultOptions, options); // prepare container that.container = containerElement; if (show) { this.show(true); } else { this.hide(true); } } /* --------------- private functions --------------- */ function initProperties() { var that = this; that.options = {}; that.container = null; that.showTransitionStartAnimation = null; that.showTransitionEndTimeout = null; that.hideTransitionStartAnimation = null; that.hideTransitionEndTimeout = null; that.showing = false; that.hiding = false; that.hidden = false; return that; } function markShown() { var that = this; that.container.classList.add(that.options.indicators.shown); that.container.setAttribute('aria-hidden', 'false'); return that; } function markHidden() { var that = this; that.container.classList.remove(that.options.indicators.shown); that.container.setAttribute('aria-hidden', 'true'); return that; } function showEnd(immediate) { // end of show immediate = immediate || false; var that = this, afterShowFn = that.options.callbacks.afterShow; if (afterShowFn) { afterShowFn({ container: that.container, immediate: immediate }); } that.showing = false; return that; } function hideEnd(immediate) { // end of hide immediate = immediate || false; var that = this, container = that.container, afterHideFn = that.options.callbacks.afterHide; // hide container container.style.display = 'none'; that.hiding = false; that.hidden = true; // mark as hidden markHidden.call(that); if (afterHideFn) { afterHideFn({ container: container, immediate: immediate }); } return that; } function showTransitionEnd() { var that = this, options = that.options, container = that.container, afterTransitionFn = options.callbacks.afterShowTransition, transitionEndElement = that.options.transitionEndElement ; // clear listeners window.cancelAnimationFrame(that.showTransitionStartAnimation); clearTimeout(that.showTransitionEndTimeout); meTools.unregisterEvent(that, transitionEndElement, 'webkitTransitionEnd'); meTools.unregisterEvent(that, transitionEndElement, 'transitionend'); // after transition if (afterTransitionFn) { afterTransitionFn({ container: container, immediate: false }); } container.classList.remove(options.indicators.show); showEnd.call(that); return that; } function hideTransitionEnd() { var that = this, options = that.options, container = that.container, afterTransitionFn = options.callbacks.afterHideTransition, transitionEndElement = that.options.transitionEndElement ; // clear listeners window.cancelAnimationFrame(that.hideTransitionStartAnimation); clearTimeout(that.hideTransitionEndTimeout); meTools.unregisterEvent(that, transitionEndElement, 'webkitTransitionEnd'); meTools.unregisterEvent(that, transitionEndElement, 'transitionend'); // after transition if (afterTransitionFn) { afterTransitionFn({ container: container, immediate: false }); } container.classList.remove(options.indicators.hide); hideEnd.call(that); return that; } /* --------------- prototype --------------- */ /** * Start showing the container * @param immediate bool; optional; show immediately * @returns {meShowTransition} */ meShowTransition.prototype.show = function (immediate) { var that = this, options = that.options, container = that.container, transitionEndElement = options.transitionEndElement || container; function _showTransitionEnd(event) { if (!options.ignoreChildTransitions || !event || !event.target || event.target === transitionEndElement) { showTransitionEnd.call(that); } } if (immediate || that.canShow()) { var callbacks = options.callbacks, beforeShowFn = callbacks.beforeShow, beforeTransitionFn = callbacks.beforeShowTransition, indicators = options.indicators; // remember that we are showing that.showing = true; // end possible hide-transition if (that.hiding) { hideTransitionEnd.call(that); } that.hidden = false; // before show if (beforeShowFn) { beforeShowFn({ container: container, immediate: immediate }); } // show container container.style.display = 'block'; if (!immediate && options.transitionMaxTime) { // transition // init transition-end-handling meTools.registerEvent(that, transitionEndElement, 'webkitTransitionEnd', _showTransitionEnd); meTools.registerEvent(that, transitionEndElement, 'transitionend', _showTransitionEnd); // set a transition-timeout in case the end-event doesn't fire that.showTransitionEndTimeout = setTimeout(_showTransitionEnd, options.transitionMaxTime); that.showTransitionStartAnimation = window.requestAnimationFrame(function () { // wait 2 ticks for the browser to apply the visibility that.showTransitionStartAnimation = window.requestAnimationFrame(function () { // before transition if (beforeTransitionFn) { beforeTransitionFn({ container: container, immediate: false }); } // mark as shown markShown.call(that); // start show transition and listeners container.classList.add(indicators.show); }); }); } else { // immediate show markShown.call(that); showEnd.call(that, immediate); } } return that; }; /** * Start hiding the container * @param immediate bool; optional; hide immediately * @returns {meShowTransition} */ meShowTransition.prototype.hide = function (immediate) { var that = this, options = that.options, container = that.container, transitionEndElement = options.transitionEndElement || container; function _hideTransitionEnd(event) { if (!options.ignoreChildTransitions || !event || !event.target || event.target === transitionEndElement) { hideTransitionEnd.call(that); } } if (immediate || !that.canShow()) { var callbacks = options.callbacks, beforeHideFn = callbacks.beforeHide, beforeTransitionFn = callbacks.beforeHideTransition, indicators = options.indicators; // remember that we are showing that.hiding = true; // end possible show-transition if (that.showing) { showTransitionEnd.call(that); } // before hide if (beforeHideFn) { beforeHideFn({ container: container, immediate: immediate }); } if (!immediate && options.transitionMaxTime) { // transition // init transition-end-handling meTools.registerEvent(that, transitionEndElement, 'webkitTransitionEnd', _hideTransitionEnd); meTools.registerEvent(that, transitionEndElement, 'transitionend', _hideTransitionEnd); // set a transition-timeout in case the end-event doesn't fire that.hideTransitionEndTimeout = setTimeout(_hideTransitionEnd, options.transitionMaxTime); that.hideTransitionStartAnimation = window.requestAnimationFrame(function () { // wait 2 ticks for the browser to apply beforeHideFn changes that.hideTransitionStartAnimation = window.requestAnimationFrame(function () { // before transition if (beforeTransitionFn) { beforeTransitionFn({ container: container, immediate: false }); } // start show transition and listeners container.classList.add(indicators.hide); }); }); } else { // immediate hide hideEnd.call(that); } } return that; }; /** * @returns {boolean} true if the component is in the process of hiding or hidden */ meShowTransition.prototype.canShow = function () { return (this.hiding || this.hidden); }; /** * Destroy the instance * @returns {null} */ meShowTransition.prototype.destroy = function () { var that = this, container = that.container, indicators = that.options.indicators ; // clear listeners clearTimeout(that.showTransitionEndTimeout); clearTimeout(that.hideTransitionEndTimeout); meTools.unregisterEvent(that); // remove added classes for (var i in indicators) { container.classList.remove(indicators[i]); } // reset properties and remove all references initProperties.call(that); return null; }; return meShowTransition; })); ;(function(root, factory) { if (typeof define === 'function' && define.amd) { define('me-trap-focus',['me-tools'], factory); } else if (typeof exports === 'object') { module.exports = factory(meTools); } else { root.meTrapFocus = factory(meTools); } } (this, function(meTools) { /** * me-trap-focus - A small utility script to trap the focus within a container element * * @link https://github.com/meibegger/me-trap-focus * @license MIT */ var /* --------------- constants --------------- */ KEY_TAB = 9, /* --------------- settings --------------- */ defaultOptions = { focusableSelector: 'a,frame,iframe,input:not([type=hidden]),select,textarea,button,*[tabindex]', // selector for elements which are focusable taboutIndicator: '.me-tabout' // selector for an optional element placed before the 1st or after the last tabable element to prevent tabbing out of the page directly to the browser-window (e.g. placed after an iframe as last tabable element) } ; /* --------------- meTrapFocus --------------- */ /** * Create a new instance * @param container mixed; id or element; the container in which the focus should be maintained * @param options object; optional; overwrite the default options */ function meTrapFocus(container, options) { var that = this; // check arguments var containerElement = container && meTools.getElementById(container); if (!containerElement) { throw new Error('meTrapFocus: Container element not found'); } // merge options initProperties.call(that).options = meTools.mergeObjects(defaultOptions, options); // prepare container that.container = containerElement; if (!containerElement.getAttribute('tabindex')) { // add tabindex to the container, so that it can get focus onClick and receives tab-events as target (to prevent tabbing out) containerElement.setAttribute('tabindex', '-1'); } meTools.registerEvent(that, containerElement, 'keydown', function (event) { handleKeyboard.call(that, event); }); fetchFocusables.call(that); } /* --------------- private functions --------------- */ function initProperties() { var that = this; that.options = {}; that.container = null; that.focusables = []; // all possibly focusable elements ordered by tabindex return that; } function handleKeyboard(event) { if (!event.ctrlKey && !event.altKey) { var code = (event.keyCode ? event.keyCode : event.which); if (code == KEY_TAB) { // tab-loop var that = this, taboutIndicator = that.options.taboutIndicator, focusables = that.focusables, tabables; if (event.shiftKey) { // back-tab tabables = getFilteredFocusables.call(that,-1); if (tabables[tabables[0].matches(taboutIndicator) ? 1 : 0] === event.target || // back-tab on first element -> focus last element focusables.indexOf(event.target) < focusables.indexOf(tabables[0]) || event.target===that.container) { focusLast.call(that,tabables); event.preventDefault(); } } else { // tab tabables = getFilteredFocusables.call(that,1); if (tabables[tabables.length - (tabables[tabables.length - 1].matches(taboutIndicator) ? 2 : 1)] === event.target || // tab on last element -> focus first element focusables.indexOf(event.target) > focusables.indexOf(tabables[tabables.length-1])) { focusFirst.call(that,tabables); event.preventDefault(); } } } } } /** * Get all radio-buttons belonging to a radio-button's group * @param radioButton * @returns [] */ function getRadioGroup(radioButton) { // get the form for the radiobutton var form = meTools.getAncestors(radioButton, 'form', true) || // radiobutton is contained in a form document, name = radioButton.getAttribute('name'); return [].slice.call(form.querySelectorAll('input[type="radio"][name="' + name + '"]')); } function fetchFocusables () { var that = this, options = that.options, _taboutFocus = function (event) { taboutFocus.call(that, event); }; that.focusables = orderFocusables(that.container.querySelectorAll(options.focusableSelector)); for (var i = 0; i < that.focusables.length; i++) { var element = that.focusables[i]; if (element.matches(options.taboutIndicator)) { meTools.unregisterEvent(that, element, 'focus'); // unregister old event meTools.registerEvent(that, element, 'focus', _taboutFocus); } } return that; } function orderFocusables (focusables) { var byTabindex = [], ordered = []; for (var i = 0; i < focusables.length; i++) { var focusable = focusables[i], tabindex = Math.max(0, focusable.getAttribute('tabindex') || 0); byTabindex[tabindex] = byTabindex[tabindex] || []; byTabindex[tabindex].push(focusable); } for (var j in byTabindex) { for (var k in byTabindex[j]) { ordered.push(byTabindex[j][k]); } } return ordered; } /** * Return not disabled, tabindex!=-1, visible, tabable radio ordered by the specified tab-direction * @param orderByTabindex int; optional; tab-direction (-1 or 1); default is 1 * @returns {Array} */ function getFilteredFocusables (orderByTabindex) { // prepare argument orderByTabindex = typeof(orderByTabindex) === 'undefined' ? 1 : orderByTabindex; var that = this, focusables = that.focusables, filtered = [], doneRadios = []; // already processed radio-buttons // remove all elements which are not tabable for (var i = 0; i < focusables.length; i++) { var focusable = focusables[i], fitting = null, tabindex = focusable.getAttribute('tabindex') || 0; if (focusable.matches(':not([disabled])') && focusable.matches(':not([tabindex="-1"])') && (focusable.offsetWidth || focusable.offsetHeight)) { // not disabled, tabindex!=-1 & visible if (focusable.matches('input[type="radio"]')) { // remove all radio buttons which are not tabable if (doneRadios.indexOf(focusable) === -1) { // group of this radio not processed yet // get radio-group var radioGroup = getRadioGroup.call(that, focusable), focusableRadio = null; doneRadios = doneRadios.concat(radioGroup); // get tabable radios of the group (checked or first&last of group) for (var j = 0; j < radioGroup.length; j++) { var radio = radioGroup[j]; if (radio.checked) { focusableRadio = radio; break; } } if (!focusableRadio) { focusableRadio = orderByTabindex === -1 ? radioGroup[radioGroup.length-1] : radioGroup[0]; // default is tabable in tab-direction!!! } fitting = focusableRadio; } } else { fitting = focusable; } } if (fitting) { filtered.push(fitting); } } return filtered; } function focusFirst(tabables) { var that = this, taboutIndicator = that.options.taboutIndicator, focusNext = tabables[0]; if (focusNext.matches(taboutIndicator)) { focusNext = tabables[1]; } if (focusNext.matches('iframe')) setTimeout(function () { focusNext.contentWindow.focus(); }, 100); else { focusNext.focus(); } } function focusLast(tabables) { var that = this, taboutIndicator = that.options.taboutIndicator, focusNext = tabables[tabables.length - 1]; if (focusNext.matches(taboutIndicator)) { focusNext = tabables[tabables.length - 2]; } if (focusNext.matches('iframe')) setTimeout(function () { focusNext.contentWindow.focus(); }, 100); else { focusNext.focus(); } } function taboutFocus(event) { var that = this, element = event.target, tabableTab = getFilteredFocusables.call(that,1), tabableBackTab = getFilteredFocusables.call(that,-1); if (element == tabableBackTab[0]) { // focus on start-focus-out -> focus last element focusLast.call(that,tabableBackTab); } else if (element == tabableTab[tabableTab.length - 1]) { // focus on end-focus-out -> focus first element focusFirst.call(that,tabableTab); } } /* --------------- prototype --------------- */ /** * Update the list of focusable elements. Call this, if the focusable elements within the container change (elements are added or removed) * @returns this */ meTrapFocus.prototype.update = function () { return fetchFocusables.call(this); }; /** * Get all possibly focusable elements * @returns {[]} DOM-elements */ meTrapFocus.prototype.getFocusables = function () { return meTools.copyValues(this.focusables, false); }; /** * Get all elements reachable by (back-) tab * @param backTab boolean; optional; default is false * @returns {[]} DOM-elements */ meTrapFocus.prototype.getTabable = function (backTab) { return meTools.copyValues(backTab ? getFilteredFocusables.call(this,-1) : getFilteredFocusables.call(this,1), false); }; /** * Destroy the instance * @returns {null} */ meTrapFocus.prototype.destroy = function () { var that = this; initProperties.call(that); meTools.unregisterEvent(that); return null; }; return meTrapFocus; })); (function (root, factory) { if (typeof define === 'function' && define.amd) { define('meDialog',['me-tools', 'me-lock-view', 'me-show-transition', 'me-trap-focus'], factory); } else if (typeof exports === 'object') { var meTools = require('me-tools'), meLockView = require('me-lock-view'), meShowTransition = require('me-show-transition'), meTrapFocus = require('me-trap-focus'); if (typeof module === 'object') { module.exports = factory(meTools, meLockView, meShowTransition, meTrapFocus); } else { exports.meDialog = factory(meTools, meLockView, meShowTransition, meTrapFocus); } } else { root.meDialog = factory(root.meTools, root.meLockView, root.meShowTransition, root.meTrapFocus); } }(this, function (meTools, meLockView, meShowTransition, meTrapFocus) { var /* --------------- constants --------------- */ NAMESPACE = 'meDialog', // code of the escape key KEY_ESCAPE = 27, // if this attribute is set on a dialog container, the dialog will be initialized automatically AUTO_INIT = "data-me-dialog", // if this attribute is set on an element with the id of the dialog container as value, click on the element will show the dialog (data-me-show-dialog="DIALOG-ID") TRIGGER_SHOW = "data-me-show-dialog", /* --------------- settings --------------- */ defaultOptions = { // set if the dialog is modal; default is true modal: true, // only relevant if modal=true // - selector identifying the backdrop element within the dialog, OR // - backdrop element backdrop: '.me-backdrop', // only relevant if modal=true // close the dialog on click on the backdrop; o // Note: if true, the behaviour is not according to the WAI ARIA best practices! closeOnBackdrop: false, // "the label should briefly and adequately describe the dialogs use" // - selector identifying the labeling element within the dialog, OR // - label text, OR // - labelling element label: '.me-label', // selector identifying the close button(s) within the dialog closeSelector: '.me-close', // class added to the close button, if the (external) backdrop should not be hidden on close/click keepBackdropIndicator: 'me-keep-backdrop', // the dialog requires confirmation (like a js confirm box), so ESC will not close the dialog requireConfirm: false, // attribute set on the container with the view properties passed onShow as value; use this to set states for a specific view of the dialog (e.g. show/hide elements etc.) viewPropsAttribute: 'data-view-props', // custom action handlers; false for automatic handling or fn customHandler: { // fn(container) returning an element within the dialog to focus; or false to use the default focus: false }, // false or fn(params); params = {container: CONTAINER,backdrop:BACKDROP,trigger:TRIGGER,immediate:BOOL (immediate show/hide call - no transition)} callbacks: { beforeShow: false, beforeShowTransition: false, afterShowTransition: false, afterShow: false, beforeHide: false, beforeHideTransition: false, afterHideTransition: false, afterHide: false }, // see meLockView lockView: true, // prefix for generated IDs idPrefix: 'id-' } ; /* --------------- meDialog --------------- */ /** * Create a new instance * @param container mixed; required; element or element-id of the dialog element * @param options object; optional; overwrite the default settings */ function meDialog(container, options) { var that = this; // merge options initProperties.call(that).options = meTools.mergeObjects(defaultOptions, options); initDialog.call(that, container); } /* --------------- private functions --------------- */ /* setup */ function initProperties() { var that = this; that.shown = false; // true from beginning of show until beginning of hide that.options = {}; that.container = null; that.backdrop = null; that.trigger = null; that.meTrapFocus = null; that.mainShowTransition = null; that.backdropShowTransition = null; that.keepBackdrop = false; return that; } function initDialog(container) { var that = this, options = that.options; // check arguments that.container = initContainer.call(that, container); if (options.modal) { that.backdrop = initBackdrop.call(that); } setLabel.call(that); initCloseBtn.call(that); initFocus.call(that); initShow.call(that); initTriggers.call(that); return that; } function initContainer(container) { // get element var that = this, containerElement = meTools.getElementById(container); if (!containerElement) { throw NAMESPACE + ': Container element not found'; } // set role containerElement.setAttribute('role', 'dialog'); // register events meTools.registerEvent(that, containerElement, 'click', function (event) { handleClick.call(that, event); }); meTools.registerEvent(that, containerElement, 'keydown', function (event) { handleKeyboard.call(that, event); }); meTools.registerEvent(that, containerElement, 'showdialog', function (event) { triggeredShow.call(that, event.detail); }); meTools.registerEvent(that, containerElement, 'hidedialog', function (event) { triggeredHide.call(that); }); return containerElement; } function initBackdrop() { var that = this, options = that.options, container = that.container, backdropDef = options.backdrop, backdropElement = false; if (typeof(backdropDef) === 'string') { backdropElement = container.querySelector(backdropDef); } else if (backdropDef && typeof(backdropDef) === 'object' && typeof(backdropDef.tagName) !== 'undefined') { backdropElement = backdropDef; } if (!backdropElement) { throw NAMESPACE + ': Backdrop element not found'; } backdropElement.setAttribute('tabindex', '-1'); // "Set the tabindex of the backdrop element to tabindex="-1" to prevent it from receiving focus via a keyboard event or mouse click." meTools.registerEvent(that, backdropElement, 'click', function (event) { handleBackdropClick.call(that, event.target); }); // set meShowTransition on the backdrop if it is not contained in the main dialog container if (!meTools.isParent(that.container, backdropElement)) { // build meShowTransition options var _options = meTools.copyValues(that.options); _options.callbacks = {}; // remove all callbacks if (backdropElement.data && backdropElement.data[NAMESPACE] && backdropElement.data[NAMESPACE].transition) { // backdrop already has a transition assigned (for instance if multiple dialogs use the same backdrop) that.backdropShowTransition = backdropElement.data[NAMESPACE].transition; // link the existing transition to the dialog instance backdropElement.data[NAMESPACE].assignedTransitions++; // remember the new linkage } else { // create transition instance that.backdropShowTransition = new meShowTransition(backdropElement, _options); // save transition instance backdropElement.data = backdropElement.data || {}; backdropElement.data[NAMESPACE] = backdropElement.data[NAMESPACE] || {}; backdropElement.data[NAMESPACE].transition = that.backdropShowTransition; backdropElement.data[NAMESPACE].assignedTransitions = 1; } } return backdropElement; } function setLabel() { var that = this, options = that.options, container = that.container, labelDef = options.label, labelElement = false; if (typeof(labelDef) === 'string') { labelElement = container.querySelector(labelDef); } else if (typeof(labelDef) === 'object' && typeof(labelDef.tagName) !== 'undefined') { labelElement = labelDef; } if (labelElement) { container.setAttribute('aria-labelledby', meTools.getId(labelElement, options.idPrefix)); } else if (typeof(labelDef) === 'string') { container.setAttribute('aria-label', labelDef); } else { throw NAMESPACE + ': Label element not found'; } return that; } function initCloseBtn() { var that = this, closeButtons = that.container.querySelectorAll(that.options.closeSelector), _hide = function () { if (this.className.indexOf(that.options.keepBackdropIndicator) !== -1) { that.keepBackdrop = true; } hide.call(that); }; for (var i = 0; i < closeButtons.length; i++) { meTools.registerEvent(that, closeButtons[i], 'click', _hide); } return that; } function initFocus() { var that = this, container = that.container; that.meTrapFocus = new meTrapFocus(container, that.options); // add tabindex to the dialog to be able to focus it if there is no focusable element inside if (!container.hasAttribute('tabindex')) { container.setAttribute('data-tabindexed', 'true'); container.setAttribute('tabindex', '-1'); } return that; } function initShow() { var that = this, options = that.options, callbacks = options.callbacks, // build meShowTransition options _options = meTools.copyValues(options); _options.callbacks = {}; // remove all callbacks /* adjust callbacks */ // call user-defined callback function customCallback(data, name) { if (callbacks[name]) { // add custom properties data.backdrop = that.backdrop; data.trigger = that.trigger; callbacks[name](data); } } function passCustomCallback(name) { return function (data) { customCallback(data, name); }; } function beforeShow(data) { // call user-defined beforeShow customCallback(data, 'beforeShow'); // show the backdrop if (that.backdropShowTransition) { that.backdropShowTransition.show(data.immediate); } // lock the view if (options.lockView) { meLockView.lock(); } // set wai-aria attributes if (that.trigger) { that.trigger.setAttribute('aria-expanded', 'true'); } that.container.setAttribute('aria-hidden', 'false'); } function afterShow(data) { // fetch the focusable elements that.meTrapFocus.update(); // set the focus inside of the dialog setFocus.call(that); // call user-defined beforeShowTransition customCallback(data, 'afterShow'); } function beforeHide(data) { // call user-defined beforeHide customCallback(data, 'beforeHide'); // hide the backdrop if (that.backdropShowTransition && !that.keepBackdrop) { that.backdropShowTransition.hide(data.immediate); } // focus the trigger if (that.trigger) { // set wai-aria attributes that.trigger.setAttribute('aria-expanded', 'false'); unsetTrigger.call(focusTrigger.call(that)); } } function afterHide(data) { // clear the view specific properties clearViewProps.call(that); // unlock the view if (options.lockView) { meLockView.unlock(!that.keepBackdrop); } that.keepBackdrop = false; // set wai-aria attributes that.container.setAttribute('aria-hidden', 'true'); // call user-defined afterHide customCallback(data, 'afterHide'); } _options.callbacks = { // false or fn(params); params = {container: CONTAINER,backdrop:UNDERLAY,trigger:TRIGGER,immediate:BOOL (immediate show/hide call - no transition)} beforeShow: beforeShow, beforeShowTransition: passCustomCallback('beforeShowTransition'), afterShowTransition: passCustomCallback('afterShowTransition'), afterShow: afterShow, beforeHide: beforeHide, beforeHideTransition: passCustomCallback('beforeHideTransition'), afterHideTransition: passCustomCallback('afterHideTransition'), afterHide: afterHide }; // init meShowTransition that.mainShowTransition = new meShowTransition(that.container, _options); return that; } function initTriggers() { var that = this, dialogId = meTools.getId(that.container, that.options.idPrefix), triggers = document.querySelectorAll('[' + TRIGGER_SHOW + '="' + dialogId + '"]'); for (var i = 0; i < triggers.length; i++) { var trigger = triggers[i]; trigger.setAttribute('aria-controls', dialogId); trigger.setAttribute('aria-expanded', 'false'); meTools.registerEvent(that, trigger, 'click', that.show.bind(that, trigger)); } return that; } /* display */ /** * * @param immediate Bool; show immediately (without transition) * @param viewProps * @returns {show} */ function show(immediate, viewProps) { addViewProps.call(this, viewProps); this.mainShowTransition.show(immediate); return this; } function hide(immediate) { this.mainShowTransition.hide(immediate); return this; } function addViewProps(viewProps) { var that = this; if (viewProps) { that.container.setAttribute(that.options.viewPropsAttribute,viewProps); } return that; } function clearViewProps() { var that = this; that.container.removeAttribute(that.options.viewPropsAttribute); return that; } /* events */ function triggeredShow(detail) { this.show(detail.trigger); } function triggeredHide() { this.hide(); } function handleClick(event) { var that = this, options = that.options; } function handleKeyboard(event) { if (!event.ctrlKey && !event.altKey) { var code = (event.keyCode ? event.keyCode : event.which); if (!this.options.requireConfirm && code == KEY_ESCAPE) { hide.call(this); event.stopPropagation(); } } } function handleBackdropClick(target) { var that = this; if (that.backdrop == target) { if (that.options.closeOnBackdrop) { hide.call(that); } else { that.container.focus(); } } return that; } /* handle trigger element */ function setTrigger(trigger) { this.trigger = trigger; return this; } function focusTrigger() { var that = this; if (that.trigger) { that.trigger.focus(); } return that; } function unsetTrigger() { this.trigger = null; return this; } /* focus */ function setFocus() { var that = this, options = that.options, getFocusElement = options.customHandler.focus, focus = null, focusables = that.meTrapFocus.getTabable(); if (typeof getFocusElement === 'function') { focus = getFocusElement(that.container); } if (!focus) { for (var i = 0; i < focusables.length; i++) { if (!focusables[i].matches(options.closeSelector)) { focus = focusables[i]; break; } } } if (!focus && focusables.length) { focus = focusables[0]; } (focus || (focusables.length ? focusables[0] : that.container)).focus(); } /* --------------- prototype --------------- */ /** * Show the dialog * @param trigger DOM-element; optional; the element, that triggered the show * @param immediate Bool; optional; default is false; show immediately (without transition) * @param viewProps String; optional; string to add to the container in the viewPropsAttribute * @param event eventObject; optional; * @returns {meDialog} */ meDialog.prototype.show = function () { var that = this, trigger, immediate, viewProps; for (var i=0; i<arguments.length; i++) { var argument = arguments[i], type = typeof argument; if (type === 'boolean') { immediate = argument; } else if (type === 'string') { viewProps = argument; } else if (type === 'object') { if (argument.tagName) { trigger = argument; } else if (argument.preventDefault) { argument.preventDefault(); } } } if (trigger) { setTrigger.call(that, trigger); } return show.call(that, immediate, viewProps); }; /** * Hide the dialog * @returns {meDialog} */ meDialog.prototype.hide = function () { return hide.call(this); }; /** * Update the list of focusable elements in the dialog. * Call this function, if elements were added or removed while the dialog is shown * @returns {meDialog} */ meDialog.prototype.update = function () { this.meTrapFocus.update(); return this; }; /** * @returns {boolean} true if the component is in the process of hiding or hidden */ meDialog.prototype.canShow = function () { return this.mainShowTransition.canShow(); }; /** * Destroy the widget * @returns {null} */ meDialog.prototype.destroy = function () { var that = this, container = that.container; container.removeAttribute('role'); container.removeAttribute('aria-hidden'); container.removeAttribute('aria-labelledby'); container.removeAttribute('aria-label'); that.backdrop.removeAttribute('tabindex'); if (container.getAttribute('data-tabindexed')) { container.removeAttribute('data-tabindexed'); container.removeAttribute('tabindex'); } if (that.trigger) { that.trigger.removeAttribute('aria-expanded'); } meLockView.unlock(!that.keepBackdrop); meTools.unregisterEvent(that); that.meTrapFocus.destroy(); that.mainShowTransition.destroy(); if (that.backdropShowTransition) { if (that.backdrop.data[NAMESPACE].assignedTransitions > 1) { // an other dialog still depends on the the backdrop transition that.backdrop.data[NAMESPACE].assignedTransitions--; // remove the linkage } else { that.backdropShowTransition.destroy(); // destroy the transition instance } } initProperties.call(that); return null; }; /* --------------- automatic initialization --------------- */ /** * Auto init all dialogs with the attribute AUTO_INIT */ function autoInit() { var dialogs = document.querySelectorAll('[' + AUTO_INIT + ']'); for (var i = 0; i < dialogs.length; i++) { new meDialog(dialogs[i]); } } // auto-initialize marked dialogs as soon as the document has finished loading. We can now access the DOM elements. if ( document.attachEvent ? document.readyState === 'complete' : document.readyState !== 'loading' ) { autoInit(); } else { window.addEventListener('DOMContentLoaded', function loaded() { window.removeEventListener('DOMContentLoaded', loaded); autoInit(); }); } /* --------------- return --------------- */ return meDialog; })); /*********************************************************************************************************************** * MATCHES * Add matches support for all IEs and others (http://caniuse.com/#feat=matchesselector) **********************************************************************************************************************/ // as described in https://developer.mozilla.org/en/docs/Web/API/Element/matches#Browser_compatibility (function(ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.msMatchesSelector || ElementPrototype.oMatchesSelector || ElementPrototype.webkitMatchesSelector || function (selector) { var $element = this , $matches = [].slice.call(document.querySelectorAll(selector)) ; return $matches.indexOf($element)!==-1; } })(Element.prototype); define("matchesPolyfill", (function (global) { return function () { var ret, fn; return ret || global.matchesPolyfill; }; }(this))); /* * classList.js: Cross-browser full element.classList implementation. * 2014-07-23 * * By Eli Grey, http://eligrey.com * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ /*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ if ("document" in self) { // Full polyfill for browsers with no classList support if (!("classList" in document.createElement("_"))) { (function (view) { "use strict"; if (!('Element' in view)) return; var classListProp = "classList" , protoProp = "prototype" , elemCtrProto = view.Element[protoProp] , objCtr = Object , strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); } , arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0 , len = this.length ; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function (type, message) { this.name = type; this.code = DOMException[type]; this.message = message; } , checkTokenAndGetIndex = function (classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR" , "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR" , "String contains an invalid character" ); } return arrIndexOf.call(classList, token); } , ClassList = function (elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class") || "") , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [] , i = 0 , len = classes.length ; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; } , classListProto = ClassList[protoProp] = [] , classListGetter = function () { return new ClassList(this); } ; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false ; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false , index ; do { token = tokens[i] + ""; index = checkTokenAndGetIndex(this, token); while (index !== -1) { this.splice(index, 1); updated = true; index = checkTokenAndGetIndex(this, token); } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, force) { token += ""; var result = this.contains(token) , method = result ? force !== true && "remove" : force !== false && "add" ; if (method) { this[method](token); } if (force === true || force === false) { return force; } else { return !result; } }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter , enumerable: true , configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(self)); } else { // There is full or partial native classList support, so just check if we need // to normalize the add/remove and toggle APIs. (function () { "use strict"; var testElement = document.createElement("_"); testElement.classList.add("c1", "c2"); // Polyfill for IE 10/11 and Firefox <26, where classList.add and // classList.remove exist but support only one argument at a time. if (!testElement.classList.contains("c2")) { var createMethod = function(method) { var original = DOMTokenList.prototype[method]; DOMTokenList.prototype[method] = function(token) { var i, len = arguments.length; for (i = 0; i < len; i++) { token = arguments[i]; original.call(this, token); } }; }; createMethod('add'); createMethod('remove'); } testElement.classList.toggle("c3", false); // Polyfill for IE 10 and Firefox <24, where classList.toggle does not // support the second argument. if (testElement.classList.contains("c3")) { var _toggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function(token, force) { if (1 in arguments && !this.contains(token) === !force) { return force; } else { return _toggle.call(this, token); } }; } testElement = null; }()); } }; define("classListPolyfill", (function (global) { return function () { var ret, fn; return ret || global.classListPolyfill; }; }(this))); /*********************************************************************************************************************** * ANIMATION FRAME * Add window.requestAnimationFrame and window.cancelAnimationFrame to all browsers **********************************************************************************************************************/ // as described in http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ (function(window) { var lastTime = 0; var vendors = ['webkit', 'moz', 'ms']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame || !window.cancelAnimationFrame) { window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } }(window)); define("animationFramePolyfill", (function (global) { return function () { var ret, fn; return ret || global.animationFramePolyfill; }; }(this))); return require('meDialog'); }));
mit
icsharpcode/WpfDesigner
WpfDesign.Designer/Tests/XamlDom/ExampleClass.cs
2807
// Copyright (c) 2019 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.Windows.Markup; namespace ICSharpCode.WpfDesign.Tests.XamlDom { [ContentProperty("StringProp")] public class ExampleClass : ISupportInitialize { internal static int nextUniqueIndex; string stringProp, otherProp, otherProp2; int uniqueIndex = nextUniqueIndex++; public ExampleClass() { TestHelperLog.Log("ctor" + Identity); } protected string Identity { get { return GetType().Name + " (" + uniqueIndex + ")"; } } void ISupportInitialize.BeginInit() { TestHelperLog.Log("BeginInit " + Identity); } void ISupportInitialize.EndInit() { TestHelperLog.Log("EndInit " + Identity); } public string StringProp { get { TestHelperLog.Log("StringProp.get " + Identity); return stringProp; } set { TestHelperLog.Log("StringProp.set to " + value + " - " + Identity); stringProp = value; } } public string OtherProp { get { TestHelperLog.Log("OtherProp.get " + Identity); return otherProp; } set { TestHelperLog.Log("OtherProp.set to " + value + " - " + Identity); otherProp = value; } } public string OtherProp2 { get { TestHelperLog.Log("OtherProp2.get " + Identity); return otherProp2; } set { TestHelperLog.Log("OtherProp2.set to " + value + " - " + Identity); otherProp2 = value; } } object objectProp; public object ObjectProp { get { TestHelperLog.Log("ObjectProp.get " + Identity); return objectProp; } set { TestHelperLog.Log("ObjectProp.set to " + value + " - " + Identity); objectProp = value; } } } }
mit
FriedBreakfast/Psi
src/TreeBase.hpp
14623
#ifndef HPP_PSI_COMPILER_TREEBASE #define HPP_PSI_COMPILER_TREEBASE #include <set> #include <boost/scoped_ptr.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_convertible.hpp> #include "ObjectBase.hpp" #include "SourceLocation.hpp" namespace Psi { namespace Compiler { class Tree; class CompileContext; template<typename T=Tree> class TreePtr : public ObjectPtr<const T> { public: TreePtr() {} explicit TreePtr(const DefaultConstructor&) {} explicit TreePtr(const T *ptr) : ObjectPtr<const T>(ptr) {} template<typename U> TreePtr(const TreePtr<U>& src) : ObjectPtr<const T>(src) {} }; template<typename T> std::size_t hash_value(const TreePtr<T>& ptr) {return boost::hash_value(ptr.get());} template<typename T> TreePtr<T> tree_from(const T *ptr) {return TreePtr<T>(ptr);} /** * Data structure for performing recursive object visiting. This stores objects * to visit in a queue and remembers previously visited objects so that nothing * is visited twice. */ template<typename T> class VisitQueue { PSI_STD::vector<T> m_queue; PSI_STD::set<T> m_visited; public: bool empty() const {return m_queue.empty();} T pop() {T x = m_queue.back(); m_queue.pop_back(); return x;} void push(const T& x) { if (m_visited.find(x) == m_visited.end()) { m_visited.insert(x); m_queue.push_back(x); } } }; /** * \brief Recursively completes a tree. */ class CompleteVisitor : public ObjectVisitorBase<CompleteVisitor> { VisitQueue<TreePtr<> > *m_queue; public: CompleteVisitor(VisitQueue<TreePtr<> > *queue) : m_queue(queue) { } template<typename T> void visit_object_ptr(const ObjectPtr<T>&) {} template<typename T> void visit_tree_ptr(const TreePtr<T>& ptr) { if (ptr) m_queue->push(ptr); } template<typename T, typename U> void visit_delayed(DelayedValue<T,U>& ptr) { boost::array<T*,1> m = {{const_cast<T*>(&ptr.get_checked())}}; visit_callback(*this, NULL, m); } }; /// \see Tree struct TreeVtable { ObjectVtable base; void (*complete) (const Tree*,VisitQueue<TreePtr<> >*); }; class Tree : public Object { friend class CompileContext; friend class Term; SourceLocation m_location; /// Disable general new operator static void* operator new (size_t); /// Disable placement new static void* operator new (size_t, void*); Tree(const TreeVtable *vptr); public: PSI_COMPILER_EXPORT static const SIVtable vtable; typedef TreeVtable VtableType; Tree(const TreeVtable *vptr, CompileContext& compile_context, const SourceLocation& location); PSI_COMPILER_EXPORT void complete() const; const SourceLocation& location() const {return m_location;} template<typename V> static void visit(V& PSI_UNUSED(v)) {} #if PSI_DEBUG void debug_print() const; #endif template<typename Derived> static void complete_impl(const Derived& self, VisitQueue<TreePtr<> >& queue) { Derived::local_complete_impl(self); boost::array<Derived*, 1> a = {{const_cast<Derived*>(&self)}}; CompleteVisitor p(&queue); visit_members(p, a); } static void local_complete_impl(const Tree&) {}; }; template<typename T> bool tree_isa(const Tree *ptr) { return ptr && si_is_a(ptr, reinterpret_cast<const SIVtable*>(&T::vtable)); } template<typename T> const T* tree_cast(const Tree *ptr) { PSI_ASSERT(tree_isa<T>(ptr)); return static_cast<const T*>(ptr); } template<typename T> const T* dyn_tree_cast(const Tree *ptr) { return tree_isa<T>(ptr) ? static_cast<const T*>(ptr) : 0; } template<typename T, typename U> bool tree_isa(const TreePtr<U>& ptr) { return tree_isa<T>(ptr.get()); } template<typename T, typename U> TreePtr<T> treeptr_cast(const TreePtr<U>& ptr) { PSI_ASSERT(tree_isa<T>(ptr)); return TreePtr<T>(static_cast<const T*>(ptr.get())); } template<typename T, typename U> TreePtr<T> dyn_treeptr_cast(const TreePtr<U>& ptr) { return tree_isa<T>(ptr) ? TreePtr<T>(static_cast<const T*>(ptr.get())) : TreePtr<T>(); } template<typename Derived> struct TreeWrapper : NonConstructible { static void complete(const Tree *self, VisitQueue<TreePtr<> > *queue) { Derived::complete_impl(*static_cast<const Derived*>(self), *queue); } }; #define PSI_COMPILER_TREE(derived,name,super) { \ PSI_COMPILER_OBJECT(derived,name,super), \ &::Psi::Compiler::TreeWrapper<derived>::complete \ } #define PSI_COMPILER_TREE_ABSTRACT(name,super) PSI_COMPILER_SI_ABSTRACT(name,&super::vtable) class DelayedEvaluation; struct DelayedEvaluationVtable { ObjectVtable base; void (*evaluate) (void *result, DelayedEvaluation *self, void *arg); }; class DelayedEvaluation : public Object { public: enum CallbackState { state_ready, state_running, state_finished, state_failed }; private: SourceLocation m_location; CallbackState m_state; protected: void evaluate(void *ptr, void *arg); public: typedef DelayedEvaluationVtable VtableType; DelayedEvaluation(const DelayedEvaluationVtable *vptr, CompileContext& compile_context, const SourceLocation& location); const SourceLocation& location() const {return m_location;} bool running() const {return m_state == state_running;} template<typename V> static void visit(V& v) { v("location", &DelayedEvaluation::m_location); } }; /** * \brief Data for a running TreeCallback. */ class RunningTreeCallback : public boost::noncopyable { DelayedEvaluation *m_callback; RunningTreeCallback *m_parent; public: RunningTreeCallback(DelayedEvaluation *callback); ~RunningTreeCallback(); PSI_ATTRIBUTE((PSI_NORETURN)) void throw_circular_dependency(); }; template<typename DataType_, typename ArgumentType_> struct DelayedEvaluationArgs { typedef DataType_ DataType; typedef ArgumentType_ ArgumentType; }; template<typename Args> class DelayedEvaluationCallback : public DelayedEvaluation { public: typedef typename Args::DataType DataType; typedef typename Args::ArgumentType ArgumentType; static const SIVtable vtable; DelayedEvaluationCallback(const DelayedEvaluationVtable *vptr, CompileContext& compile_context, const SourceLocation& location) : DelayedEvaluation(vptr, compile_context, location) {} DataType evaluate(const ArgumentType& arg) { ResultStorage<DataType> rs; DelayedEvaluation::evaluate(rs.ptr(), const_cast<ArgumentType*>(&arg)); return rs.done(); } template<typename V> static void visit(V& v) { visit_base<DelayedEvaluation>(v); } }; template<typename T> const SIVtable DelayedEvaluationCallback<T>::vtable = PSI_COMPILER_SI_ABSTRACT("psi.compiler.DelayedEvaluationCallback", &DelayedEvaluation::vtable); template<typename BaseArgs_, typename FunctionType_> struct DelayedEvaluationImplArgs { typedef BaseArgs_ BaseArgs; typedef FunctionType_ FunctionType; }; template<typename Args> class DelayedEvaluationImpl : public DelayedEvaluationCallback<typename Args::BaseArgs> { public: typedef typename Args::BaseArgs BaseArgs; typedef typename BaseArgs::DataType DataType; typedef typename BaseArgs::ArgumentType ArgumentType; typedef typename Args::FunctionType FunctionType; private: FunctionType *m_function; public: static const DelayedEvaluationVtable vtable; DelayedEvaluationImpl(CompileContext& compile_context, const SourceLocation& location, const FunctionType& function) : DelayedEvaluationCallback<BaseArgs>(&vtable, compile_context, location), m_function(new FunctionType(function)) { } ~DelayedEvaluationImpl() { if (m_function) delete m_function; } static void evaluate_impl(void *result, DelayedEvaluation *self_ptr, void *arg) { DelayedEvaluationImpl<Args>& self = *static_cast<DelayedEvaluationImpl<Args>*>(self_ptr); boost::scoped_ptr<FunctionType> function_copy(self.m_function); self.m_function = NULL; new (result) DataType (function_copy->evaluate(*static_cast<ArgumentType*>(arg))); } template<typename V> static void visit(V& v) { visit_base<DelayedEvaluationCallback<BaseArgs> >(v); v("function", &DelayedEvaluationImpl::m_function); } }; #define PSI_COMPILER_DELAYED_EVALUATION(derived,name,super) { \ PSI_COMPILER_OBJECT(derived,name,super), \ &derived::evaluate_impl \ } #if !PSI_DEBUG template<typename T> const DelayedEvaluationVtable DelayedEvaluationImpl<T>::vtable = PSI_COMPILER_DELAYED_EVALUATION(DelayedEvaluationImpl<T>, "(callback)", DelayedEvaluationCallback<typename T::BaseArgs>); #else template<typename T> const DelayedEvaluationVtable DelayedEvaluationImpl<T>::vtable = PSI_COMPILER_DELAYED_EVALUATION(DelayedEvaluationImpl<T>, typeid(typename T::FunctionType).name(), DelayedEvaluationCallback<typename T::BaseArgs>); #endif /** * \brief A value filled in on demand by a callback. * * This should be movable since the callback may only be used once, * but I'm not using C++11 so copyable it is. */ template<typename T, typename Arg> class DelayedValue { mutable T m_value; typedef DelayedEvaluationArgs<T, Arg> BaseArgs; mutable ObjectPtr<DelayedEvaluationCallback<BaseArgs> > m_callback; template<typename U> void init(boost::true_type, CompileContext&, const SourceLocation&, const U& value) { m_value = value; } template<typename U> void init(boost::false_type, CompileContext& compile_context, const SourceLocation& location, const U& callback) { m_callback.reset(new DelayedEvaluationImpl<DelayedEvaluationImplArgs<BaseArgs, U> >(compile_context, location, callback)); } public: template<typename U> DelayedValue(CompileContext& compile_context, const SourceLocation& location, const U& callback_or_value) { init(boost::is_convertible<U,T>(), compile_context, location, callback_or_value); } template<typename X, typename Y> const T& get(const X& self, Y (X::*getter) () const, void (X::*checker) (T&) const = NULL) const { if (m_callback) { m_value = m_callback->evaluate((self.*getter)()); m_callback.reset(); if (checker) (self.*checker)(m_value); } return m_value; } template<typename X> const T& get(const X& self) const { if (m_callback) { m_value = m_callback->evaluate(self); m_callback.reset(); } return m_value; } /// \brief Get the value if it has already been built T* get_maybe() { return m_callback ? NULL : &m_value; } /// \brief Get a value which must have already been computed const T& get_checked() const { PSI_ASSERT(!m_callback); return m_value; } /// \brief True if the callback is currently executing bool running() const { return m_callback && m_callback->running(); } template<typename V> static void visit(V& v) { v("value", &DelayedValue::m_value) ("callback", &DelayedValue::m_callback); } }; template<typename Args> struct SharedDelayedValueObject : public Object { typedef typename Args::DataType DataType; typedef typename Args::ArgumentType ArgumentType; static const VtableType vtable; DelayedValue<DataType, ArgumentType> value; template<typename U> SharedDelayedValueObject(CompileContext& compile_context, const SourceLocation& location, const U& callback_or_value) : Object(&vtable, compile_context), value(compile_context, location, callback_or_value) { } template<typename V> static void visit(V& v) { visit_base<Object>(v); v("value", &SharedDelayedValueObject::value); } }; template<typename T> const ObjectVtable SharedDelayedValueObject<T>::vtable = PSI_COMPILER_OBJECT(SharedDelayedValueObject<T>, "SharedDelayedValueObject", Object); template<typename T, typename Arg> class SharedDelayedValue { ObjectPtr<SharedDelayedValueObject<DelayedEvaluationArgs<T, Arg> > > m_ptr; public: SharedDelayedValue() {} template<typename U> SharedDelayedValue(CompileContext& compile_context, const SourceLocation& location, const U& callback_or_value) { reset(compile_context, location, callback_or_value); } template<typename U> void reset(CompileContext& compile_context, const SourceLocation& location, const U& callback_or_value) { m_ptr.reset(::new SharedDelayedValueObject<DelayedEvaluationArgs<T, Arg> >(compile_context, location, callback_or_value)); } bool empty() const { return !m_ptr; } template<typename X, typename Y> const T& get(const X& self, Y (X::*getter) () const = NULL, void (X::*checker) (T&) const = NULL) const { return m_ptr->value.template get<X,Y>(self, getter, checker); } template<typename X> const T& get(const X& self) const { return m_ptr->value.template get<X>(self); } /// \brief Get the value if it has already been built T* get_maybe() const {return m_ptr->value.get_maybe();} /// \brief Get a value which must have already been computed const T& get_checked() const {return m_ptr->value.get_checked();} /// \brief True if the callback is currently executing bool running() const {return m_ptr->value.running();} template<typename V> static void visit(V& v) { v("ptr", &SharedDelayedValue::m_ptr); } }; } } #endif
mit
iwconfig/svtplay-dl
lib/svtplay_dl/fetcher/hls.py
4853
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- from __future__ import absolute_import import sys import os import re import copy from svtplay_dl.output import progressbar, progress_stream, ETA, output from svtplay_dl.log import log from svtplay_dl.error import UIException, ServiceError from svtplay_dl.fetcher import VideoRetriever class HLSException(UIException): def __init__(self, url, message): self.url = url super(HLSException, self).__init__(message) class LiveHLSException(HLSException): def __init__(self, url): super(LiveHLSException, self).__init__( url, "This is a live HLS stream, and they are not supported.") def _get_full_url(url, srcurl): if url[:4] == 'http': return url if url[0] == '/': baseurl = re.search(r'^(http[s]{0,1}://[^/]+)/', srcurl) return "%s%s" % (baseurl.group(1), url) # remove everything after last / in the path of the URL baseurl = re.sub(r'^([^\?]+)/[^/]*(\?.*)?$', r'\1', srcurl) returl = "%s/%s" % (baseurl, url) return returl def hlsparse(options, res, url): streams = {} if not res: return None if res.status_code > 400: streams[0] = ServiceError("Can't read HLS playlist. {0}".format(res.status_code)) return streams files = (parsem3u(res.text))[1] for i in files: try: bitrate = float(i[1]["BANDWIDTH"])/1000 except KeyError: streams[0] = ServiceError("Can't read HLS playlist") return streams streams[int(bitrate)] = HLS(copy.copy(options), _get_full_url(i[0], url), bitrate, cookies=res.cookies) return streams class HLS(VideoRetriever): def name(self): return "hls" def download(self): if self.options.live and not self.options.force: raise LiveHLSException(self.url) cookies = self.kwargs["cookies"] m3u8 = self.http.request("get", self.url, cookies=cookies).text globaldata, files = parsem3u(m3u8) encrypted = False key = None if "KEY" in globaldata: keydata = globaldata["KEY"] encrypted = True if encrypted: try: from Crypto.Cipher import AES except ImportError: log.error("You need to install pycrypto to download encrypted HLS streams") sys.exit(2) match = re.search(r'URI="(https?://.*?)"', keydata) key = self.http.request("get", match.group(1)).content rand = os.urandom(16) decryptor = AES.new(key, AES.MODE_CBC, rand) file_d = output(self.options, "ts") if hasattr(file_d, "read") is False: return n = 1 eta = ETA(len(files)) for i in files: item = _get_full_url(i[0], self.url) if self.options.output != "-" and not self.options.silent: eta.increment() progressbar(len(files), n, ''.join(['ETA: ', str(eta)])) n += 1 data = self.http.request("get", item, cookies=cookies) if data.status_code == 404: break data = data.content if encrypted: data = decryptor.decrypt(data) file_d.write(data) if self.options.output != "-": file_d.close() if not self.options.silent: progress_stream.write('\n') self.finished = True def parsem3u(data): if not data.startswith("#EXTM3U"): raise ValueError("Does not apprear to be a ext m3u file") files = [] streaminfo = {} globdata = {} data = data.replace("\r", "\n") for l in data.split("\n")[1:]: if not l: continue if l.startswith("#EXT-X-STREAM-INF:"): # not a proper parser info = [x.strip().split("=", 1) for x in l[18:].split(",")] for i in range(0, len(info)): if info[i][0] == "BANDWIDTH": streaminfo.update({info[i][0]: info[i][1]}) if info[i][0] == "RESOLUTION": streaminfo.update({info[i][0]: info[i][1]}) elif l.startswith("#EXT-X-ENDLIST"): break elif l.startswith("#EXT-X-"): line = [l[7:].strip().split(":", 1)] if len(line[0]) == 1: line[0].append("None") globdata.update(dict(line)) elif l.startswith("#EXTINF:"): dur, title = l[8:].strip().split(",", 1) streaminfo['duration'] = dur streaminfo['title'] = title elif l[0] == '#': pass else: files.append((l, streaminfo)) streaminfo = {} return globdata, files
mit
peterjcaulfield/portaljs
portal.js
21004
;(function(window, document, undefined) { 'use strict'; var INSTANCE_COUNT = 0; // portal will be bound to the window object using this name var NAME = 'Portal'; // Portal defaults. // Can be overridden with a config object when creating portal object var DEFAULTS = { selector: '#portal', uploadUrl: '/upload.php', maxParallelUploads: 10, validFiletypes: ['txt', 'md', 'pdf', 'png', 'jpg', 'gif', 'mp3', 'avi', 'mkv', 'mp4'], maxFilesize: 1000 * 1000 * 100, timeout: 10000 }; /** * Portal object * * @param {object} config - the config object to override defaults */ function Portal(config) { /** * Portal configuration object * * @public * @property {object} */ this.config = {}; /** * lock for uploads * * @private * @property {boolean} */ this._lock = false; /** * internal object for private data * * @private * @property {object} */ this._data = {}; /** * Dom element(s) used for file drop bindings * * @public * @property {array} */ this._data.portals; /** * Holds the requests objects before upload * * @private * @property {array} */ this._data.requests = []; /** * Holds the requests objects in process of being uploaded * * @private * @property {object} */ this._data.requestsInProgress = {}; /** * Number of created uploads * * @private * @property {int} */ this._data.uploadsCreated = 0; /** * Number of attempted uploads * * @private * @property {int} */ this._data.uploadsAttempted = 0; /** * Number of failed uploads * * @private * @property {int} */ this._data.uploadsFailed = 0; /** * Number of uploads completed successfully * * @private * @property {int} */ this._data.uploadsCompleted = 0; /** * Event types * * @private * @property {array} */ this._data.events = [ 'uploadCreate', 'uploadStart', 'uploadProgress', 'uploadDone', 'uploadSuccess', 'uploadFail', 'uploadTimeout', 'uploadInvalid' ]; /** * Event type queues * * @private * @property {object} */ this._data.eventQueues = (function(self) { var _ = {}; for (var i = 0; i < self._data.events.length; i++) { _[self._data.events[i]] = []; } return _; })(this); // initialise the portal object on DOM load var that = this; document.addEventListener('DOMContentLoaded', function() { that._initialise(DEFAULTS, config); }); }; Portal.prototype = { constructor: Portal, /** * Function for binding functions to events * * @public * @method * @param {string} - event name * @param {function} - callback function for when event fires */ on: function(event, callback){ if (this._validEvent(event)) { this._data.eventQueues[event].push(callback); } }, /** * Function for retrieving target dom elements (portals) * * @private * @method */ _getPortals: function(){ var selector = this.config.selector; if (selector[0] == '#') { var portals = [document.getElementById(selector.substring(1, selector.length))]; } else if (selector[0] == '.') { var portals = document.getElementsByClassName(selector.substring(1, selector.length)); } else { throw Error('Selector property must be a class or id. "' + selector + '" given.'); } if (portals == null || portals[0] == null) { throw Error('No dom element(s) found for selector: "' + selector + '"'); } this._data.portals = portals; }, /** * Check if needle is in haystack * * @private * @method * @param {string} needle * @param {array} haystack * @return {boolean} */ _inArray: function(needle, haystack) { return haystack.indexOf(needle) > -1; }, /** * Check if event type is valid * * @private * @method * @param {string} event - event name * @return {boolean} */ _validEvent: function(event) { return this._inArray(event, this._data.events); }, /** * Fire event * * @private * @method * @param {string} event - event name * @param {string} args - event callback */ _fireEvent: function(event, args) { if (this._validEvent(event)) { var eventSubscribers = this._data.eventQueues[event]; for(var i = 0; i < eventSubscribers.length; i++) { eventSubscribers[i].apply(null, args); } } }, /** * Convert bytes to human readable byte size * * @private * @method * @param {float} numBytes - size of file in bytes * @return {string} - string representation of filesize */ _bytesToHumanReadable: function(numBytes) { var size; switch (true) { case (numBytes < 1000000): size = (numBytes / 1000).toFixed(3) + ' kB'; break; case (numBytes < 1000000000): size = (numBytes / 1000000).toFixed(1) + ' MB'; break; default: size = (numBytes / 1000000000).toFixed(1) + ' GB'; } return size; }, /** * Create a form data object * * @private * @method * @param {object} file - file object * @return {object} */ _createRequestData: function(file) { var form = new FormData(); form.append('file', file); return form; }, /** * Get function to bind to xhr onload event * * @private * @method * @param {object} request - request object * @return {function} - function to executed on xhr request onload event */ _bindOnLoadEvent: function(request) { var that = this; return function() { if (request.xhr.status === 200) { that._fireEvent('uploadSuccess', [request.data, request.xhr.status, request.xhr.responseText]); that._data.uploadsCompleted++; } else { that._fireEvent('uploadFail', [request.data, request.xhr.status, request.xhr.responseText]); that._data.uploadsFailed++; } delete that._data.requestsInProgress[request.data.num]; that._fireEvent('uploadDone'); }; }, /** * Get function to bind to xhr ontimeout event * * @private * @method * @param {object} request - request object * @return {function} - function to executed on xhr request onload event */ _bindOnTimeOutEvent: function(request) { var that = this; return function() { that._fireEvent('uploadTimeout', [request.data, request.xhr.status, request.xhr.responseText]); that._data.uploadsFailed++; delete that._data.requestsInProgress[request.data.num]; that._fireEvent('uploadDone'); }; }, /** * Callback for when an upload is completed * * @private * @method */ _uploadDone: function() { this._processUploadQueue(); }, /** * Process uploads not yet in progress * * @private * @method */ _processUploadQueue: function() { if (! this._lock) { this._lock = true; var inProgress = Object.keys(this._data.requestsInProgress).length; if (this._data.requests.length && inProgress < this.config.maxParallelUploads) { var batchSize = (this._data.requests.length > this.config.maxParallelUploads - inProgress) ? this.config.maxParallelUploads - inProgress: this._data.requests.length; for (var i = 0; i < batchSize; i++) { this._upload(); } } this._lock = false; } }, /** * Get function to bind to xhr onprogress event * * @private * @method * @param {object} request - request object * @return {function} - function to be executed on xhr request on progress event */ _bindOnProgressEvent: function(request) { var that = this; var percentComplete = 0; var loaded = 0; var perSec = 0; return function(e) { if (e.lengthComputable) { var date = new Date(); percentComplete = e.loaded / e.total * 100 | 0; if (! this.nextSecond) this.nextSecond = 0; if (date.getTime() < this.nextSecond && percentComplete != 100) return; this.nextSecond = date.getTime() + 1000; perSec = e.loaded - loaded; loaded = e.loaded; that._fireEvent('uploadProgress', [ request.data, e, that._bytesToHumanReadable(perSec), that._bytesToHumanReadable(loaded), (e.loaded / e.total * 100 | 0) ]); } }; }, /** * Create a portal request object * * @private * @method * @param {object} file - file object * @return {object} - portal request object */ _createRequestObject: function(file) { var requestData = this._createRequestData(file); var requestObject = { data : {} }; requestObject.data.num = ++this._data.uploadsCreated; requestObject.data.file = file; requestObject.data.file.readableSize = this._bytesToHumanReadable(file.size); requestObject._data = this._createRequestData(file); requestObject.xhr = this._createXMLHttpRequest(requestObject); requestObject.xhr.timeout = this.config.timeout; requestObject.xhr.onload = this._bindOnLoadEvent(requestObject); requestObject.xhr.upload.onprogress = this._bindOnProgressEvent(requestObject); requestObject.xhr.ontimeout = this._bindOnTimeOutEvent(requestObject); this._fireEvent('uploadCreate', [requestObject.data]); return requestObject; }, /** * create a new XMLHttpRequest * * @private * @method * @return {object} - XMLHttpRequest */ _createXMLHttpRequest: function() { var HttpRequest = new XMLHttpRequest(); HttpRequest.open('POST', this.config.uploadUrl, true); return HttpRequest; }, /** * Upload file * * @private * @method */ _upload: function() { if (this._data.requests.length) { var request = this._data.requests.pop(); request.xhr.send(request._data); this._data.uploadsAttempted++; this._data.requestsInProgress[request.data.num] = request; this._fireEvent('uploadStart', [request.data]); } }, /** * Check if file is valid based on portal config * * @private * @method * @param {object} file - file object * @return {array} - errors */ _isValidFile: function(file) { var errors = []; if (! this._isValidFiletype(file.name)) { errors.push('Invalid filetype'); } if (!this._isValidFilesize(file.size)) { errors.push('Filesize exceeds max'); } return errors; }, /** * Check if file is valid size * * @private * @method * @param filesize - filesize in bytes * @return {boolean} */ _isValidFilesize: function(filesize) { return filesize <= this.config.maxFilesize }, /** * Check if filetype if valid based on portal config * * @private * @method * @param {string} filename - name of file with extension * @return {boolean} */ _isValidFiletype: function(filename) { if (this._isHiddenFiletype(filename)) { return this._inArray(filename, this.config.validFiletypes); } return this._inArray(this._getFiletype(filename), this.config.validFiletypes); }, /** * Check if file is hidden filetype * * @private * @method * @param {string} filename - name of file * @return {boolean} */ _isHiddenFiletype: function(filename) { return filename[0] == '.'; }, /** * Get filetype (extension) * * @private * @method * @param {string} filename - name of file with extension * @return {string} */ _getFiletype: function(filename) { return filename.substr((~-filename.lastIndexOf(".") >>> 0) + 2).toLowerCase(); }, /** * Process files passed from file drop event * * @private * @method * @param {array} files - array of file objects */ _handleDrop: function(files) { for (var i = 0; i < files.length; i++) { var errors = this._isValidFile(files[i]); if (errors.length) { this._fireEvent('uploadInvalid', [files[i], errors]); } else { this._data.requests.unshift(this._createRequestObject(files[i])); } } this._processUploadQueue(); }, _handleClick: function(e) { var hiddenPortal = e.srcElement; this._handleDrop(hiddenPortal.files); var parentPortal = hiddenPortal.parentNode; // reset the input var tmpForm = document.createElement('form'); tmpForm.appendChild(hiddenPortal); tmpForm.reset(); parentPortal.appendChild(tmpForm.firstChild); }, /** * Initialize Portal object * * @private * @method * @param {object} defaults - object of default settings * @param {object} options - user passed settings to override defaults */ _initialise: function(defaults, options) { this._updateConfig(defaults, options); // bind portal dom events this._bind(); var that = this; this.on('uploadDone', function(){ that._uploadDone() }); }, /** * Update portal default config * * @private * @method * @param {object} - object containing values to overwrite * @param {object} - object containing the values to write */ _updateConfig: function(defaults, options) { if (typeof options == "undefined") return; var objs = [defaults, options]; for (var i = 0; i < 2; i++) { var obj = objs[i]; for(var key in obj) { this.config[key] = obj[key]; } } }, /** * Trigger click event on an element * * @private * @method * @param string - DOM element id */ _triggerClickEvent: function(elementId) { var evt; var el = document.getElementById(elementId); if (document.createEvent) { evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); } evt.cancelBubble = true; (evt) ? el.dispatchEvent(evt) : (el.click && el.click()); }, /** * Create hidden portal (file input) * * @private * @method * @param string - id index */ _createHiddenPortal: function(id) { var hiddenInput = document.createElement('input'); hiddenInput.type = 'file'; hiddenInput.setAttribute('multiple', 'multiple'); hiddenInput.classList.add('hiddenPortal'); hiddenInput.setAttribute('id', 'hiddenPortal-' + id); hiddenInput.style.visibility = 'hidden'; return hiddenInput; }, /** * Bind Portals dom events * * @private * @method * @param {object} portal - dom element to bind to */ _bind: function() { var hiddenInput = this._createHiddenPortal(++INSTANCE_COUNT); document.body.appendChild(hiddenInput); hiddenInput.addEventListener('change', function(e) { that._handleClick(e); } ); this._getPortals(); var that = this; for (var i = 0; i < this._data.portals.length; i++) { var portal = this._data.portals[i]; // only divs allow uploads via click if (portal.nodeName == "DIV") { portal.addEventListener('click', function(){ that._triggerClickEvent(hiddenInput.id); }); } portal.ondragover = function(e) { e.preventDefault(); return false; }; portal.ondragenter = function(e) { if (that._inArray('Files', e.dataTransfer.types)) { this.classList.add('active'); return false; } }; portal.ondragleave = function(e) { if (that._inArray('Files', e.dataTransfer.types)) { this.classList.remove('active'); return false; } }; portal.ondrop = function(e) { if (that._inArray('Files', e.dataTransfer.types)) { e.preventDefault(); this.classList.remove('active'); that._handleDrop(e.dataTransfer.files); return false; } }; }; } }; // expose portal window[NAME] = Portal; })(window, document);
mit
alanc10n/py-cutplanner
cutplanner/__init__.py
172
""" Utility for planning cuts for a given set of available stock. """ from .planner import Planner, Piece from .stock import Stock __all__ = ['Planner', 'Piece', 'Stock']
mit
anthonyshikanga/Bluecircle
config/environments/development.rb
1976
Rails.application.configure do config.action_mailer.default_url_options = {host: 'localhost', port: 3000} # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
mit
AlaMurkan-FIFA-Boyz-2017-Dremz2Lyf/Game-Manager
migrations/20161017114552_setup.js
1468
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTable('players', function(table) { table.increments('id').primary(); table.string('username').unique().notNullable(); }), knex.schema.createTable('tournaments', function(table) { table.increments('id').primary(); table.string('tournament_name').unique().notNullable(); table.integer('winner_id').references('id').inTable('players'); }), knex.schema.createTable('games', function(table) { table.increments('id').primary(); table.integer('player1_id').references('id').inTable('players'); table.integer('player2_id').references('id').inTable('players'); table.integer('player1_score').unsigned(); table.integer('player2_score').unsigned(); table.integer('player1_shots').unsigned(); table.integer('player2_shots').unsigned(); table.integer('player1_possession').unsigned(); table.integer('player2_possession').unsigned(); table.integer('player1_shotsOnGoal').unsigned(); table.integer('player2_shotsOnGoal').unsigned(); table.integer('tournament_id').references('id').inTable('tournaments'); table.string('status').defaultTo('created'); }) ]); }; exports.down = function(knex, Promise) { return Promise.all([ knex.raw('DROP TABLE players CASCADE'), knex.raw('DROP TABLE tournaments CASCADE'), knex.raw('DROP TABLE games CASCADE') ]); };
mit
ivan-shulev/despreneur-academy
functions.php
15645
<?php /** * Sage includes * * The $sage_includes array determines the code library included in your theme. * Add or remove files to the array as needed. Supports child theme overrides. * * Please note that missing files will produce a fatal error. * * @link https://github.com/roots/sage/pull/1042 */ $sage_includes = array( 'lib/assets.php', // Scripts and stylesheets 'lib/extras.php', // Custom functions 'lib/setup.php', // Theme setup 'lib/titles.php', // Page titles 'lib/wrapper.php', // Theme wrapper class 'lib/customizer.php', // Theme customizer ); foreach ($sage_includes as $file) { if (!$filepath = locate_template($file)) { trigger_error(sprintf(__('Error locating %s for inclusion', 'sage'), $file), E_USER_ERROR); } require_once $filepath; } unset($file, $filepath); /** * Extended Walker class for use with the * Twitter Bootstrap toolkit Dropdown menus in Wordpress. * Edited to support n-levels submenu. * @author johnmegahan https://gist.github.com/1597994, Emanuele 'Tex' Tessore https://gist.github.com/3765640 * @license CC BY 4.0 https://creativecommons.org/licenses/by/4.0/ */ class BootstrapNavMenuWalker extends Walker_Nav_Menu { function start_lvl( &$output, $depth ) { $indent = str_repeat( "\t", $depth ); $submenu = ($depth > 0) ? ' sub-menu' : ''; $output .= "\n$indent<ul class=\"dropdown-menu$submenu depth_$depth\">\n"; } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $li_attributes = ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; // managing divider: add divider class to an element to get a divider before it. $divider_class_position = array_search('divider', $classes); if($divider_class_position !== false){ $output .= "<li class=\"divider\"></li>\n"; unset($classes[$divider_class_position]); } $classes[] = ($args->has_children) ? 'dropdown' : ''; $classes[] = ($item->current || $item->current_item_ancestor || 'Courses' === $item->title && is_post_type_archive( 'course' ) || 'Courses' === $item->title && is_singular( 'course' ) ) ? 'active' : ''; $classes[] = 'menu-item-' . $item->ID; if($depth && $args->has_children){ $classes[] = 'dropdown-submenu'; } $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = ' class="' . esc_attr( $class_names ) . '"'; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args ); $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $value . $class_names . $li_attributes . '>'; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $attributes .= ($args->has_children) ? ' class="dropdown-toggle" data-toggle="dropdown"' : ''; $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= ($depth == 0 && $args->has_children) ? ' <b class="caret"></b></a>' : '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) { //v($element); if ( !$element ) return; $id_field = $this->db_fields['id']; //display this element if ( is_array( $args[0] ) ) $args[0]['has_children'] = ! empty( $children_elements[$element->$id_field] ); else if ( is_object( $args[0] ) ) $args[0]->has_children = ! empty( $children_elements[$element->$id_field] ); $cb_args = array_merge( array(&$output, $element, $depth), $args); call_user_func_array(array(&$this, 'start_el'), $cb_args); $id = $element->$id_field; // descend only when the depth is right and there are childrens for this element if ( ($max_depth == 0 || $max_depth > $depth+1 ) && isset( $children_elements[$id]) ) { foreach( $children_elements[ $id ] as $child ){ if ( !isset($newlevel) ) { $newlevel = true; //start the child delimiter $cb_args = array_merge( array(&$output, $depth), $args); call_user_func_array(array(&$this, 'start_lvl'), $cb_args); } $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output ); } unset( $children_elements[ $id ] ); } if ( isset($newlevel) && $newlevel ){ //end the child delimiter $cb_args = array_merge( array(&$output, $depth), $args); call_user_func_array(array(&$this, 'end_lvl'), $cb_args); } //end this element $cb_args = array_merge( array(&$output, $element, $depth), $args); call_user_func_array(array(&$this, 'end_el'), $cb_args); } } function da_add_members_query_var( $vars ){ $vars[] = "country"; $vars[] = "occupation"; $vars[] = "order"; return $vars; } add_filter( 'query_vars', 'da_add_members_query_var' ); function da_add_profile_query_var( $vars ){ $vars[] = "userid"; return $vars; } add_filter( 'query_vars', 'da_add_profile_query_var' ); add_action( 'show_user_profile', 'my_show_extra_profile_fields' ); add_action( 'edit_user_profile', 'my_show_extra_profile_fields' ); function my_show_extra_profile_fields( $user ) { ?> <table class="form-table"> <tbody> <tr class="user-capabilities-wrap"> <th scope="row">Occupation tags</th> <td> <fieldset> <legend class="screen-reader-text"><span>Occupation</span></legend> <label for="occupation-designer"> <input name="occupation_designer" type="checkbox" id="occupation-designer" value="1" <?php echo ( '1' === get_user_meta( $user_id = $user->ID, $key = 'occupation_designer', $single = true ) ? 'checked' : ''); ?>/> <span><?php esc_attr_e( 'Designer', '' ); ?></span> </label> <label for="occupation-engineer"> <input name="occupation_engineer" type="checkbox" id="occupation-engineer" value="1" <?php echo ( '1' === get_user_meta( $user_id = $user->ID, $key = 'occupation_engineer', $single = true ) ? 'checked' : ''); ?>/> <span><?php esc_attr_e( 'Engineer', '' ); ?></span> </label> <label for="occupation-entrepreneur"> <input name="occupation_entrepreneur" type="checkbox" id="occupation-entrepreneur" value="1" <?php echo ( '1' === get_user_meta( $user_id = $user->ID, $key = 'occupation_entrepreneur', $single = true ) ? 'checked' : ''); ?>/> <span><?php esc_attr_e( 'Entrepreneur', '' ); ?></span> </label> </fieldset> </td> </tr> </tbody> </table> <?php } add_action( 'personal_options_update', 'my_save_extra_profile_fields' ); add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' ); function my_save_extra_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_usermeta( $user_id, 'occupation_designer', $_POST['occupation_designer'] ); update_usermeta( $user_id, 'occupation_engineer', $_POST['occupation_engineer'] ); update_usermeta( $user_id, 'occupation_entrepreneur', $_POST['occupation_entrepreneur'] ); } add_action( 'fu_after_upload', 'my_fu_after_upload', 10, 3 ); function my_fu_after_upload( $attachment_ids, $success, $post_id ) { if($success) update_usermeta( get_current_user_id(), 'profile_background', $attachment_ids[0] ); } function da_custom_styles() { wp_enqueue_style( $handle = 'font-montserrat', $src = '//fonts.googleapis.com/css?family=Montserrat:400,700', $deps, $ver, $media ); wp_enqueue_style( $handle = 'font-s-sans-pro', $src = '//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700', $deps, $ver, $media ); wp_enqueue_style( $handle = 'font-s-serif-pro', $src = '//fonts.googleapis.com/css?family=Source+Serif+Pro:400,600', $deps, $ver, $media ); wp_enqueue_style( $handle = 'fontawesome', $src = '//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css', $deps, $ver, $media ); $default_color = get_theme_mod( $name = 'da_default_background_color', $default = '#A2A2A2' ); if(is_page( 'profile' ) || is_page( 'settings' )) { global $wpdb; $user_id = get_current_user_id(); $user_id_var = get_query_var( 'userid', '' ); if('' !== $user_id_var && is_numeric($user_id_var)){ $user = get_userdata( $user_id_var ); if(false !== $user) { $payment_status = $wpdb->get_var( $wpdb->prepare( "SELECT status FROM $wpdb->pmpro_memberships_users WHERE user_id = %s", $user_id_var ) ); if('active' == $payment_status) { $user_id = $user_id_var; } } } $background_id = get_user_meta( $user_id = $user_id, $key = 'profile_background', $single = true ); if('' !== $background_id) { $custom_css = '.full-width-background:before { background-image: url("' . wp_get_attachment_url($background_id) . '"); }'; function da_add_profile_special_class($classes) { $classes[] = 'da-profile-background'; return $classes; } add_action( $tag = 'body_class', $function_to_add = 'da_add_profile_special_class' ); } else { $custom_css = '.full-width-background { background: ' . $default_color . '; }'; } wp_add_inline_style( 'sage/css', $custom_css ); } elseif(is_pmpro_page()) { $background_image_src = get_theme_mod('da_payment_pages_background', ''); if( '' !== $background_image_src ) { $custom_css = '.partial-height { background-image: url("' . $background_image_src . '"); }'; } else { $custom_css = '.partial-height { background-color: ' . $default_color . '; }'; } wp_add_inline_style( 'sage/css', $custom_css ); } elseif(is_post_type_archive( 'course' )) { $background_image_src = get_theme_mod('da_course_archive_background', ''); if( '' !== $background_image_src ) { $custom_css = '.partial-height { background-image: url("' . $background_image_src . '"); }'; } else { $custom_css = '.partial-height { background-color: ' . $default_color . '; }'; } wp_add_inline_style( 'sage/css', $custom_css ); } elseif(is_page()) { $the_id = get_the_ID(); if(get_post_meta( $post_id = $the_id, $key = 'full_width_top_section', $single = true )) { if( has_post_thumbnail() ) { $thumbnail_url = wp_get_attachment_url( get_post_thumbnail_id() ); $custom_css = '.full-width-background { background-image: url("' . $thumbnail_url . '"); }'; } else { $custom_css = '.full-width-background { background-color: ' . $default_color . '; }'; } wp_add_inline_style( 'sage/css', $custom_css ); } } } add_action( 'wp_enqueue_scripts', 'da_custom_styles', 101 ); function da_avatar_filter() { // Remove from show_user_profile hook remove_action('show_user_profile', array('wp_user_avatar', 'wpua_action_show_user_profile')); remove_action('show_user_profile', array('wp_user_avatar', 'wpua_media_upload_scripts')); // Remove from edit_user_profile hook remove_action('edit_user_profile', array('wp_user_avatar', 'wpua_action_show_user_profile')); remove_action('edit_user_profile', array('wp_user_avatar', 'wpua_media_upload_scripts')); remove_action('wpua_before_avatar', 'wpua_do_before_avatar'); remove_action('wpua_after_avatar', 'wpua_do_after_avatar'); // Add to edit_user_avatar hook add_action('edit_user_avatar', array('wp_user_avatar', 'wpua_action_show_user_profile')); add_action('edit_user_avatar', array('wp_user_avatar', 'wpua_media_upload_scripts')); } // Loads only outside of administration panel if(!is_admin()) { add_action('init','da_avatar_filter'); } add_action( 'init', 'add_ppro_heading' ); function add_ppro_heading() { if( is_page( 'settings' ) ) { include(PMPRO_DIR . "/preheaders/levels.php"); } } function da_add_logout_link($sorted_menu_items) { if(is_user_logged_in()) { $new_menu_items = $sorted_menu_items; foreach ($sorted_menu_items as $menu_item) { if('Settings' === $menu_item->title) { $link = array ( 'title' => 'Logout', 'menu_item_parent' => $menu_item->menu_item_parent, 'url' => wp_logout_url(home_url()), ); $new_menu_items[] = (object) $link; } } return $new_menu_items; } else { return $sorted_menu_items; } } add_filter( 'wp_nav_menu_objects', 'da_add_logout_link'); function da_add_login_link($items, $args) { if(!is_user_logged_in() && $args->menu->slug == 'primary') { $items .= '<li class="menu-item"><a data-toggle="modal" data-target="#modal-login" href="#">Login</a></li>'; } return $items; } add_filter( 'wp_nav_menu_items', 'da_add_login_link', 10, 2); require_once (trailingslashit( get_template_directory() ) . 'lib/widgets.php'); function da_ajax_login_init() { wp_register_script('ajax-handler', get_template_directory_uri() . '/dist/scripts/ajax-handler.js', array('jquery') ); wp_enqueue_script('ajax-handler'); wp_localize_script( 'ajax-handler', 'ajax_handler_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'redirecturl' => get_permalink( get_page_by_path('profile') ), 'loadingmessage' => __('Sending user info, please wait...') )); // Enable the user with no privileges to run da_ajax_login() and da_ajax_regster() in AJAX // VITAL!!! add_action( 'wp_ajax_nopriv_ajaxlogin', 'da_ajax_login' ); add_action( 'wp_ajax_nopriv_ajaxregister', 'da_ajax_register' ); } // Execute the action only if the user isn't logged in if (!is_user_logged_in()) { add_action('init', 'da_ajax_login_init'); } function da_ajax_login() { // First check the nonce, if it fails the function will break check_ajax_referer( 'ajax-login-nonce', 'ajax-login' ); // Nonce is checked, get the POST data and sign user on $info = array(); $info['user_login'] = $_POST['login-email']; $info['user_password'] = $_POST['login-password']; $info['remember'] = $_POST['rememberme']; $user_signon = wp_signon( $info, false ); if ( is_wp_error($user_signon) ){ echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.'))); } else { echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...'))); } die(); } function da_ajax_register() { // First check the nonce, if it fails the function will break check_ajax_referer( 'ajax-register-nonce', 'ajax-register' ); // Nonce is checked, get the POST data and sign user on $userdata = array( 'user_login' => $_POST['register-email'], 'user_pass' => $_POST['register-password'], 'user_email' => $_POST['register-email'], ); $new_user_id = wp_insert_user( $userdata ); if ( ! is_wp_error( $new_user_id )) { $user = get_user_by( 'id', $new_user_id ); if( $user ) { update_user_meta( $user_id = $new_user_id, $meta_key = 'role', $meta_value = 'student', $prev_value ); wp_set_current_user( $new_user_id, $user->user_login ); wp_set_auth_cookie( $new_user_id ); do_action( 'wp_login', $user->user_login ); echo json_encode(array('registration'=>true, 'message'=>__('Login successful, redirecting...'))); } else { echo json_encode(array('registration'=>false, 'message'=>__('Error! Try again :)'))); } } else { $error = $new_user_id->get_error_message(); echo json_encode(array('registration'=>false, 'message'=>__($error))); } die(); }
mit
AbsoluteZero273/Deezic
app/renderer/presentational/generic/Slider.js
986
import React, { Component } from 'react' class Slider extends Component { constructor (props) { super(props) this.slider = null } componentDidUpdate () { const materialSlider = this.slider.MaterialSlider if (materialSlider) { materialSlider.change(this.props.value) } } componentDidMount () { // Buy time for mdl library to insert its dom to slider setTimeout(() => { // Injecting classname to slider container // because there is no way to select parent through css this.slider.parentNode.classList.add(this.props.containerClassName) }, 400) } render () { return ( <input ref={(el) => { this.slider = el }} className='mdl-slider mdl-js-slider' type='range' min='0' max={this.props.max} value={this.props.value} tabIndex='0' onChange={this.props.onSlide} onMouseLeave={this.props.onMouseLeave} /> ) } } export default Slider
mit
frangucc/gamify
www/sandbox/pals/sandbox/ScenarioRunner/app/js/controllers/messageListCtrl.js
558
four51.app.controller('MessageListCtrl', function($scope, MessageList) { MessageList.query(function(list) { $scope.messages = list; }); $scope.checkAll = function(event) { angular.forEach($scope.messages, function(msg) { msg.Selected = event.currentTarget.checked; }); }; $scope.deleteSelected = function() { $scope.displayLoadingIndicator = true; MessageList.delete($scope.messages, function() { MessageList.query(function(list) { $scope.messages = list; $scope.displayLoadingIndicator = false; }); }); }; });
mit
fweber1/Annies-Ancestors
webtrees/admin_module_charts.php
3673
<?php /** * webtrees: online genealogy * Copyright (C) 2016 webtrees development team * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Fisharebest\Webtrees; use Fisharebest\Webtrees\Controller\PageController; use Fisharebest\Webtrees\Functions\FunctionsEdit; use Fisharebest\Webtrees\Module\ModuleConfigInterface; define('WT_SCRIPT_NAME', 'admin_module_charts.php'); require 'includes/session.php'; $controller = new PageController; $controller ->restrictAccess(Auth::isAdmin()) ->setPageTitle(I18N::translate('Charts')); $action = Filter::post('action'); $modules = Module::getAllModulesByComponent('chart'); if ($action === 'update_mods' && Filter::checkCsrf()) { foreach ($modules as $module) { foreach (Tree::getAll() as $tree) { $access_level = Filter::post('access-' . $module->getName() . '-' . $tree->getTreeId(), WT_REGEX_INTEGER, $module->defaultAccessLevel()); Database::prepare( "REPLACE INTO `##module_privacy` (module_name, gedcom_id, component, access_level) VALUES (?, ?, 'chart', ?)" )->execute(array($module->getName(), $tree->getTreeId(), $access_level)); } } header('Location: ' . WT_BASE_URL . WT_SCRIPT_NAME); return; } $controller ->pageHeader(); ?> <ol class="breadcrumb small"> <li><a href="admin.php"><?php echo I18N::translate('Control panel'); ?></a></li> <li><a href="admin_modules.php"><?php echo I18N::translate('Module administration'); ?></a></li> <li class="active"><?php echo $controller->getPageTitle(); ?></li> </ol> <h1><?php echo $controller->getPageTitle(); ?></h1> <form method="post"> <input type="hidden" name="action" value="update_mods"> <?php echo Filter::getCsrf(); ?> <table class="table table-bordered"> <thead> <tr> <th class="col-xs-2"><?php echo I18N::translate('Chart'); ?></th> <th class="col-xs-5"><?php echo I18N::translate('Description'); ?></th> <th class="col-xs-5"><?php echo I18N::translate('Access level'); ?></th> </tr> </thead> <tbody> <?php foreach ($modules as $module_name => $module): ?> <tr> <td class="col-xs-2"> <?php if ($module instanceof ModuleConfigInterface): ?> <a href="<?php echo $module->getConfigLink(); ?>"><?php echo $module->getTitle(); ?> <i class="fa fa-cogs"></i></a> <?php else: ?> <?php echo $module->getTitle(); ?> <?php endif; ?> </td> <td class="col-xs-5"><?php echo $module->getDescription(); ?></td> <td class="col-xs-5"> <table class="table"> <tbody> <?php foreach (Tree::getAll() as $tree): ?> <tr> <td> <?php echo $tree->getTitleHtml(); ?> </td> <td> <?php echo FunctionsEdit::editFieldAccessLevel('access-' . $module->getName() . '-' . $tree->getTreeId(), $module->getAccessLevel($tree, 'chart')); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> </td> </tr> <?php endforeach; ?> </tbody> </table> <button class="btn btn-primary" type="submit"> <i class="fa fa-check"></i> <?php echo I18N::translate('save'); ?> </button> </form>
mit
GreenLightning/hypercube
src/eu/greenlightning/hypercubepdf/layout/HCPLayout.java
986
package eu.greenlightning.hypercubepdf.layout; /** * Represents a one-dimensional layout algorithm which is independent of the axis on which it is applied. * * @author Green Lightning */ public interface HCPLayout { /** * Returns the total size that this layout would need to optimally lay out the specified elements. This method takes * shrinking and stretching as well as gaps introduced by the layout into account. * * @param sizes the sizes of the individual elements * @return the total size needed to lay out these elements */ float getSize(float[] sizes); /** * Applies this layout algorithm to the specified elements and places them in the specified layout space. * * @param space the space in which the elements should be placed * @param sizes the sizes of the individual elements * @return an {@link HCPLayoutResults} instance containing the results of the layout process */ HCPLayoutResults apply(HCPLayoutSpace space, float[] sizes); }
mit
botify-labs/simpleflow
tests/utils/mock_swf_test_case.py
2849
import unittest import boto import boto.swf from moto.swf import swf_backend from simpleflow.swf.executor import Executor from simpleflow.swf.process.worker.base import ActivityPoller, ActivityWorker from swf.actors import Decider from tests.data import DOMAIN from tests.moto_compat import mock_s3, mock_swf @mock_s3 @mock_swf class MockSWFTestCase(unittest.TestCase): def setUp(self): # SWF preparation self.domain = DOMAIN self.workflow_type_name = "test-workflow" self.workflow_type_version = "v1.2" self.decision_task_list = "test-task-list" self.conn = boto.connect_swf() self.conn.register_domain(self.domain.name, "50") self.conn.register_workflow_type( self.domain.name, self.workflow_type_name, self.workflow_type_version, task_list=self.decision_task_list, default_child_policy="TERMINATE", default_execution_start_to_close_timeout="6", default_task_start_to_close_timeout="3", ) # S3 preparation in case we use jumbo fields self.s3_conn = boto.connect_s3() self.s3_conn.create_bucket("jumbo-bucket") def tearDown(self): swf_backend.reset() assert not self.conn.list_domains("REGISTERED")[ "domainInfos" ], "moto state incorrectly reset!" def register_activity_type(self, func, task_list): self.conn.register_activity_type(self.domain.name, func, task_list) def start_workflow_execution(self, input=None): self.workflow_id = "wfe-1234" response = self.conn.start_workflow_execution( self.domain.name, self.workflow_id, self.workflow_type_name, self.workflow_type_version, input=input, ) self.run_id = response["runId"] def build_decisions(self, workflow_class): self.decider = Decider(self.domain, self.decision_task_list) response = self.decider.poll() self._decision_token = response.token self.executor = Executor(self.domain, workflow_class) return self.executor.replay(response) def take_decisions(self, decisions, execution_context=None): self.decider.complete( self._decision_token, decisions=decisions, execution_context=execution_context, ) def get_workflow_execution_history(self): return self.conn.get_workflow_execution_history( self.domain.name, workflow_id=self.workflow_id, run_id=self.run_id, ) def process_activity_task(self): poller = ActivityPoller(self.domain, "default") response = poller.poll(identity="tst") worker = ActivityWorker() worker.process(poller, response.task_token, response.activity_task)
mit
anthraxx/pwndbg
pwndbg/events.py
6586
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Enables callbacks into functions to be automatically invoked when various events occur to the debuggee (e.g. STOP on SIGINT) by using a decorator. """ import sys from functools import partial from functools import wraps import gdb import pwndbg.config debug = pwndbg.config.Parameter('debug-events', False, 'display internal event debugging info') pause = 0 # There is no GDB way to get a notification when the binary itself # is loaded from disk, by the operating system, before absolutely # anything happens # # However, we get an Objfile event when the binary is loaded, before # its entry point is invoked. # # We also get an Objfile event when we load up GDB, so we need # to detect when the binary is running or not. # # Additionally, when attaching to a process running under QEMU, the # very first event which is fired is a 'stop' event. We need to # capture this so that we can fire off all of the 'start' events first. class StartEvent: def __init__(self): self.registered = list() self.running = False def connect(self, function): if function not in self.registered: self.registered.append(function) def disconnect(self, function): if function in self.registered: self.registered.remove(function) def on_new_objfile(self): if self.running or not gdb.selected_thread(): return self.running = True for function in self.registered: if debug: sys.stdout.write('%r %s.%s\n' % ('start', function.__module__, function.__name__)) function() def on_exited(self): self.running = False def on_stop(self): self.on_new_objfile() gdb.events.start = StartEvent() class EventWrapper: """ Wraper for GDB events which may not exist on older GDB versions but we still can fire them manually (to invoke them you have to call `invoke_callbacks`). """ def __init__(self, name): self.name = name self._event = getattr(gdb.events, self.name, None) self._is_real_event = self._event is not None def connect(self, func): if self._event is not None: self._event.connect(func) def disconnect(self, func): if self._event is not None: self._event.disconnect(func) @property def is_real_event(self): return self._is_real_event def invoke_callbacks(self): """ As an optimization please don't call this if your GDB has this event (check `.is_real_event`). """ for f in registered[self]: f() # Old GDBs doesn't have gdb.events.before_prompt, so we will emulate it using gdb.prompt_hook before_prompt_event = EventWrapper('before_prompt') gdb.events.before_prompt = before_prompt_event # In order to support reloading, we must be able to re-fire # all 'objfile' and 'stop' events. registered = { gdb.events.exited: [], gdb.events.cont: [], gdb.events.new_objfile: [], gdb.events.stop: [], gdb.events.start: [], gdb.events.before_prompt: [] # The real event might not exist, but we wrap it } # GDB 7.9 and above only try: registered[gdb.events.memory_changed] = [] registered[gdb.events.register_changed] = [] except (NameError, AttributeError): pass class Pause: def __enter__(self, *a, **kw): global pause pause += 1 def __exit__(self, *a, **kw): global pause pause -= 1 # When performing remote debugging, gdbserver is very noisy about which # objects are loaded. This greatly slows down the debugging session. # In order to combat this, we keep track of which objfiles have been loaded # this session, and only emit objfile events for each *new* file. objfile_cache = dict() def connect(func, event_handler, name=''): if debug: print("Connecting", func.__name__, event_handler) @wraps(func) def caller(*a): if debug: sys.stdout.write('%r %s.%s %r\n' % (name, func.__module__, func.__name__, a)) if a and isinstance(a[0], gdb.NewObjFileEvent): objfile = a[0].new_objfile handler = '%s.%s' % (func.__module__, func.__name__) path = objfile.filename dispatched = objfile_cache.get(path, set()) if handler in dispatched: return dispatched.add(handler) objfile_cache[path] = dispatched if pause: return try: func() except Exception as e: import pwndbg.exception pwndbg.exception.handle() raise e registered[event_handler].append(caller) event_handler.connect(caller) return func def exit(func): return connect(func, gdb.events.exited, 'exit') def cont(func): return connect(func, gdb.events.cont, 'cont') def new_objfile(func): return connect(func, gdb.events.new_objfile, 'obj') def stop(func): return connect(func, gdb.events.stop, 'stop') def start(func): return connect(func, gdb.events.start, 'start') before_prompt = partial(connect, event_handler=gdb.events.before_prompt, name='before_prompt') def reg_changed(func): try: return connect(func, gdb.events.register_changed, 'reg_changed') except AttributeError: return func def mem_changed(func): try: return connect(func, gdb.events.memory_changed, 'mem_changed') except AttributeError: return func def log_objfiles(ofile=None): if not (debug and ofile): return name = ofile.new_objfile.filename print("objfile: %r" % name) gdb.execute('info sharedlibrary') gdb.events.new_objfile.connect(log_objfiles) def after_reload(start=True): if gdb.selected_inferior().pid: for f in registered[gdb.events.stop]: f() for f in registered[gdb.events.start]: if start: f() for f in registered[gdb.events.new_objfile]: f() for f in registered[gdb.events.before_prompt]: f() def on_reload(): for event, functions in registered.items(): for function in functions: event.disconnect(function) registered[event] = [] @new_objfile def _start_newobjfile(): gdb.events.start.on_new_objfile() @exit def _start_exit(): gdb.events.start.on_exited() @stop def _start_stop(): gdb.events.start.on_stop() @exit def _reset_objfiles(): global objfile_cache objfile_cache = dict()
mit
katydecorah/font-library
test/families.test.js
1984
const test = require("tape"); const fetch = require("node-fetch"); const families = require("../families.json"); // build list of family names in families.json const familiesList = families.map(({ family }) => family); (async () => { try { const response = await fetch( "https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyDK4Jz71F7DQCrUhXYaF3xgEXoQGLDk5iE" ); const { items } = await response.json(); // build list of family names in Google Fonts API const googleFamilies = items.map(({ family }) => family); runTests(googleFamilies); } catch (err) { console.log(err); } })(); function runTests(googleFamilies) { // test each family in families.json families.forEach(({ family, tags }, index) => { test(family, (t) => { t.ok(family, "must have a family"); t.ok(tags, "must have tags"); // check if font exists in Google Fonts t.notEqual( googleFamilies.indexOf(family), "-1", `The font '${family}' does not match a font found in Google Fonts` ); // no more than 5 tags if (tags) { t.equal(tags.length < 6, true, "no more than 5 tags"); } // tags must be lowercase tags.forEach((tag) => { if (isNaN(tag[0]) && tag[0] == tag[0].toUpperCase()) { t.fail(`${tag} tag must be lowercase`); } }); // make sure families are in alphabetical order const prevFamily = families[index - 1] ? families[index - 1].family : undefined; if (prevFamily > family) { t.fail( `Font families must be in alphabetical order: '${family}' should appear before '${prevFamily}'` ); } t.end(); }); }); // check Google Fonts API for new fonts for (const font of googleFamilies) { if (!familiesList.includes(font)) { test(font, (t) => { t.fail(`Add the new font '${font}' to families.json`); t.end(); }); } } }
mit
liruqi/bigfoot
Interface/AddOns/DBM-TombofSargeras/localization.cn.lua
2067
-- Mini Dragon(projecteurs@gmail.com) -- 夏一可 -- Blizzard Entertainment -- Last update: 2017/08/24 if GetLocale() ~= "zhCN" then return end local L --------------------------- -- Goroth -- --------------------------- L= DBM:GetModLocalization(1862) --------------------------- -- Demonic Inquisition -- --------------------------- L= DBM:GetModLocalization(1867) --------------------------- -- Harjatan the Bludger -- --------------------------- L= DBM:GetModLocalization(1856) --------------------------- -- Mistress Sassz'ine -- --------------------------- L= DBM:GetModLocalization(1861) L:SetOptionLocalization({ TauntOnPainSuccess = "同步痛苦负担的的计时器和嘲讽提示为释放技能之后(高级打法,不懂别乱用)" }) --------------------------- -- Sisters of the Moon -- --------------------------- L= DBM:GetModLocalization(1903) --------------------------- -- The Desolate Host -- --------------------------- L= DBM:GetModLocalization(1896) L:SetOptionLocalization({ IgnoreTemplarOn3Tank = "当使用三个或以上Tank时忽略复活的圣殿骑士的骨盾的信息窗/提示/姓名条(请勿在战斗中更改,会打乱计次)" }) --------------------------- -- Maiden of Vigilance -- --------------------------- L= DBM:GetModLocalization(1897) --------------------------- -- Fallen Avatar -- --------------------------- L= DBM:GetModLocalization(1873) L:SetOptionLocalization({ InfoFrame = "信息窗:战斗总览" }) L:SetMiscLocalization({ FallenAvatarDialog = "你们眼前的躯壳曾承载过萨格拉斯的力量。但这座圣殿才是我们想要的。它能让我们将这世界化为灰烬!" }) --------------------------- -- Kil'jaeden -- --------------------------- L= DBM:GetModLocalization(1898) L:SetMiscLocalization({ Obelisklasers = "石碑激光" }) ------------- -- Trash -- ------------- L = DBM:GetModLocalization("TombSargTrash") L:SetGeneralLocalization({ name = "萨格拉斯之墓小怪" })
mit
ljtfreitas/java-restify
java-restify-http-client/src/main/java/com/github/ljtfreitas/restify/http/client/request/EndpointRequest.java
7960
/******************************************************************************* * * MIT License * * Copyright (c) 2016 Tiago de Freitas Lima * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ package com.github.ljtfreitas.restify.http.client.request; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.util.Optional; import com.github.ljtfreitas.restify.http.client.message.Header; import com.github.ljtfreitas.restify.http.client.message.Headers; import com.github.ljtfreitas.restify.http.contract.Parameters; import com.github.ljtfreitas.restify.reflection.JavaType; import com.github.ljtfreitas.restify.util.Try; public class EndpointRequest { private final URI endpoint; private final String method; private final Headers headers; private final Object body; private final JavaType responseType; private final EndpointVersion version; private final EndpointRequestMetadata metadata; public EndpointRequest(URI endpoint, String method) { this(endpoint, method, (EndpointVersion) null); } public EndpointRequest(URI endpoint, String method, EndpointVersion version) { this(endpoint, method, void.class, version); } public EndpointRequest(URI endpoint, String method, Type responseType) { this(endpoint, method, responseType, (EndpointVersion) null); } public EndpointRequest(URI endpoint, String method, JavaType responseType) { this(endpoint, method, responseType, null); } public EndpointRequest(URI endpoint, String method, Type responseType, EndpointVersion version) { this(endpoint, method, new Headers(), responseType, version); } public EndpointRequest(URI endpoint, String method, JavaType responseType, EndpointVersion version) { this(endpoint, method, new Headers(), null, responseType, version); } public EndpointRequest(URI endpoint, String method, Headers headers, Type responseType) { this(endpoint, method, headers, responseType, (EndpointVersion) null); } public EndpointRequest(URI endpoint, String method, Headers headers, JavaType responseType) { this(endpoint, method, headers, responseType, (EndpointVersion) null); } public EndpointRequest(URI endpoint, String method, Headers headers, Type responseType, EndpointVersion version) { this(endpoint, method, headers, null, responseType, version); } public EndpointRequest(URI endpoint, String method, Headers headers, JavaType responseType, EndpointVersion version) { this(endpoint, method, headers, null, responseType, version); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body) { this(endpoint, method, headers, body, (EndpointVersion) null); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body, EndpointVersion version) { this(endpoint, method, headers, body, void.class, version); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body, Type responseType) { this(endpoint, method, headers, body, responseType, null); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body, Type responseType, EndpointVersion version) { this(endpoint, method, headers, body, JavaType.of(responseType), version, EndpointRequestMetadata.empty()); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body, JavaType responseType) { this(endpoint, method, headers, body, responseType, null, EndpointRequestMetadata.empty()); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body, JavaType responseType, EndpointVersion version) { this(endpoint, method, headers, body, responseType, null, EndpointRequestMetadata.empty()); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body, Type responseType, EndpointVersion version, EndpointRequestMetadata metadata) { this(endpoint, method, headers, body, JavaType.of(responseType), version, metadata); } public EndpointRequest(URI endpoint, String method, Headers headers, Object body, JavaType responseType, EndpointVersion version, EndpointRequestMetadata metadata) { this.endpoint = endpoint; this.method = method; this.headers = headers; this.body = body; this.responseType = responseType; this.version = version; this.metadata = metadata; } public URI endpoint() { return endpoint; } public String method() { return method; } public Optional<Object> body() { return Optional.ofNullable(body); } public Headers headers() { return headers; } public JavaType responseType() { return responseType; } public Optional<EndpointVersion> version() { return Optional.ofNullable(version); } public EndpointRequestMetadata metadata() { return metadata; } public EndpointRequest append(Parameters parameters) { String query = parameters.queryString(); return appendOnQuery(query); } public EndpointRequest add(Header header) { Headers newheaders = headers.add(header); return new EndpointRequest(endpoint, method, newheaders, body, responseType, version, metadata); } public EndpointRequest add(Headers headers) { return new EndpointRequest(endpoint, method, this.headers.addAll(headers), body, responseType, version, metadata); } public EndpointRequest replace(Header header) { Headers newheaders = headers.replace(header); return new EndpointRequest(endpoint, method, newheaders, body, responseType, version, metadata); } private EndpointRequest appendOnQuery(String query) { String appender = endpoint.getQuery() == null ? "" : "&"; String newQuery = Optional.ofNullable(endpoint.getRawQuery()) .orElse("") .concat(appender) .concat(query); return Try.of(() -> cloneWithQuery(newQuery)) .error(IllegalArgumentException::new) .get(); } private EndpointRequest cloneWithQuery(String query) throws URISyntaxException { URI newURI = new URI(endpoint.getScheme(), endpoint.getRawAuthority(), endpoint.getRawPath(), query, endpoint.getRawFragment()); return new EndpointRequest(newURI, method, headers, body, responseType, version, metadata); } public EndpointRequest replace(URI endpoint) { return new EndpointRequest(endpoint, method, headers, body, responseType, version, metadata); } public EndpointRequest usingBody(Object body) { return new EndpointRequest(endpoint, method, headers, body, responseType, version, metadata); } @Override public String toString() { StringBuilder report = new StringBuilder(); report .append("EndpointRequest: [") .append("URI: ") .append(endpoint) .append(", ") .append("HTTP Method: ") .append(method) .append(", ") .append("Body: ") .append(body) .append(", ") .append("Response Type: ") .append(responseType) .append("]"); return report.toString(); } }
mit
wavelo/plugin-macro-loader
src/loader.js
2949
export { loadScripts, unloadScripts } from './loader/scripts' export { load, unloadPlugins, findPlugins } from './loader/selector' export { command, commandAll } from './loader/selector' export { loadGlobal, unloadGlobal, updateGlobal } from './loader/global' export { loadSystem, unloadSystem } from './loader/system' export contains from './lib/contains' export querySelectorAll from './lib/querySelectorAll' export resolveDataAttribute from './lib/resolveDataAttribute' import { mockApi as _mockApi } from './loader/api' import { bindApi as _bindApi } from './loader/api' import { bindGlobal as _bindGlobal } from './loader/global' import { bindSystem as _bindSystem } from './loader/system' import { bind as _bind } from './loader/selector' import createPluginApi from './lib/api' import createCreateInstance from './lib/createInstance' import { findPlugins, unloadPlugins } from './loader/selector' import { updateGlobal } from './loader/global' const _PluginApi = createPluginApi(); const _createInstance = createCreateInstance(_PluginApi); export const mockApi = _mockApi(_PluginApi); export const bindApi = _bindApi(_PluginApi); export const bindSystem = _bindSystem(_createInstance); export const bindGlobal = _bindGlobal(_createInstance); export const { bind, bindSelector, bindAttribute } = _bind(_createInstance); export function loader(fn) { const __PluginApi = createPluginApi(_PluginApi); const __createInstance = createCreateInstance(__PluginApi); const mockApi = _mockApi(__PluginApi); const bindApi = _bindApi(__PluginApi); const bindSystem = _bindSystem(__createInstance); const bindGlobal = _bindGlobal(__createInstance); const { bind, bindSelector, bindAttribute } = _bind(__createInstance); fn({ mockApi, bindApi, bindSystem, bindGlobal, bind, bindSelector, bindAttribute }); } export function loaderGlobal(fn) { fn({ mockApi, bindApi, bindSystem, bindGlobal, bind, bindSelector, bindAttribute }); } /** * @param {object} * @param {object} */ export function updatePlugins(plugins, data) { Object.keys(data||{}).forEach(function(key) { const [, name, method='update'] = key.match(/^(.*?)(?:::(.+))?$/)||[]; updateGlobal(name, data[key]); plugins. filter(val => val.pluginName===name || val.name===name). filter(({ instance }) => instance && instance[method]). forEach(({ instance }) => instance[method](data[key])); }); } /** * @param {object} * @param {object} */ export function updatePlugin(plugin, data) { Object.keys(data||{}).forEach(function(key) { const [, name, method='update'] = key.match(/^(.*?)(?:::(.+))?$/)||[]; if (plugin && plugin.instance && plugin.instance[method] && !name) { plugin.instance[method](data[key]); } }); } /** * @param {Element} */ export function unload($dom) { unloadPlugins(findPlugins($dom)); } /** * @param {Element} * @param {object} */ export function update($dom, data) { updatePlugins(findPlugins($dom), data); }
mit
shengnian/shengnian-ui-react
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleReversedComputerVertically.js
545
import React from 'react' import { Grid } from 'shengnian-ui-react' const GridExampleReversedComputerVertically = () => ( <Grid reversed='computer vertically'> <Grid.Row> <Grid.Column>Computer Row 4</Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column>Computer Row 3</Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column>Computer Row 2</Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column>Computer Row 1</Grid.Column> </Grid.Row> </Grid> ) export default GridExampleReversedComputerVertically
mit
tsechingho/authlogic_bundle
features/support/env.rb
2517
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. # It is recommended to regenerate this file in the future when you upgrade to a # newer version of cucumber-rails. Consider adding your own code to a new file # instead of editing this one. Cucumber will automatically load all features/**/*.rb # files. ENV["RAILS_ENV"] ||= "cucumber" require File.expand_path(File.dirname(__FILE__) + '/../../../../../config/environment') require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support require 'cucumber/rails/rspec' require 'cucumber/rails/world' require 'cucumber/rails/active_record' require 'cucumber/web/tableish' require 'webrat' require 'webrat/core/matchers' Webrat.configure do |config| config.mode = :rails config.open_error_files = false # Set to true if you want error pages to pop up in the browser end # If you set this to false, any error raised from within your app will bubble # up to your step definition and out to cucumber unless you catch it somewhere # on the way. You can make Rails rescue errors and render error pages on a # per-scenario basis by tagging a scenario or feature with the @allow-rescue tag. # # If you set this to true, Rails will rescue all errors and render error # pages, more or less in the same way your application would behave in the # default production environment. It's not recommended to do this for all # of your scenarios, as this makes it hard to discover errors in your application. ActionController::Base.allow_rescue = false # If you set this to true, each scenario will run in a database transaction. # You can still turn off transactions on a per-scenario basis, simply tagging # a feature or scenario with the @no-txn tag. If you are using Capybara, # tagging with @culerity or @javascript will also turn transactions off. # # If you set this to false, transactions will be off for all scenarios, # regardless of whether you use @no-txn or not. # # Beware that turning transactions off will leave data in your database # after each scenario, which can lead to hard-to-debug failures in # subsequent scenarios. If you do this, we recommend you create a Before # block that will explicitly put your database in a known state. Cucumber::Rails::World.use_transactional_fixtures = true # How to clean your database when transactions are turned off. See # http://github.com/bmabey/database_cleaner for more info. require 'database_cleaner' DatabaseCleaner.strategy = :truncation
mit