answer
stringlengths
15
1.25M
const os = require("os"); const fs = require("fs"); const config = { } let libs; switch (os.platform()) { case "darwin": { libs = [ "out/Debug_x64/libpvpkcs11.dylib", "out/Debug/libpvpkcs11.dylib", "out/Release_x64/libpvpkcs11.dylib", "out/Release/libpvpkcs11.dylib", ]; break; } case "win32": { libs = [ "out/Debug_x64/pvpkcs11.dll", "out/Debug/pvpkcs11.dll", "out/Release_x64/pvpkcs11.dll", "out/Release/pvpkcs11.dll", ]; break; } default: throw new Error("Cannot get pvpkcs11 compiled library. Unsupported OS"); } config.lib = libs.find(o => fs.existsSync(o)); if (!config.lib) { throw new Error("config.lib is empty"); } module.exports = config;
using System; using Xunit; using System.Linq; using hihapi.Models; using hihapi.Controllers; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.OData.Results; using hihapi.test.common; namespace hihapi.unittest.Finance { [Collection("HIHAPI_UnitTests public class <API key> { private <API key> fixture = null; public <API key>(<API key> fixture) { this.fixture = fixture; } [Theory] [InlineData("")] [InlineData(DataSetupUtility.UserA)] public async Task TestCase_Read(string strusr) { var context = fixture.<API key>(); // 1. Read it without User assignment var control = new <API key>(context); if (String.IsNullOrEmpty(strusr)) { var userclaim = DataSetupUtility.GetClaimForUser(strusr); control.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userclaim } }; } var getresult = control.Get(); Assert.NotNull(getresult); var getokresult = Assert.IsType<OkObjectResult>(getresult); var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value); Assert.NotNull(getqueryresult); if (String.IsNullOrEmpty(strusr)) { var dbcategories = (from tt in context.FinDocumentTypes where tt.HomeID == null select tt).ToList<FinanceDocumentType>(); Assert.Equal(dbcategories.Count, getqueryresult.Count()); } await context.DisposeAsync(); } [Theory] [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, "Test 1")] [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home2ID, "Test 2")] public async Task TestCase_CRUD(string currentUser, int hid, string name) { var context = fixture.<API key>(); // 1. Read it out before insert. var control = new <API key>(context); var userclaim = DataSetupUtility.GetClaimForUser(currentUser); control.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userclaim } }; var getresult = control.Get(); Assert.NotNull(getresult); var getokresult = Assert.IsType<OkObjectResult>(getresult); var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value); Assert.NotNull(getqueryresult); // 2. Insert a new one. FinanceDocumentType ctgy = new FinanceDocumentType(); ctgy.HomeID = hid; ctgy.Name = name; ctgy.Comment = name; var postresult = await control.Post(ctgy); var createdResult = Assert.IsType<CreatedODataResult<FinanceDocumentType>>(postresult); Assert.NotNull(createdResult); short nctgyid = createdResult.Entity.ID; Assert.Equal(hid, createdResult.Entity.HomeID); Assert.Equal(ctgy.Name, createdResult.Entity.Name); Assert.Equal(ctgy.Comment, createdResult.Entity.Comment); // 3. Read it out var getsingleresult = control.Get(nctgyid); Assert.NotNull(getsingleresult); var getctgy = Assert.IsType<FinanceDocumentType>(getsingleresult); Assert.Equal(hid, getctgy.HomeID); Assert.Equal(ctgy.Name, getctgy.Name); Assert.Equal(ctgy.Comment, getctgy.Comment); // 4. Change it getctgy.Comment += "Changed"; var putresult = control.Put(nctgyid, getctgy); Assert.NotNull(putresult); // 5. Delete it var deleteresult = control.Delete(nctgyid); Assert.NotNull(deleteresult); await context.DisposeAsync(); } } }
<?php # MantisBT - a php based bugtracking system # MantisBT is free software: you can redistribute it and/or modify # (at your option) any later version. # MantisBT is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /** * MantisBT Core API's */ require_once( 'core.php' ); require_once( 'email_api.php' ); <API key>( 'signup' ); $f_username = strip_tags( gpc_get_string( 'username' ) ); $f_email = strip_tags( gpc_get_string( 'email' ) ); $f_captcha = gpc_get_string( 'captcha', '' ); $f_public_key = gpc_get_int( 'public_key', '' ); $f_username = trim( $f_username ); $f_email = email_append_domain( trim( $f_email ) ); $f_captcha = utf8_strtolower( trim( $f_captcha ) ); # force logout on the current user if already authenticated if( <API key>() ) { auth_logout(); } # Check to see if signup is allowed if ( OFF == config_get_global( 'allow_signup' ) ) { <API key>( 'login_page.php' ); exit; } if( ON == config_get( 'signup_use_captcha' ) && get_gd_version() > 0 && <API key>( '<API key>, array() ) ) { # captcha image requires GD library and related option to ON $t_key = utf8_strtolower( utf8_substr( md5( config_get( '<API key> ) . $f_public_key ), 1, 5) ); if ( $t_key != $f_captcha ) { trigger_error( <API key>, ERROR ); } } <API key>( $f_email ); # notify the selected group a new user has signed-up if( user_signup( $f_username, $f_email ) ) { <API key>( $f_username, $f_email ); } form_security_purge( 'signup' ); html_page_top1(); html_page_top2a(); ?> <br /> <div align="center"> <table class="width50" cellspacing="1"> <tr> <td class="center"> <b><?php echo lang_get( 'signup_done_title' ) ?></b><br /> <?php echo "[$f_username - $f_email] " ?> </td> </tr> <tr> <td> <br /> <?php echo lang_get( '<API key>' ) ?> <br /><br /> <?php echo lang_get( 'no_reponse_msg') ?> <br /><br /> </td> </tr> </table> <br /> <?php print_bracket_link( 'login_page.php', lang_get( 'proceed' ) ); ?> </div> <?php html_page_bottom1a( __FILE__ );
team_mapping = { "SY": "Sydney", "WB": "Western Bulldogs", "WC": "West Coast", "HW": "Hawthorn", "GE": "Geelong", "FR": "Fremantle", "RI": "Richmond", "CW": "Collingwood", "CA": "Carlton", "GW": "Greater Western Sydney", "AD": "Adelaide", "GC": "Gold Coast", "ES": "Essendon", "ME": "Melbourne", "NM": "North Melbourne", "PA": "Port Adelaide", "BL": "Brisbane Lions", "SK": "St Kilda" } def get_team_name(code): return team_mapping[code] def get_team_code(full_name): for code, name in team_mapping.items(): if name == full_name: return code return full_name def <API key>(response): match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0] match_details = match_container.xpath(".//text()").extract() return { "round": match_details[1], "venue": match_details[3], "date": match_details[6], "attendance": match_details[8], "homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(), "awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(), "homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()), "awayScore": int(response.xpath("//table[1]/tr[3]/td[5]/b/text()").extract_first()) } def get_match_urls(response): for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract(): yield response.urljoin(match)
from keras.applications import imagenet_utils from keras.applications import mobilenet def <API key>(image): image -= 127.5 return image def <API key>(preprocessType): if preprocessType == "dummy": return <API key> elif preprocessType == "mobilenet": return mobilenet.preprocess_input elif preprocessType == "imagenet": return imagenet_utils.preprocess_input else: raise Exception(preprocessType + " not supported")
using System; namespace TheS.Runtime { internal class CallbackException : FatalException { public CallbackException() { } public CallbackException(string message, Exception innerException) : base(message, innerException) { // This can't throw something like ArgumentException because that would be worse than // throwing the callback exception that was requested. Fx.Assert(innerException != null, "CallbackException requires an inner exception."); Fx.Assert(!Fx.IsFatal(innerException), "CallbackException can't be used to wrap fatal exceptions."); } } }
<?php namespace App\Http\Controllers; use App\Jobs\GetInstance; use App\Models\Build; use App\Models\Commit; use App\Models\Repository; use App\RepositoryProviders\GitHub; use Illuminate\Support\Facades\DB; class DashboardController extends Controller { public function index() { $repositories = Repository::all(); $commits = Commit::select('branch', DB::raw('max(created_at) as created_at')) ->orderBy('created_at', 'desc') ->groupBy('branch') ->get(); $masterInfo = Commit::getBranchInfo('master'); $branches = []; foreach ($commits as $commit) { $info = Commit::getBranchInfo($commit->branch); $branches[] = [ 'branch' => $commit->branch, 'status' => $info['status'], 'label' => $info['label'], 'last_commit_id' => $info['last_commit_id'], ]; } return view('dashboard', compact('repositories', 'branches', 'masterInfo')); } public function build(Commit $commit, $attempt = null) { $count = Build::where(['commit_id' => $commit->id])->count(); $query = Build::where(['commit_id' => $commit->id]) ->orderBy('attempt', 'desc'); if ($attempt) { $query->where(['attempt' => $attempt]); } $build = $query->first(); $logs = json_decode($build->log, true); $next = $build->attempt < $count ? "/build/$build->id/" . ($build->attempt + 1) : null; return view('build', compact('build', 'commit', 'attempt', 'logs', 'count', 'next')); } public function rebuild(Build $build) { $rebuild = new Build(); $rebuild->commit_id = $build->commit_id; $rebuild->attempt = $build->attempt + 1; $rebuild->status = 'QUEUED'; $rebuild->save(); $github = new GitHub( $rebuild->commit->repository->name, $rebuild->commit->commit_id, env('PROJECT_URL') . '/build/' . $rebuild->commit_id ); $github->notifyPendingBuild(); dispatch(new GetInstance($rebuild->id)); return redirect("/build/$rebuild->commit_id"); } }
#pragma once /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../types/types.h" #pragma warning(pop) /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../actionbatching/actionbatching.h" #pragma warning(pop) /** include */ #include "./opengl_impl.h" #include "./opengl_impl_include.h" /** NBsys::NOpengl */ #if(BSYS_OPENGL_ENABLE) #pragma warning(push) #pragma warning(disable:4710) namespace NBsys{namespace NOpengl { class <API key> : public NBsys::NActionBatching::<API key> { private: /** opengl_impl */ Opengl_Impl& opengl_impl; /** shaderlayout */ sharedptr<Opengl_ShaderLayout> shaderlayout; /** asyncresult */ AsyncResult<bool> asyncresult; public: /** constructor */ <API key>(Opengl_Impl& a_opengl_impl,const sharedptr<Opengl_ShaderLayout>& a_shaderlayout,AsyncResult<bool>& a_asyncresult) : opengl_impl(a_opengl_impl), shaderlayout(a_shaderlayout), asyncresult(a_asyncresult) { } /** destructor */ virtual ~<API key>() { } private: /** copy constructor */ <API key>(const <API key>& a_this) = delete; void operator =(const <API key>& a_this) = delete; public: virtual void Start() { } virtual s32 Do(f32& a_delta,bool a_endrequest) { if(a_endrequest == true){ } if(this->shaderlayout->IsBusy() == true){ a_delta -= 1.0f; return 0; } //Render_LoadShader this->opengl_impl.Render_LoadShader(this->shaderlayout); //asyncresult this->asyncresult.Set(true); return 1; } }; }} #pragma warning(pop) #endif
<?php namespace Vich\UploaderBundle\Mapping; use Vich\UploaderBundle\Naming\NamerInterface; /** * PropertyMapping. * * @author Dustin Dobervich <ddobervich@gmail.com> */ class PropertyMapping { /** * @var \ReflectionProperty $property */ protected $property; /** * @var \ReflectionProperty $fileNameProperty */ protected $fileNameProperty; /** * @var NamerInterface $namer */ protected $namer; /** * @var array $mapping */ protected $mapping; /** * @var string $mappingName */ protected $mappingName; /** * Gets the reflection property that represents the * annotated property. * * @return \ReflectionProperty The property. */ public function getProperty() { return $this->property; } /** * Sets the reflection property that represents the annotated * property. * * @param \ReflectionProperty $property The reflection property. */ public function setProperty(\ReflectionProperty $property) { $this->property = $property; $this->property->setAccessible(true); } /** * Gets the reflection property that represents the property * which holds the file name for the mapping. * * @return \ReflectionProperty The reflection property. */ public function getFileNameProperty() { return $this->fileNameProperty; } /** * Sets the reflection property that represents the property * which holds the file name for the mapping. * * @param \ReflectionProperty $fileNameProperty The reflection property. */ public function setFileNameProperty(\ReflectionProperty $fileNameProperty) { $this->fileNameProperty = $fileNameProperty; $this->fileNameProperty->setAccessible(true); } /** * Gets the configured namer. * * @return null|NamerInterface The namer. */ public function getNamer() { return $this->namer; } /** * Sets the namer. * * @param \Vich\UploaderBundle\Naming\NamerInterface $namer The namer. */ public function setNamer(NamerInterface $namer) { $this->namer = $namer; } /** * Determines if the mapping has a custom namer configured. * * @return bool True if has namer, false otherwise. */ public function hasNamer() { return null !== $this->namer; } /** * Sets the configured configuration mapping. * * @param array $mapping The mapping; */ public function setMapping(array $mapping) { $this->mapping = $mapping; } /** * Gets the configured configuration mapping name. * * @return string The mapping name. */ public function getMappingName() { return $this->mappingName; } /** * Sets the configured configuration mapping name. * * @param $mappingName The mapping name. */ public function setMappingName($mappingName) { $this->mappingName = $mappingName; } /** * Gets the name of the annotated property. * * @return string The name. */ public function getPropertyName() { return $this->property->getName(); } /** * Gets the value of the annotated property. * * @param object $obj The object. * @return UploadedFile The file. */ public function getPropertyValue($obj) { return $this->property->getValue($obj); } /** * Gets the configured file name property name. * * @return string The name. */ public function <API key>() { return $this->fileNameProperty->getName(); } /** * Gets the configured upload directory. * * @return string The configured upload directory. */ public function getUploadDir() { return $this->mapping['upload_dir']; } /** * Determines if the file should be deleted upon removal of the * entity. * * @return bool True if delete on remove, false otherwise. */ public function getDeleteOnRemove() { return $this->mapping['delete_on_remove']; } /** * Determines if the uploadable field should be injected with a * Symfony\Component\HttpFoundation\File\File instance when * the object is loaded from the datastore. * * @return bool True if the field should be injected, false otherwise. */ public function getInjectOnLoad() { return $this->mapping['inject_on_load']; } }
personalprojects ============= A bunch of little things I made in my freetime PyPong A simple pong game made in Python and Pygame. **Changes Made**: Made the AI a bit (a lot) worse, you can actually win now. Maze Runner A maze app that uses Deep Field Search (DFS) to make a perfect maze and then uses the same algorithm in reverse to solve. Requires PyGame. **Usage**: Run it, enter your resolution, and let it run! Press "Escape" at anytime to quit. **Changes Made**: Exits more elegantly, colors are more visible. Find the Cow A joke of a game inspired by a conversation at dinner with friends. I challenged myself to keep it under 100 lines of code. Requires PyGame. **Usage**: Click to guess where the cow is. The volume of the "moo" indicates how far away the cow is. Once the cow is found, press spacebar to go to the next level. **ToDo**: Add a menu, although, I want to keep this under 100 lines of code. Binary Clock Something I thought I would finish, but never had the initative. It was supposed to be a simple 5 row binary clock. Maybe someday it will get a life.
#ifndef <API key> #define <API key> #include "sigmawallet.h" namespace elysium { class SigmaWalletV0 : public SigmaWallet { public: SigmaWalletV0(); protected: uint32_t BIP44ChangeIndex() const; SigmaPrivateKey GeneratePrivateKey(uint512 const &seed); class Database : public SigmaWallet::Database { public: Database(); public: bool WriteMint(SigmaMintId const &id, SigmaMint const &mint, CWalletDB *db = nullptr); bool ReadMint(SigmaMintId const &id, SigmaMint &mint, CWalletDB *db = nullptr) const; bool EraseMint(SigmaMintId const &id, CWalletDB *db = nullptr); bool HasMint(SigmaMintId const &id, CWalletDB *db = nullptr) const; bool WriteMintId(uint160 const &hash, SigmaMintId const &mintId, CWalletDB *db = nullptr); bool ReadMintId(uint160 const &hash, SigmaMintId &mintId, CWalletDB *db = nullptr) const; bool EraseMintId(uint160 const &hash, CWalletDB *db = nullptr); bool HasMintId(uint160 const &hash, CWalletDB *db = nullptr) const; bool WriteMintPool(std::vector<MintPoolEntry> const &mints, CWalletDB *db = nullptr); bool ReadMintPool(std::vector<MintPoolEntry> &mints, CWalletDB *db = nullptr); void ListMints(std::function<void(SigmaMintId&, SigmaMint&)> const&, CWalletDB *db = nullptr); }; public: using SigmaWallet::GeneratePrivateKey; }; } #endif // <API key>
# Gears # *Documentation may be outdated or incomplete as some URLs may no longer exist.* *Warning! This codebase is deprecated and will no longer receive support; excluding critical issues.* A PHP class that loads template files, binds variables to a single file or globally without the need for custom placeholders/variables, allows for parent-child hierarchy and parses the template structure. Gear is a play on words for: Engine + Gears + Structure. * Loads any type of file into the system * Binds variables to a single file or to all files globally * Template files DO NOT need custom markup and placeholders for variables * Can access and use variables in a template just as you would a PHP file * Allows for parent-child hierarchy * Parse a parent template to parse all children, and their children, and so on * Can destroy template indexes on the fly * No eval() or security flaws * And much more... ## Introduction ## Most of the template systems today use a very robust setup where the template files contain no server-side code. Instead they use a system where they use custom variables and markup to get the job done. For example, in your template you may have a variable called {pageTitle} and in your code you assign that variable a value of "Welcome". This is all well and good, but to be able to parse this "system", it requires loads of regex and matching/replacing/looping which can be quite slow and cumbersome. It also requires you to learn a new markup language, specific for the system you are using. Why would you want to learn a new markup language and structure simply to do an if statement or go through a loop? In Gears, the goal is to remove all that custom code, separate your markup from your code, allow the use of standard PHP functions, loops, statements, etc within templates, and much more! ## Installation ## Install by manually downloading the library or defining a [Composer dependency](http://getcomposer.org/). javascript { "require": { "mjohnson/gears": "4.0.0" } } Once available, instantiate the class and create template files. php // index.php $temp = new mjohnson\gears\Gears(dirname(__FILE__) . 'templates/'); $temp->setLayout('layouts/default'); // templates/layouts/default.tpl <!DOCTYPE html> <html> <head> <title><?php echo $pageTitle; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <?php echo $this->getContent(); ?> </body> </html> Within the code block above I am initiating the class by calling `new mjohnson\gears\Gears($path)` (where `$path` is the path to your templates directory) and storing it within a `$temp` variable. Next I am setting the layout I want to use; a layout is the outer HTML that will wrap the inner content pages. Within a layout you can use `getContent()` which will output the inner HTML wherever you please. ## Binding Variables ## It's now time to bind data to variables within your templates; to do this we use the `bind()` method. The bind method will take an array of key value pairs, or key value arguments. php $temp->bind(array( 'pageTitle' => 'Gears - Template Engine', 'description' => 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.' )); The way binding variables works is extremely easy to understand. In the data being binded, the key is the name of the variable within the template, and the value is what the variable will be output. For instance the variable pageTitle (Gears - Template Engine) above will be assigned to the variable `$pageTitle` within the `layouts/default.tpl`. Variables are binded globally to all templates, includes and the layout. ## Displaying the Templates ## To render templates, use the `display()` method. The display method takes two arguments, the name of the template you want to display and the key to use for caching. php echo $temp->display('index'); The second argument defines the name of the key to use for caching. Generally it will be the same name as the template name, but you do have the option to name it whatever you please. php echo $temp->display('index', 'index'); It's also possible to display templates within folders by separating the path with a forward slash. php echo $temp->display('users/login'); ## Opening a Template ## To render a template within another template you would use the `open()` method. The `open()` method takes 3 arguments: the path to the template (relative to the templates folder), an array of key value pairs to define as custom scoped variables and an array of cache settings. php echo $this->open('includes/footer', array('date' => date('Y')); By default, includes are not cached but you can enable caching by passing true as the third argument or an array of settings. The viable settings are key and duration, where key is the name of the cached file (usually the path) and duration is the length of the cache. php echo $this->open('includes/footer', array('date' => date('Y')), true); // Custom settings echo $this->open('includes/footer', array('date' => date('Y')), array( 'key' => 'cacheKey', 'duration' => '+10 minutes' )); ## Caching ## Gears comes packaged with a basic caching mechanism. By default caching is disabled, but to enable caching you can use `setCaching()`. This method will take the cache location as its 1st argument (best to place it in the same templates folder) and the expiration duration as the 2nd argument (default +1 day). php $temp->setCaching(dirname(__FILE__) . '/templates/cache/'); You can customize the duration by using the strtotime() format. You can also pass null as the first argument and the system will place the cache files within your template path. php $temp->setCaching(null, '+15 minutes'); To clear all cached files, you can use `flush()`. php $temp->flush(); For a better example of how to output cached data, refer to the tests folder within the Gears package.
(function (window) { 'use strict'; window.JWLB = window.JWLB || {}; window.JWLB.View = window.JWLB.View || {}; // Event handling var wallOnClick = function (event) { if (event.target.tagName.toLowerCase() === 'img') { var id = event.target.parentNode.dataset.id; var selectedPhoto = this.photos.filter(function (photo) { if (photo.id === id) { photo.portrait.id = id; return photo; } })[0]; this.sendEvent('gallery', selectedPhoto.portrait); } }; // View overrides var addUIListeners = function () { this.ui.wall.addEventListener('click', wallOnClick.bind(this)); }; var initUI = function () { var isUIValid = false; var comp = document.querySelector(this.selector); this.ui.wall = comp; if (this.ui.wall) { this.reset(); isUIValid = true; } return isUIValid; }; // Constructor var Gallery = function (domId) { // Overriden View class methods this.initUI = initUI; this.addUIListeners = addUIListeners; this.name = 'Gallery'; // Instance properties this.photos = []; // Initialize View JWLB.View.call(this, domId); }; // Inheritance Gallery.prototype = Object.create(JWLB.View.prototype); Gallery.prototype.constructor = Gallery; // Instance methods Gallery.prototype.addThumb = function (data, id) { // Store image data for future reference var photo = { id: id, thumb: null, portrait: data.size[0] }; data.size.forEach(function (elem) { if (elem.label === 'Square') { photo.thumb = elem; } if (elem.height > photo.portrait.height) { photo.portrait = elem; } }); this.photos.push(photo); // Build thumbnail UI var node = document.createElement('div'); node.setAttribute('data-id', id); node.setAttribute('class', 'thumb'); var img = document.createElement('img'); img.setAttribute('src', photo.thumb.source); img.setAttribute('title', 'id: '+ id); node.appendChild(img); this.ui.wall.querySelector('article[name=foobar]').appendChild(node); }; Gallery.prototype.reset = function () { if (this.ui.wall.children.length > 0) { var article = this.ui.wall.children.item(0) article.parentElement.removeChild(article); } var article = document.createElement('article'); article.setAttribute('name', 'foobar'); this.ui.wall.appendChild(article); }; window.JWLB.View.Gallery = Gallery; })(window);
module InfinityTest module Core class Base # Specify the Ruby Version Manager to run cattr_accessor :strategy # * :rvm # * :rbenv # * :ruby_normal (Use when don't pass any rubies to run) # * :auto_discover(defaults) self.strategy = :auto_discover # Specify Ruby version(s) to test against # rubies = %w(ree jruby) cattr_accessor :rubies self.rubies = [] # Options to include in the command. cattr_accessor :specific_options self.specific_options = '' # Test Framework to use Rspec, Bacon, Test::Unit or AutoDiscover(defaults) # * :rspec # * :bacon # * :test_unit (Test unit here apply to this two libs: test/unit and minitest) # * :auto_discover(defaults) # This will load a exactly a class constantize by name. cattr_accessor :test_framework self.test_framework = :auto_discover # Framework to know the folders and files that need to monitoring by the observer. # * :rails # * :rubygems # * :auto_discover(defaults) # This will load a exactly a class constantize by name. cattr_accessor :framework self.framework = :auto_discover # Framework to observer watch the dirs. # * watchr cattr_accessor :observer self.observer = :watchr # Ignore test files. # ignore_test_files = [ 'spec/generators/<API key>.rb' ] cattr_accessor :ignore_test_files self.ignore_test_files = [] # Ignore test folders. # # Imagine that you don't want to run integration specs. # ignore_test_folders = [ 'spec/integration' ] cattr_accessor :ignore_test_folders self.ignore_test_folders = [] # Verbose Mode. Print commands before executing them. cattr_accessor :verbose self.verbose = true # Set the notification framework to use with Infinity Test. # * :growl # * :lib_notify # * :auto_discover(defaults) # This will load a exactly a class constantize by name. cattr_writer :notifications self.notifications = :auto_discover # You can set directory to show images matched by the convention names. # Infinity test will work on these names in the notification framework: # * success (png, gif, jpeg) # * failure (png, gif, jpeg) # * pending (png, gif, jpeg) cattr_accessor :mode # => This will show images in the folder: self.mode = :simpson # Success Image to show after the tests run. cattr_accessor :success_image # Pending Image to show after the tests run. cattr_accessor :pending_image # Failure Image to show after the tests run. cattr_accessor :failure_image # Use a specific gemset for each ruby. # OBS.: This only will work for RVM strategy. cattr_accessor :gemset # InfinityTest try to use bundler if Gemfile is present. # Set to false if you don't want use bundler. cattr_accessor :bundler self.bundler = true # Callbacks accessor to handle before or after all run and for each ruby! cattr_accessor :callbacks self.callbacks = [] # Run the observer to monitor files. # If set to false will just <b>Run tests and exit</b>. # Defaults to true: run tests and monitoring the files. cattr_accessor :infinity_and_beyond self.infinity_and_beyond = true # The extension files that Infinity Test will search. # You can observe python, erlang, etc files. cattr_accessor :extension self.extension = :rb # Setup Infinity Test passing the ruby versions and others setting. # <b>See the class accessors for more information.</b> # InfinityTest::Base.setup do |config| # config.strategy = :rbenv # config.rubies = %w(ree jruby rbx 1.9.2) # end def self.setup yield self end # Receives a object that quacks like InfinityTest::Options and do the merge with self(Base class). def self.merge!(options) ConfigurationMerge.new(self, options).merge! end def self.<API key> <API key>.start end def self.<API key> @<API key> ||= <API key>.new(self) end # Just a shortcut to bundler class accessor. def self.using_bundler? bundler end # Just a shortcut to bundler class accessor. def self.verbose? verbose end # Callback method to handle before all run and for each ruby too! # before(:all) do # end # before(:each_ruby) do |environment| # end # before do # if you pass not then will use :all option # end def self.before(scope, &block) # setting_callback(Callbacks::BeforeCallback, scope, &block) end # Callback method to handle after all run and for each ruby too! # after(:all) do # end # after(:each_ruby) do # end # after do # if you pass not then will use :all option # end def self.after(scope, &block) # setting_callback(Callbacks::AfterCallback, scope, &block) end # Clear the terminal (Useful in the before callback) def self.clear_terminal system('clear') end # <b>DEPRECATED:</b> Please use <tt>.notification=</tt> instead. def self.notifications(notification_name = nil, &block) if notification_name.blank? self.class_variable_get(:@@notifications) else message = <<-MESSAGE .notifications is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.notifications = :growl end MESSAGE ActiveSupport::Deprecation.warn(message) self.notifications = notification_name self.instance_eval(&block) if block_given? end end # <b>DEPRECATED:</b> Please use: # <tt>success_image=</tt> or # <tt>pending_image=</tt> or # <tt>failure_image=</tt> or # <tt>mode=</tt> instead. def self.show_images(options) message = <<-MESSAGE .show_images is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.success_image = 'some_image.png' config.pending_image = 'some_image.png' config.failure_image = 'some_image.png' config.mode = '<API key>' end MESSAGE ActiveSupport::Deprecation.warn(message) self.success_image = options[:success_image] || options[:sucess_image] if options[:success_image].present? || options[:sucess_image].present? # for fail typo in earlier versions. self.pending_image = options[:pending_image] if options[:pending_image].present? self.failure_image = options[:failure_image] if options[:failure_image].present? self.mode = options[:mode] if options[:mode].present? end # <b>DEPRECATED:</b> Please use: # .rubies = or # .specific_options = or # .test_framework = or # .framework = or # .verbose = or # .gemset = instead def self.use(options) message = <<-MESSAGE .use is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.rubies = %w(2.0 jruby) config.specific_options = '-J' config.test_framework = :rspec config.framework = :padrino config.verbose = true config.gemset = :some_gemset end MESSAGE ActiveSupport::Deprecation.warn(message) self.rubies = options[:rubies] if options[:rubies].present? self.specific_options = options[:specific_options] if options[:specific_options].present? self.test_framework = options[:test_framework] if options[:test_framework].present? self.framework = options[:app_framework] if options[:app_framework].present? self.verbose = options[:verbose] unless options[:verbose].nil? self.gemset = options[:gemset] if options[:gemset].present? end # <b>DEPRECATED:</b> Please use .clear_terminal instead. def self.clear(option) message = '.clear(:terminal) is DEPRECATED. Please use .clear_terminal instead.' ActiveSupport::Deprecation.warn(message) clear_terminal end def self.heuristics(&block) # There is a spec pending. end def self.replace_patterns(&block) # There is a spec pending. end private # def self.setting_callback(callback_class, scope, &block) # callback_instance = callback_class.new(scope, &block) # self.callbacks.push(callback_instance) # callback_instance # end end end end
<?php session_start(); require_once('../php/conexion.php'); $conect = connect::conn(); $user = $_SESSION['usuario']; if($_SERVER['REQUEST_METHOD'] == 'POST'){ $sql = "insert into cotidiano (dir_origen,dir_destino,semana,hora,usuario,estado) values (?,?,?,?,?,?);"; $favo = sqlsrv_query($conect,$sql,array($_POST['Dir_o'],$_POST['Dir_d'],$_POST['semana'],$_POST['reloj'],$user['usuario'],1)); if($favo){ echo 'Inserccion correcta'; } else{ if( ($errors = sqlsrv_errors() ) != null) { foreach( $errors as $error ) { echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />"; echo "code: ".$error[ 'code']."<br />"; echo "message: ".$error[ 'message']."<br />"; } } } }else{ print "aqui la estabas cagando"; } ?>
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.MSProjectApi.Enums { <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863548(v=office.14).aspx </remarks> [SupportByVersion("MSProject", 11,12,14)] [EntityType(EntityType.IsEnum)] public enum PjMonthLabel { <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>57</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 57, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>86</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 86, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>85</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 85, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>11</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_m = 11, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>10</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 10, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>8</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 8, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>9</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 9, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>7</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 7, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>59</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 59, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>58</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 58, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>45</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 45, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>61</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 61, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>60</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 60, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>44</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 44, <summary> SupportByVersion MSProject 11, 12, 14 </summary> <remarks>35</remarks> [SupportByVersion("MSProject", 11,12,14)] <API key> = 35 } }
//#define USE_TOUCH_SCRIPT using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; namespace GarageKit { [RequireComponent(typeof(Camera))] public class FlyThroughCamera : MonoBehaviour { public static bool winTouch = false; public static bool updateEnable = true; public enum <API key> { DRAG = 0, DRAG_HOLD } public <API key> controllType; public enum <API key> { XZ = 0, XY } public <API key> moveType; public Collider groundCollider; public Collider limitAreaCollider; public bool useLimitArea = false; public float moveBias = 1.0f; public float moveSmoothTime = 0.1f; public bool dragInvertX = false; public bool dragInvertY = false; public float rotateBias = 1.0f; public float rotateSmoothTime = 0.1f; public bool rotateInvert = false; public OrbitCamera <API key>; private GameObject flyThroughRoot; public GameObject FlyThroughRoot { get{ return flyThroughRoot; } } private GameObject shiftTransformRoot; public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } } private bool inputLock; public bool IsInputLock { get{ return inputLock; } } private object lockObject; private Vector3 defaultPos; private Quaternion defaultRot; private bool isFirstTouch; private Vector3 oldScrTouchPos; private Vector3 dragDelta; private Vector3 velocitySmoothPos; private Vector3 dampDragDelta = Vector3.zero; private Vector3 pushMoveDelta = Vector3.zero; private float velocitySmoothRot; private float dampRotateDelta = 0.0f; private float pushRotateDelta = 0.0f; public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } } public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } } void Awake() { } void Start() { if(!ApplicationSetting.Instance.GetBool("UseMouse")) winTouch = true; inputLock = false; Ray ray = new Ray(this.transform.position, this.transform.forward); RaycastHit hitInfo; if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity)) { flyThroughRoot = new GameObject(this.gameObject.name + " FlyThrough Root"); flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false); flyThroughRoot.transform.position = hitInfo.point; flyThroughRoot.transform.rotation = Quaternion.identity; shiftTransformRoot = new GameObject(this.gameObject.name + " ShiftTransform Root"); shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true); shiftTransformRoot.transform.localPosition = Vector3.zero; shiftTransformRoot.transform.localRotation = Quaternion.identity; this.gameObject.transform.SetParent(shiftTransformRoot.transform, true); } else { Debug.LogWarning("FlyThroughCamera :: not set the ground collider !!"); return; } defaultPos = flyThroughRoot.transform.position; defaultRot = flyThroughRoot.transform.rotation; ResetInput(); } void Update() { if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0) GetInput(); else ResetInput(); UpdateFlyThrough(); <API key>(); } private void ResetInput() { isFirstTouch = true; oldScrTouchPos = Vector3.zero; dragDelta = Vector3.zero; } private void GetInput() { // for Touch if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { if(Input.touchCount == 1) { Vector3 currentScrTouchPos = Input.GetTouch(0).position; if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == <API key>.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } #if <API key> else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch) { #if !USE_TOUCH_SCRIPT if(Input.touchCount == 1) { Vector3 currentScrTouchPos = Input.touches[0].position; #else if(TouchScript.TouchManager.Instance.<API key> == 1) { Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position; #endif if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == <API key>.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } #endif // for Mouse else { if(Input.GetMouseButton(0)) { Vector3 currentScrTouchPos = Input.mousePosition; if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == <API key>.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } } <summary> InputLock </summary> public void LockInput(object sender) { if(!inputLock) { lockObject = sender; inputLock = true; } } <summary> InputUnLock </summary> public void UnlockInput(object sender) { if(inputLock && lockObject == sender) inputLock = false; } <summary> </summary> private void UpdateFlyThrough() { if(!FlyThroughCamera.updateEnable || flyThroughRoot == null) return; float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f); float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f); if(moveType == <API key>.XZ) dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime); else if(moveType == <API key>.XY) dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime); flyThroughRoot.transform.Translate(dampDragDelta, Space.Self); pushMoveDelta = Vector3.zero; if(useLimitArea) { if(limitAreaCollider != null) { Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position; Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position; if(moveType == <API key>.XZ) { float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x); float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z); flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ); } else if(moveType == <API key>.XY) { float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x); float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y); flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z); } } } dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime); if(moveType == <API key>.XZ) flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self); else if(moveType == <API key>.XY) flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self); pushRotateDelta = 0.0f; } private void <API key>() { if(<API key> != null && <API key>.OrbitRoot != null) { Vector3 lookPoint = <API key>.OrbitRoot.transform.position; Transform orbitParent = <API key>.OrbitRoot.transform.parent; <API key>.OrbitRoot.transform.parent = null; flyThroughRoot.transform.LookAt(lookPoint, Vector3.up); flyThroughRoot.transform.rotation = Quaternion.Euler( 0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f); <API key>.OrbitRoot.transform.parent = orbitParent; } } <summary> </summary> public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f) { dampDragDelta = Vector3.zero; flyThroughRoot.transform.DOMove(targetPosition, time) .SetEase(Ease.OutCubic) .Play(); } <summary> </summary> public void <API key>(Vector3 move) { dampDragDelta = Vector3.zero; flyThroughRoot.transform.Translate(move, Space.Self); } <summary> </summary> public void RotateToFlyThrough(float targetAngle, float time = 1.0f) { dampRotateDelta = 0.0f; Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles; targetEulerAngles.y = targetAngle; flyThroughRoot.transform.DORotate(targetEulerAngles, time) .SetEase(Ease.OutCubic) .Play(); } <summary> </summary> public void PushMove(Vector3 move) { pushMoveDelta = move; } <summary> </summary> public void PushRotate(float rotate) { pushRotateDelta = rotate; } <summary> </summary> public void ResetFlyThrough() { ResetInput(); MoveToFlyThrough(defaultPos); RotateToFlyThrough(defaultRot.eulerAngles.y); } } }
"use strict"; const readdir = require("../../"); const dir = require("../utils/dir"); const { expect } = require("chai"); const through2 = require("through2"); const fs = require("fs"); let nodeVersion = parseFloat(process.version.substr(1)); describe("Stream API", () => { it("should be able to pipe to other streams as a Buffer", done => { let allData = []; readdir.stream("test/dir") .pipe(through2((data, enc, next) => { try { // By default, the data is streamed as a Buffer expect(data).to.be.an.instanceOf(Buffer); // Buffer.toString() returns the file name allData.push(data.toString()); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir") .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // In "object mode", the data is a string expect(data).to.be.a("string"); allData.push(data); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe fs.Stats to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir", { stats: true }) .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // The data is an fs.Stats object expect(data).to.be.an("object"); expect(data).to.be.an.instanceOf(fs.Stats); allData.push(data.path); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", done); }); it("should be able to pause & resume the stream", done => { let allData = []; let stream = readdir.stream("test/dir") .on("data", data => { allData.push(data); // The stream should not be paused expect(stream.isPaused()).to.equal(false); if (allData.length === 3) { // Pause for one second stream.pause(); setTimeout(() => { try { // The stream should still be paused expect(stream.isPaused()).to.equal(true); // The array should still only contain 3 items expect(allData).to.have.lengthOf(3); // Read the rest of the stream stream.resume(); } catch (e) { done(e); } }, 1000); } }) .on("end", () => { expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to use "readable" and "read"', done => { let allData = []; let nullCount = 0; let stream = readdir.stream("test/dir") .on("readable", () => { // Manually read the next chunk of data let data = stream.read(); while (true) { // eslint-disable-line if (data === null) { // The stream is done nullCount++; break; } else { // The data should be a string (the file name) expect(data).to.be.a("string").with.length.of.at.least(1); allData.push(data); data = stream.read(); } } }) .on("end", () => { if (nodeVersion >= 12) { // In Node >= 12, the "readable" event fires twice, // and stream.read() returns null twice expect(nullCount).to.equal(2); } else if (nodeVersion >= 10) { // In Node >= 10, the "readable" event only fires once, // and stream.read() only returns null once expect(nullCount).to.equal(1); } else { // In Node < 10, the "readable" event fires 13 times (once per file), // and stream.read() returns null each time expect(nullCount).to.equal(13); } expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to subscribe to custom events instead of "data"', done => { let allFiles = []; let allSubdirs = []; let stream = readdir.stream("test/dir"); // Calling "resume" is required, since we're not handling the "data" event stream.resume(); stream .on("file", filename => { expect(filename).to.be.a("string").with.length.of.at.least(1); allFiles.push(filename); }) .on("directory", subdir => { expect(subdir).to.be.a("string").with.length.of.at.least(1); allSubdirs.push(subdir); }) .on("end", () => { expect(allFiles).to.have.same.members(dir.shallow.files); expect(allSubdirs).to.have.same.members(dir.shallow.dirs); done(); }) .on("error", done); }); it('should handle errors that occur in the "data" event listener', done => { testErrorHandling("data", dir.shallow.data, 7, done); }); it('should handle errors that occur in the "file" event listener', done => { testErrorHandling("file", dir.shallow.files, 3, done); }); it('should handle errors that occur in the "directory" event listener', done => { testErrorHandling("directory", dir.shallow.dirs, 2, done); }); it('should handle errors that occur in the "symlink" event listener', done => { testErrorHandling("symlink", dir.shallow.symlinks, 5, done); }); function testErrorHandling (eventName, expected, expectedErrors, done) { let errors = [], data = []; let stream = readdir.stream("test/dir"); // Capture all errors stream.on("error", error => { errors.push(error); }); stream.on(eventName, path => { data.push(path); if (path.indexOf(".txt") >= 0 || path.indexOf("dir-") >= 0) { throw new Error("Epic Fail!!!"); } else { return true; } }); stream.on("end", () => { try { // Make sure the correct number of errors were thrown expect(errors).to.have.lengthOf(expectedErrors); for (let error of errors) { expect(error.message).to.equal("Epic Fail!!!"); } // All of the events should have still been emitted, despite the errors expect(data).to.have.same.members(expected); done(); } catch (e) { done(e); } }); stream.resume(); } });
<?php namespace PHPExiftool\Driver\Tag\Font; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class PreferredSubfamily extends AbstractTag { protected $Id = 17; protected $Name = 'PreferredSubfamily'; protected $FullName = 'Font::Name'; protected $GroupName = 'Font'; protected $g0 = 'Font'; protected $g1 = 'Font'; protected $g2 = 'Document'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Preferred Subfamily'; }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (10.0.2) on Fri Sep 21 22:00:31 PDT 2018 --> <title>U-Index</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="date" content="2018-09-21"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../script.js"></script> <script type="text/javascript" src="../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif] <script type="text/javascript" src="../jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="U-Index"; } } catch(err) { } var pathtoroot = "../";loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="fixedNav"> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../main/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../main/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-1.html">Prev Letter</a></li> <li>Next Letter</li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li> <li><a href="index-2.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.top"> </a></div> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><! $('.navPadding').css('padding-top', $('.fixedNav').css("height")); </script> <div class="contentContainer"><a href="index-1.html">M</a>&nbsp;<a href="index-2.html">U</a>&nbsp;<a name="I:U"> </a> <h2 class="title">U</h2> <dl> <dt><a href="../main/UsingTheGridLayout.html" title="class in main"><span class="typeNameLink">UsingTheGridLayout</span></a> - Class in <a href="../main/package-summary.html">main</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../main/UsingTheGridLayout.html#UsingTheGridLayout--">UsingTheGridLayout()</a></span> - Constructor for class main.<a href="../main/UsingTheGridLayout.html" title="class in main">UsingTheGridLayout</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">M</a>&nbsp;<a href="index-2.html">U</a>&nbsp;</div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../main/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../main/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-1.html">Prev Letter</a></li> <li>Next Letter</li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li> <li><a href="index-2.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
package com.microsoft.azure.management.synapse.v2019_06_01_preview; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.<API key>; /** * Defines values for <API key>. */ public final class <API key> extends <API key><<API key>> { /** Static value Initial for <API key>. */ public static final <API key> INITIAL = fromString("Initial"); /** Static value Stopped for <API key>. */ public static final <API key> STOPPED = fromString("Stopped"); /** Static value Started for <API key>. */ public static final <API key> STARTED = fromString("Started"); /** Static value Starting for <API key>. */ public static final <API key> STARTING = fromString("Starting"); /** Static value Stopping for <API key>. */ public static final <API key> STOPPING = fromString("Stopping"); /** Static value NeedRegistration for <API key>. */ public static final <API key> NEED_REGISTRATION = fromString("NeedRegistration"); /** Static value Online for <API key>. */ public static final <API key> ONLINE = fromString("Online"); /** Static value Limited for <API key>. */ public static final <API key> LIMITED = fromString("Limited"); /** Static value Offline for <API key>. */ public static final <API key> OFFLINE = fromString("Offline"); /** Static value AccessDenied for <API key>. */ public static final <API key> ACCESS_DENIED = fromString("AccessDenied"); /** * Creates or finds a <API key> from its string representation. * @param name a name to look for * @return the corresponding <API key> */ @JsonCreator public static <API key> fromString(String name) { return fromString(name, <API key>.class); } /** * @return known <API key> values */ public static Collection<<API key>> values() { return values(<API key>.class); } }
// Base class for a module. Stores the environment and handles magic such as route annotations. export class Module { constructor(env) { this.env_ = env; let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_; if (!decoratedRoutes) return; decoratedRoutes.forEach(route => { env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]); }); } }; // Annotation that can be used on modules to indicate that the annotated method is the request // handler for a |method| (GET, POST) request for |route_path|. export function route(method, route_path) { return (target, handler) => { if (!target.hasOwnProperty('decoratedRoutes_')) target.decoratedRoutes_ = []; target.decoratedRoutes_.push({ method, route_path, handler }); }; }
<?php namespace PhpCsFixer\Fixer\PhpUnit; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\Tokenizer\Tokens; /** * @author Roland Franssen <franssen.roland@gmail.com> */ final class <API key> extends AbstractFixer { /** * {@inheritdoc} */ public function getDefinition() { return new FixerDefinition( 'PHPUnit annotations should be a FQCNs including a root namespace.', array(new CodeSample( '<?php final class MyTest extends \<API key> { /** * @expectedException <API key> * @covers Project\NameSpace\Something * @coversDefaultClass Project\Default * @uses Project\Test\Util */ public function testSomeTest() { } } ' )) ); } /** * {@inheritdoc} */ public function getPriority() { // should be run before <API key> return -9; } /** * {@inheritdoc} */ public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } /** * {@inheritdoc} */ protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $token) { if ($token->isGivenKind(T_DOC_COMMENT)) { $token->setContent(preg_replace( '~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(\w.*)$~m', '$1\\\\$2', $token->getContent() )); } } } }
layout: post title: "OJ" date: 2016-12-20 11:36:52 categories: tags: OJ algorithms mathjax: true OJ OJOnline JudgeOJTYVJRQNOJURAL LeetcodeOJOJLeetCode OJ OJACMLeetCode LeetCodeOJGitHub LeetCodebug OJLeetCode LeetCodehttps://leetcode.com/ ![<API key>.png-65.6kB][1] ![<API key>.png-91.4kB][2] LeetCodelintcode [1]: http://static.zybuluo.com/coldxiangyu/<API key>/<API key>.png [2]: http://static.zybuluo.com/coldxiangyu/<API key>/<API key>.png
package com.timotheteus.raincontrol.handlers; import com.timotheteus.raincontrol.tileentities.IGUITile; import com.timotheteus.raincontrol.tileentities.<API key>; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; import net.minecraftforge.fml.network.FMLPlayMessages; import net.minecraftforge.fml.network.NetworkHooks; import javax.annotation.Nullable; public class GuiHandler implements IGuiHandler { public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) { BlockPos pos = openContainer.getAdditionalData().readBlockPos(); // new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos)); <API key> te = (<API key>) Minecraft.getInstance().world.getTileEntity(pos); if (te != null) { return te.createGui(Minecraft.getInstance().player); } return null; } //TODO can remove these, I think @Nullable @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createContainer(player); } return null; } @Nullable @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createGui(player); } return null; } }
<?php namespace Matthimatiker\<API key>\Locking; use Symfony\Component\Filesystem\LockHandler; class FileLockManager implements <API key> { /** * The directory that contains the lock files. * * @var string */ private $lockDirectory = null; /** * Contains the locks that are currently active. * * The name of the lock is used as key. * * @var array<string, LockHandler> */ private $activeLocksByName = array(); /** * @param string $lockDirectory Path to the directory that contains the locks. */ public function __construct($lockDirectory) { $this->lockDirectory = $lockDirectory; } /** * Obtains a lock for the provided name. * * The lock must be released before it can be obtained again. * * @param string $name * @return boolean True if the lock was obtained, false otherwise. */ public function lock($name) { if ($this->isLocked($name)) { return false; } $lock = new LockHandler($name . '.lock', $this->lockDirectory); if ($lock->lock()) { // Obtained lock. $this->activeLocksByName[$name] = $lock; return true; } return false; } /** * Releases the lock with the provided name. * * If the lock does not exist, then this method will do nothing. * * @param string $name */ public function release($name) { if (!$this->isLocked($name)) { return; } /* @var $lock LockHandler */ $lock = $this->activeLocksByName[$name]; $lock->release(); unset($this->activeLocksByName[$name]); } /** * Checks if a lock with the given name is active. * * @param string $name * @return boolean */ private function isLocked($name) { return isset($this->activeLocksByName[$name]); } }
// Core is a collection of helpers // Nothing specific to the emultor application "use strict"; // all code is defined in this namespace window.te = window.te || {}; // te.provide creates a namespace if not previously defined. // Levels are seperated by a `.` Each level is a generic JS object. // Example: // te.provide("my.name.space"); // my.name.foo = function(){}; // my.name.space.bar = function(){}; te.provide = function(ns /*string*/ , root) { var parts = ns.split('.'); var lastLevel = root || window; for (var i = 0; i < parts.length; i++) { var p = parts[i]; if (!lastLevel[p]) { lastLevel = lastLevel[p] = {}; } else if (typeof lastLevel[p] !== 'object') { throw new Error('Error creating namespace.'); } else { lastLevel = lastLevel[p]; } } }; // A simple UID generator. Returned UIDs are guaranteed to be unique to the page load te.Uid = (function() { var id = 1; function next() { return id++; } return { next: next }; })(); // defaultOptionParse is a helper for functions that expect an options // var passed in. This merges the passed in options with a set of defaults. // Example: // foo function(options) { // tf.defaultOptionParse(options, {bar:true, fizz:"xyz"}); te.defaultOptionParse = function(src, defaults) { src = src || {}; var keys = Object.keys(defaults); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (src[k] === undefined) { src[k] = defaults[k]; } } return src; }; // Simple string replacement, eg: // tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar te.sprintf = function(str) { for (var i = 1; i < arguments.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, arguments[i]); } return str; };
# Backup v4.x Configuration # Config Options # The options here may be overridden on the command line, but the result # will depend on the use of --root-path on the command line. # If --root-path is used on the command line, then all paths set here # will be overridden. If a path (like --tmp-path) is not given along with # --root-path, that path will use it's default location _relative to --root-path_. # If --root-path is not used on the command line, a path option (like --tmp-path) # given on the command line will override the tmp_path set here, but all other # paths set here will be used. # Note that relative paths given on the command line without --root-path # are relative to the current directory. The root_path set here only applies # to relative paths set here. # Sets the root path for all relative paths, including default paths. # May be an absolute path, or relative to the current working directory. # root_path 'my/root' # Sets the path where backups are processed until they're stored. # This must have enough free space to hold apx. 2 backups. # May be an absolute path, or relative to the current directory or +root_path+. # tmp_path 'my/tmp' # Sets the path where backup stores persistent information. # When Backup's Cycler is used, small YAML files are stored here. # May be an absolute path, or relative to the current directory or +root_path+. # data_path 'my/data' # Utilities # If you need to use a utility other than the one Backup detects, # or a utility can not be found in your $PATH. # Utilities.configure do # tar '/usr/bin/gnutar' # redis_cli '/opt/redis/redis-cli' # end # Logging # Logging options may be set on the command line, but certain settings # may only be configured here. # Logger.configure do # console.quiet = true # Same as command line: --quiet # logfile.max_bytes = 2_000_000 # Default: 500_000 # syslog.enabled = true # Same as command line: --syslog # syslog.ident = 'my_app_backup' # Default: 'backup' # end # Command line options will override those set here. # For example, the following would override the example settings above # to disable syslog and enable console output. # backup perform --trigger my_backup --no-syslog --no-quiet # Component Defaults # Set default options to be applied to components in all models. # Options set within a model will override those set here. # Storage::S3.defaults do |s3| # s3.access_key_id = "my_access_key_id" # s3.secret_access_key = "<API key>" # end # Notifier::Mail.defaults do |mail| # mail.from = 'sender@email.com' # mail.to = 'receiver@email.com' # mail.address = 'smtp.gmail.com' # mail.port = 587 # mail.domain = 'your.host.name' # mail.user_name = 'sender@email.com' # mail.password = 'my_password' # mail.authentication = 'plain' # mail.encryption = :starttls # end # Preconfigured Models # Create custom models with preconfigured components. # Components added within the model definition will # +add to+ the preconfigured components. # preconfigure 'MyModel' do # archive :user_pictures do |archive| # archive.add '~/pictures' # end # notify_by Mail do |mail| # mail.to = 'admin@email.com' # end # end # MyModel.new(:john_smith, 'John Smith Backup') do # archive :user_music do |archive| # archive.add '~/music' # end # notify_by Mail do |mail| # mail.to = 'john.smith@email.com' # end # end
import Ember from 'ember'; let __TRANSLATION_MAP__ = {}; export default Ember.Service.extend({ map: __TRANSLATION_MAP__ });
package cmd import ( "github.com/fatih/color" out "github.com/plouc/go-gitlab-client/cli/output" "github.com/spf13/cobra" ) func init() { getCmd.AddCommand(getProjectVarCmd) } var getProjectVarCmd = &cobra.Command{ Use: resourceCmd("project-var", "project-var"), Aliases: []string{"pv"}, Short: "Get the details of a project's specific variable", RunE: func(cmd *cobra.Command, args []string) error { ids, err := config.aliasIdsOrArgs(currentAlias, "project-var", args) if err != nil { return err } color.Yellow("Fetching project variable (id: %s, key: %s)…", ids["project_id"], ids["var_key"]) loader.Start() variable, meta, err := client.ProjectVariable(ids["project_id"], ids["var_key"]) loader.Stop() if err != nil { return err } out.Variable(output, outputFormat, variable) printMeta(meta, false) return nil }, }
export interface IContact { id?: number; email: string; listName: string; name: string; }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk.Interop { <summary> </summary> [StructLayout(LayoutKind.Sequential)] public unsafe partial struct <API key> { <summary> The type of this structure. </summary> public SharpVk.StructureType SType; <summary> Null or an extension-specific structure. </summary> public void* Next; <summary> </summary> public SharpVk.<API key> HandleTypes; } }
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.<API key>; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.<API key>; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.<API key>; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.<API key>; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.<API key>; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.<API key>; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.<API key>; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.<API key>; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.<API key>; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.<API key>; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.*; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class CreditTest { @Mock private Database mockDatabase; @Mock private DatabaseTable mockWalletTable; @Mock private DatabaseTable mockBalanceTable; @Mock private DatabaseTransaction mockTransaction; private List<DatabaseTableRecord> mockRecords; private DatabaseTableRecord mockBalanceRecord; private DatabaseTableRecord mockWalletRecord; private <API key> <API key>; private <API key> testBalance; @Before public void setUpMocks(){ <API key> = new <API key>(); mockBalanceRecord = new <API key>(); mockWalletRecord = new <API key>(); mockRecords = new ArrayList<>(); mockRecords.add(mockBalanceRecord); setUpMockitoRules(); } public void setUpMockitoRules(){ when(mockDatabase.getTable(<API key>.<API key>)).thenReturn(mockWalletTable); when(mockDatabase.getTable(<API key>.<API key>)).thenReturn(mockBalanceTable); when(mockBalanceTable.getRecords()).thenReturn(mockRecords); when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord); when(mockDatabase.newTransaction()).thenReturn(mockTransaction); } @Before public void <API key>(){ testBalance = new <API key>(mockDatabase); } @Test public void <API key>() throws Exception{ catchException(testBalance).credit(<API key>); assertThat(caughtException()).isNull(); } @Test public void <API key>() throws Exception{ doThrow(new <API key>("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(<API key>); assertThat(caughtException()) .isNotNull() .isInstanceOf(<API key>.class); } @Test public void <API key>() throws Exception{ doThrow(new <API key>("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(<API key>); assertThat(caughtException()) .isNotNull() .isInstanceOf(<API key>.class); } @Test public void <API key>() throws Exception{ doThrow(new <API key>("MOCK", null, null, null)).when(mockWalletTable).loadToMemory(); catchException(testBalance).credit(<API key>); assertThat(caughtException()) .isNotNull() .isInstanceOf(<API key>.class); } @Test public void <API key>() throws Exception{ when(mockBalanceTable.getRecords()).thenReturn(null); catchException(testBalance).credit(<API key>); assertThat(caughtException()) .isNotNull() .isInstanceOf(<API key>.class); } }
using System; namespace Sherlock { <summary> A reader than can read values from a pipe. </summary> <typeparam name="T">The type of value to read.</typeparam> public interface IPipeReader<T> : IDisposable { <summary> Attempts to read a value from the pipe. </summary> <param name="item">The read value.</param> <returns>A value indicating success.</returns> bool Read(out T item); <summary> Closes the reader. </summary> void Close(); <summary> Gets a value indicating whether the reader is closed. </summary> bool IsClosed { get; } } }
# Nitrogen 2.0 New Features New Elements, Actions, and API functions * wf:wire can now act upon CSS classes or full JQuery Paths, not just Nitrogen elements. For example, wf:wire(".people > .address", Actions) will wire actions to any HTML elements with an "address" class underneath a "people" class. Anything on http://api.jquery.com/category/selectors/ is supported * Added wf:replace(ID, Elements), remove an element from the page, put new elements in their place. * Added wf:remove(ID), remove an element from the page. * New #api{} action allows you to define a javascript method that takes parameters and will trigger a postback. Javascript parameters are automatically translated to Erlang, allowing for pattern matching. * New * The #upload{} event callbacks have changed. Event fires both on start of upload and when upload finishes. * Upload callbacks take a Node parameter so that file uploads work even when a postback hits a different node. * Many methods that used to be in 'nitrogen.erl' are now in 'wf.erl'. Also, some method signatures in wf.erl have changed. * wf:get_page_module changed to wf:page_module * wf:q(ID) no longer returns a list, just the value. * wf:qs(ID) returns a list. * wf:depickle(Data, TTL) returns undefined if expired. Comet Pools * Behind the scenes, combined logic for comet and continue events. This now all goes through the same channel. You can switch async mode between comet and intervalled polling by calling wf:switch_to_comet() or wf:switch_to_polling(IntervalMS), respectively. * Comet processes can now register in a local pool (for a specific session) or a global pool (across the entire Nitrogen cluster). All other processes in the pool are alerted when a process joins or leaves. The first process in a pool gets a special init message. * Use wf:send(Pool, Message) or wf:send_global(Pool, Message) to broadcast a message to the entire pool. * wf:comet_flush() is now wf:flush() Architectural Changes * Nitrogen now runs _under_ other web frameworks (inets, mochiweb, yaws, misultin) using simple_bridge. In other words, you hook into the other frameworks like normal (mochiweb loop, yaws appmod, etc.) and then call nitrogen:run() from within that process. * Handlers are the new mechanism to extend the inner parts of Nitrogen, such as session storage, authentication, etc. * New route handler code means that pages can exist in any namespace, don't have to start with /web/... (see <API key> and named_route_handler) * Changed interface to elements and actions, any custom elements and actions will need tweaks. * sync:go() recompiles any changed files more intelligently by scanning for Emakefiles. * New ability to package Nitrogen projects as self-contained directories using rebar. # Nitrogen 1.0 Changelog 2009-05-02 - Added changes and bugfixes by Tom McNulty. 2009-04-05 - Added a templateroot setting in .app file, courtesy of Ville Koivula. 2009-03-28 - Added file upload support. 2009-03-22 - Added alt text support to #image elements by Robert Schonberger. - Fixed bug, 'nitrogen create (PROJECT)' now does a recursive copy of the Nitrogen support files, by Jay Doane. - Added radio button support courtesy of Benjamin Nortier and Tom McNulty. 2009-03-16 - Added .app configuration setting to bind Nitrogen to a specific IP address, by Tom McNulty. 2009-03-08 - Added DatePicker element by Torbjorn Tornkvist. - Upgrade to JQuery 1.3.2 and JQuery UI 1.7. - Created initial VERSIONS file. - Added code from Tom McNulty to expose Mochiweb loop. - Added coverage code from Michael Mullis, including lib/coverize submodule. - Added wf_platform:get_peername/0 code from Marius A. Eriksen. 2009-03-07 - Added code by Torbjorn Tornkvist: Basic Authentication, Hostname settings, access to HTTP Headers, and a Max Length validator. 2009-01-26 - Added Gravatar support by Dan Bravender. 2009-01-24 - Add code-level documentation around comet. - Fix bug where comet functions would continue running after a user left the page. - Apply patch by Tom McNulty to allow request object access within the route/1 function. - Apply patch by Tom McNulty to correctly bind binaries. - Apply patch by Tom McNulty for wf_tags library to correctly handle binaries. 2009-01-16 - Clean up code around timeout events. (Events that will start running after X seconds on the browser.) 2009-01-08 - Apply changes by Jon Gretar to support 'nitrogen create PROJECT' and 'nitrogen page /web/page' scripts. - Finish putting all properties into .app file. Put request/1 into application module file. - Add ability to route through route/1 in application module file. - Remove need for wf_global.erl - Start Yaws process underneath the main Nitrogen supervisor. (Used to be separate.) 2009-01-06 - Make Nitrogen a supervised OTP application, startable and stoppable via nitrogen:start() and nitrogen:stop(). - Apply changes by Dave Peticolas to fix session bugs and turn sessions into supervised processes. 2009-01-04 - Update sync module, add mirror module. These tools allow you to deploy and start applications on a bare remote node. 2009-01-03 - Allow Nitrogen to be run as an OTP application. See Quickstart project for example. - Apply Tom McNulty's patch to create and implement wf_tags library. Emit html tags more cleanly. - Change templates to allow multiple callbacks, and use first one that is defined. Basic idea and starter code by Tom McNulty. - Apply Martin Scholl's patch to optimize copy_to_baserecord in wf_utils.
package gogo import ( "net/http" "net/http/httptest" "testing" "github.com/golib/assert" ) func Test_NewResponse(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) it.Implements((*Responser)(nil), response) it.Equal(http.StatusOK, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func <API key>(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.<API key>) it.Equal(http.<API key>, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func <API key>(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.<API key>) response.FlushHeader() it.Equal(http.<API key>, recorder.Code) it.NotEqual(nonHeaderFlushed, response.Size()) // no effect after flushed headers response.WriteHeader(http.StatusOK) it.Equal(http.StatusOK, response.Status()) response.FlushHeader() it.NotEqual(http.StatusOK, recorder.Code) } func Test_ResponseWrite(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() hello := []byte("Hello,") world := []byte("world!") expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(hello) response.Write(world) it.True(response.HeaderFlushed()) it.Equal(len(expected), response.Size()) it.Equal(expected, recorder.Body.Bytes()) } func <API key>(b *testing.B) { b.ReportAllocs() b.ResetTimer() hello := []byte("Hello,") world := []byte("world!") recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Write(hello) response.Write(world) } } func Test_ResponseHijack(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(expected) it.True(response.HeaderFlushed()) it.Equal(recorder, response.(*Response).ResponseWriter) it.Equal(len(expected), response.Size()) response.Hijack(httptest.NewRecorder()) it.False(response.HeaderFlushed()) it.NotEqual(recorder, response.(*Response).ResponseWriter) it.Equal(nonHeaderFlushed, response.Size()) } func <API key>(b *testing.B) { b.ReportAllocs() b.ResetTimer() recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Hijack(recorder) } }
#if !defined(<API key>) #define <API key> #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Dialog3.h : header file // CDialog3 dialog class CDialog3 : public CDialog { // Construction public: CDialog3(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDialog3) enum { IDD = IDD_DIALOG3 }; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDialog3) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDialog3) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(<API key>)
# Load DSL and set up stages require 'capistrano/setup' # Include default deployment tasks require 'capistrano/deploy' # Include tasks from other gems included in your Gemfile require 'capistrano/rvm' require 'capistrano/bundler' require 'capistrano/rails' require 'capistrano/rails/migrations' require 'capistrano/nginx_unicorn' require 'capistrano/rails/assets' # Load custom tasks from `lib/capistrano/tasks` if you have any defined
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var saltRounds = 10; var userSchema = new mongoose.Schema({ email: { type: String, index: {unique: true} }, password: String, name: String }); //hash password userSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds)); } userSchema.methods.validPassword = function(password){ return bcrypt.compareSync(password, this.password); } var User = mongoose.model('User',userSchema); module.exports = User;
<?php namespace Wolphy\Jobs; use Illuminate\Bus\Queueable; abstract class Job { use Queueable; }
#!/bin/sh echo "Stopping web-server ..." COUNT_PROCESS=1 while [ $COUNT_PROCESS -gt 0 ] do COUNT_PROCESS=`ps -Aef | grep node | grep -c server.js` if [ $COUNT_PROCESS -gt 0 ]; then PID_PROCESS=`ps -Aef | grep node | grep server.js | awk '{print $2}'` if [ ! -z "$PID_PROCESS" ]; then echo "Killing web server PID=$PID_PROCESS" kill "$PID_PROCESS" fi fi echo "Waiting on web-server to stop ..." sleep 1 done echo "This web-server is stopped" exit 0
<?php namespace <API key>; if (\class_exists('<API key>')) { return; } class <API key> { } \class_alias('<API key>', '<API key>', \false);
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' from layers_basic import LW_Layer, default_data_format from <API key> import conv_output_length class _LW_Pooling1D(LW_Layer): input_dim = 3 def __init__(self, pool_size=2, strides=None, padding='valid'): if strides is None: strides = pool_size assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.pool_length = pool_size self.stride = strides self.border_mode = padding def <API key>(self, input_shape): length = conv_output_length(input_shape[1], self.pool_length, self.border_mode, self.stride) return (input_shape[0], length, input_shape[2]) class LW_MaxPooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_MaxPooling1D, self).__init__(pool_size, strides, padding) class LW_AveragePooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_AveragePooling1D, self).__init__(pool_size, strides, padding) class _LW_Pooling2D(LW_Layer): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): if data_format == 'default': data_format = default_data_format assert data_format in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = padding self.dim_ordering = data_format def <API key>(self, input_shape): if self.dim_ordering == 'channels_first': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'channels_last': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.pool_size[0], self.border_mode, self.strides[0]) cols = conv_output_length(cols, self.pool_size[1], self.border_mode, self.strides[1]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], rows, cols) elif self.dim_ordering == 'channels_last': return (input_shape[0], rows, cols, input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_MaxPooling2D, self).__init__(pool_size, strides, padding, data_format) class LW_AveragePooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_AveragePooling2D, self).__init__(pool_size, strides, padding, data_format) class _LW_Pooling3D(LW_Layer): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): if dim_ordering == 'default': dim_ordering = default_data_format assert dim_ordering in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.dim_ordering = dim_ordering def <API key>(self, input_shape): if self.dim_ordering == 'channels_first': len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] elif self.dim_ordering == 'channels_last': len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) len_dim1 = conv_output_length(len_dim1, self.pool_size[0], self.border_mode, self.strides[0]) len_dim2 = conv_output_length(len_dim2, self.pool_size[1], self.border_mode, self.strides[1]) len_dim3 = conv_output_length(len_dim3, self.pool_size[2], self.border_mode, self.strides[2]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3) elif self.dim_ordering == 'channels_last': return (input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_MaxPooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) class LW_AveragePooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_AveragePooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) class _LW_GlobalPooling1D(LW_Layer): def __init__(self): pass def <API key>(self, input_shape): return (input_shape[0], input_shape[2]) class <API key>(_LW_GlobalPooling1D): pass class <API key>(_LW_GlobalPooling1D): pass class _LW_GlobalPooling2D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def <API key>(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[3]) else: return (input_shape[0], input_shape[1]) class <API key>(_LW_GlobalPooling2D): pass class <API key>(_LW_GlobalPooling2D): pass class _LW_GlobalPooling3D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def <API key>(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[4]) else: return (input_shape[0], input_shape[1]) class <API key>(_LW_GlobalPooling3D): pass class <API key>(_LW_GlobalPooling3D): pass if __name__ == '__main__': pass
class CreateEventTypes < ActiveRecord::Migration def change create_table :event_types do |t| t.string :name, :limit => 80 t.timestamps end end end
require "empty_port/version" require 'socket' require 'timeout' # ## Example # require 'empty_port' # class YourServerTest < Test::Unit::TestCase # def setup # @port = EmptyPort.get # @server_pid = Process.fork do # server = TCPServer.open('localhost', @port) # end # EmptyPort.wait(@port) # end # def <API key> # end # def teardown # Process.kill(@server_pid) # end # end module EmptyPort class NotFoundException < Exception; end module ClassMethods MIN_PORT_NUMBER = 49152 MAX_PORT_NUMBER = 65535 # get an empty port except well-known-port. def get random_port = MIN_PORT_NUMBER + ( rand() * 1000 ).to_i while random_port < MAX_PORT_NUMBER begin sock = TCPSocket.open('localhost', random_port) sock.close rescue Errno::ECONNREFUSED => e return random_port end random_port += 1 end raise NotFoundException end def listened?(port) begin sock = TCPSocket.open('localhost', port) sock.close return true rescue Errno::ECONNREFUSED return false end end DEFAULT_TIMEOUT = 2 DEFAULT_INTERVAL = 0.1 def wait(port, options={}) options[:timeout] ||= DEFAULT_TIMEOUT options[:interval] ||= DEFAULT_INTERVAL timeout(options[:timeout]) do start = Time.now loop do if self.listened?(port) finished = Time.now return finished - start end sleep(options[:interval]) end end end end extend ClassMethods end
.vertical-center { min-height: 100%; /* Fallback for browsers do NOT support vh unit */ min-height: 100vh; /* These two lines are counted as one :-) */ display: flex; align-items: center; } @media (min-width: 768px){ #wrapper {/*padding-right: 225px;*/ padding-left: 0;} .side-nav{right: 0;left: auto;} } /* Global Styles */ body { background-color: #222; } #wrapper { padding-left: 0; } #page-wrapper { width: 100%; padding: 0; background-color: #fff; } .huge { font-size: 50px; line-height: normal; } @media(min-width:768px) { #wrapper { padding-left: 225px; } #page-wrapper { padding: 10px; margin-top: 20px; } } /* Top Navigation */ .top-nav { padding: 0 15px; } .top-nav>li { display: inline-block; float: left; } .top-nav>li>a { padding-top: 15px; padding-bottom: 15px; line-height: 20px; color: #999; } .top-nav>li>a:hover, .top-nav>li>a:focus, .top-nav>.open>a, .top-nav>.open>a:hover, .top-nav>.open>a:focus { color: #fff; background-color: #000; } .top-nav>.open>.dropdown-menu { float: left; position: absolute; margin-top: 0; border: 1px solid rgba(0,0,0,.15); <API key>: 0; <API key>: 0; background-color: #fff; -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); box-shadow: 0 6px 12px rgba(0,0,0,.175); } .top-nav>.open>.dropdown-menu>li>a { white-space: normal; } ul.message-dropdown { padding: 0; max-height: 250px; overflow-x: hidden; overflow-y: auto; } li.message-preview { width: 275px; border-bottom: 1px solid rgba(0,0,0,.15); } li.message-preview>a { padding-top: 15px; padding-bottom: 15px; } li.message-footer { margin: 5px 0; } ul.alert-dropdown { width: 200px; } .alert-danger { margin-top: 50px; } /* Side Navigation */ @media(min-width:768px) { .side-nav { position: fixed; top: 51px; /* left: 225px;*/ left: 0px; width: 225px; /* margin-left: -225px;*/ border: none; border-radius: 0; overflow-y: auto; background-color: #222; bottom: 0; overflow-x: hidden; padding-bottom: 40px; } .side-nav>li>a { width: 225px; } .side-nav li a:hover, .side-nav li a:focus { outline: none; background-color: #000 !important; } } .side-nav>li>ul { padding: 0; } .side-nav>li>ul>li>a { display: block; padding: 10px 15px 10px 38px; text-decoration: none; color: #999; } .side-nav>li>ul>li>a:hover { color: #fff; } /* Flot Chart Containers */ .flot-chart { display: block; height: 400px; } .flot-chart-content { width: 100%; height: 100%; } /* Custom Colored Panels */ .huge { font-size: 40px; } .panel-green { border-color: #5cb85c; } .panel-green > .panel-heading { border-color: #5cb85c; color: #fff; background-color: #5cb85c; } .panel-green > a { color: #5cb85c; } .panel-green > a:hover { color: #3d8b3d; } .panel-red { border-color: #d9534f; } .panel-red > .panel-heading { border-color: #d9534f; color: #fff; background-color: #d9534f; } .panel-red > a { color: #d9534f; } .panel-red > a:hover { color: #b52b27; } .panel-yellow { border-color: #f0ad4e; } .panel-yellow > .panel-heading { border-color: #f0ad4e; color: #fff; background-color: #f0ad4e; } .panel-yellow > a { color: #f0ad4e; } .panel-yellow > a:hover { color: #df8a13; } .navbar-nav > li > ul > li.active { background: rgba(9, 9, 9, 0.57); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> button </title> </head> <body> <form action="http: <button type="button"><b></b></button><br/> <button type="submit"><img sec="./img/3.jpg" alt=""></button><br/> </form> </body> </html>
layout: post title: Tweets date: 2019-08-08 summary: These are the tweets for August 8, 2019. categories:
import type { FormatRelativeFn } from '../../../types' const <API key> = { lastWeek: "'గత' eeee p", // CLDR #1384 yesterday: "'నిన్న' p", // CLDR #1393 today: "'ఈ రోజు' p", // CLDR #1394 tomorrow: "'రేపు' p", // CLDR #1395 nextWeek: "'తదుపరి' eeee p", // CLDR #1386 other: 'P', } const formatRelative: FormatRelativeFn = (token, _date, _baseDate, _options) => <API key>[token] export default formatRelative
INSERT INTO customers(id, name) VALUES (1, 'Jane Woods'); INSERT INTO customers(id, name) VALUES (2, 'Michael Li'); INSERT INTO customers(id, name) VALUES (3, 'Heidi Hasselbach'); INSERT INTO customers(id, name) VALUES (4, 'Rahul Pour');
#ifndef <API key> #define <API key> #include "../../../bitcoin/<API key>.hpp" #include <string> #include <vector> #include <utils/DerivationScheme.hpp> #include "../../../utils/Option.hpp" #include "../../../preferences/Preferences.hpp" #include "../../../api/Configuration.hpp" #include "../../../api/DynamicObject.hpp" #include <api/Currency.hpp> #include <api/AccountCreationInfo.hpp> #include <api/<API key>.hpp> #include <api/Keychain.hpp> #include <bitcoin/BitcoinLikeAddress.hpp> namespace ledger { namespace core { class BitcoinLikeKeychain: public api::Keychain { public: enum KeyPurpose { RECEIVE, CHANGE }; public: using Address = std::shared_ptr<BitcoinLikeAddress>; BitcoinLikeKeychain( const std::shared_ptr<api::DynamicObject>& configuration, const api::Currency& params, int account, const std::shared_ptr<Preferences>& preferences); virtual bool markAsUsed(const std::vector<std::string>& addresses); virtual bool markAsUsed(const std::string& address, bool needExtendKeychain = true); virtual bool markPathAsUsed(const DerivationPath& path, bool needExtendKeychain = true) = 0; virtual std::vector<Address> <API key>(uint32_t from, uint32_t to) = 0; virtual std::vector<std::string> <API key>(uint32_t from, uint32_t to) = 0; virtual std::vector<Address> <API key>(KeyPurpose purpose, uint32_t from, uint32_t to) = 0; virtual Address getFreshAddress(KeyPurpose purpose) = 0; virtual std::vector<Address> getFreshAddresses(KeyPurpose purpose, size_t n) = 0; virtual Option<KeyPurpose> getAddressPurpose(const std::string& address) const = 0; virtual Option<std::string> <API key>(const std::string& address) const = 0; virtual bool isEmpty() const = 0; int getAccountIndex() const; const api::<API key>& <API key>() const; const api::Currency& getCurrency() const; virtual Option<std::vector<uint8_t>> getPublicKey(const std::string& address) const = 0; std::shared_ptr<api::DynamicObject> getConfiguration() const; const DerivationScheme& getDerivationScheme() const; const DerivationScheme& <API key>() const; std::string getKeychainEngine() const; bool isSegwit() const; bool isNativeSegwit() const; virtual std::string getRestoreKey() const = 0; virtual int32_t <API key>() const = 0; virtual bool contains(const std::string& address) const = 0; virtual std::vector<Address> getAllAddresses() = 0; virtual int32_t <API key>() const = 0; static bool isSegwit(const std::string &keychainEngine); static bool isNativeSegwit(const std::string &keychainEngine); std::shared_ptr<Preferences> getPreferences() const; protected: DerivationScheme& getDerivationScheme(); private: const api::Currency _currency; DerivationScheme _scheme; DerivationScheme _fullScheme; int _account; std::shared_ptr<Preferences> _preferences; std::shared_ptr<api::DynamicObject> _configuration; }; } } #endif //<API key>
<?php namespace AppBundle\Repository; /** * <API key> * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class <API key> extends \Doctrine\ORM\EntityRepository { }
#!/usr/bin/env ruby #Example handler file.. infile = ARGV.first outfile = File.basename(infile, ".tif") + ".jpg.tif" system("~/cm/processing_scripts/rgb_to_jpeg_tif.rb --internal-mask #{infile} #{outfile}")
using Newtonsoft.Json; using ProtoBuf; using ITK.ModelManager; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Steam.Models { [Model("SteamPlayerBans")] [ProtoContract] [JsonObject(MemberSerialization.OptIn)] public class PlayerBans { <summary> A string containing the player's 64 bit ID. </summary> [JsonProperty("SteamID")] [ProtoMember(1, IsRequired = true)] public ulong SteamId {get; set;} <summary> Boolean indicating whether or not the player is banned from Community </summary> [JsonProperty("CommunityBanned")] [ProtoMember(2)] public bool IsCommunityBanned {get; set;} <summary> Boolean indicating whether or not the player has VAC bans on record. </summary> [JsonProperty("VACBanned")] [ProtoMember(3)] public bool IsVACBanned {get; set;} <summary> Amount of VAC bans on record. </summary> [JsonProperty("NumberOfVACBans")] [ProtoMember(4)] public int VACBanCount {get; set;} <summary> Amount of days since last ban. </summary> [JsonProperty("DaysSinceLastBan")] [ProtoMember(5)] public int DaysSinceLastBan {get; set;} <summary> String containing the player's ban status in the economy. If the player has no bans on record the string will be "none", if the player is on probation it will say "probation", and so forth. </summary> [JsonProperty("EconomyBan")] [ProtoMember(6)] public string EconomyBan {get; set;} public override int GetHashCode() { return SteamId.GetHashCode(); } public override bool Equals(object obj) { var other = obj as PlayerBans; return other != null && SteamId.Equals(other.SteamId); } } }
layout: post title: ESPN took a picture of me categories: link Check [this link](http://espn.go.com/college-football/story/_/id/9685394/<API key>) for some story about Bo Pelini's goofing off, and -- look there in the last photo! -- it's some goofball in a Nebraska trilby.
// GFTestAppDelegate.h // TestChaosApp #import <UIKit/UIKit.h> @interface GFTestAppDelegate : UIResponder <<API key>> @property (strong, nonatomic) UIWindow *window; @end
var modules = { "success" : [ {id: 1, name:"", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'} ], "error" : { code : "0200-ERROR", msg : "There are some errors occured." } } module.exports = { "modules": modules }
const { createServer, plugins: { queryParser, serveStatic } } = require('restify'); const { join } = require('path'); const fetch = require('node-fetch'); const proxy = require('<API key>'); const { PORT = 5000 } = process.env; const server = createServer(); server.use(queryParser()); server.get('/', async (req, res, next) => { if (!req.query.b) { const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { headers: { origin: 'http://localhost:5000' }, method: 'POST' }); if (!tokenRes.ok) { return res.send(500); } const { token } = await tokenRes.json(); return res.send(302, null, { location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}` }); } return serveStatic({ directory: join(__dirname, 'dist'), file: 'index.html' })(req, res, next); }); server.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' })); server.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));
define(["core/js/layout/Panel"], function (Panel) { var view = Panel.extend({ /*Panel start*/ title:"-", help:"", brief:"", /*Panel End*/ oninitialized:function(triggerEvent){ this._super(); this.mainRegion={ comXtype:$Component.TREE, comConf:{ data:[this.getModuleTree("core/js/base/AbstractView")], } }; var that = this; this.footerRegion = { comXtype: $Component.TOOLSTRIP, comConf: { /*Panel start*/ textAlign: $TextAlign.RIGHT, items: [{ text: "", onclick: function (e) { that.getMainRegionRef().getComRef().expandAll(); }, },{ text: "", onclick: function (e) { that.getMainRegionRef().getComRef().collapseAll(); }, }] /*Panel End*/ } }; }, getModuleTree:function(moduleName,arr){ var va = window.rtree.tree[moduleName]; var tree = {title: moduleName}; if(!arr){ arr = []; }else{ if(_.contains(arr,moduleName)){ return false; } } arr.push(moduleName); if(va&&va.deps&&va.deps.length>0){ tree.children = []; tree.folder=true; for(var i=0;i<va.deps.length;i++){ var newTree = this.getModuleTree(va.deps[i],arr); if(newTree){ tree.children.push(newTree); }else{ if(!tree.count){ tree.count = 0; } tree.count++; } } } return tree; } }); return view; });
# Django Media Albums [![Build Status](https: This app is used to create albums consisting of any combination of the following: * Photos * Video files * Audio files This app also optionally allows regular (non-staff) users to upload photos. This app requires Django 1.8, 1.9, 1.10, or 1.11. ## Installation Step 1 of 5: Install the required packages Install using pip: bash pip install django-media-albums If you will be using the templates that come with this app, also install these packages using pip: bash pip install <API key> sorl-thumbnail If you will be allowing regular (non-staff) users to upload photos and will be using the `upload.html` template that comes with this app, also install the `django-crispy-forms` package using pip: bash pip install django-crispy-forms Step 2 of 5: Update `settings.py` Make sure the following settings are all configured the way you want them in your `settings.py`: MEDIA_ROOT MEDIA_URL STATIC_ROOT STATIC_URL If you will be allowing regular (non-staff) users to upload photos, you will also need to have the `DEFAULT_FROM_EMAIL` setting present in your `settings.py` (for the notification email that gets sent out when a user uploads a photo). Add `'media_albums'` to your `settings.py` INSTALLED_APPS: python INSTALLED_APPS = ( 'media_albums', ) If you will be using the templates that come with this app, also add the following to your `settings.py` INSTALLED_APPS: python INSTALLED_APPS = ( '<API key>', 'sorl.thumbnail', ) If you will be allowing regular (non-staff) users to upload photos and will be using the `upload.html` template that comes with this app, also add `'crispy_forms'` to your `settings.py` INSTALLED_APPS and make sure the `<API key>` setting is configured the way you want it: python INSTALLED_APPS = ( 'crispy_forms', ) <API key> = 'bootstrap3' If you will be enabling audio and/or video and will be using the templates that come with this app, also enable the `'django.template.context_processors.media'` context processor: python TEMPLATES = [ { 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.media', ], }, }, ] Step 3 of 5: Update `urls.py` Create a URL pattern in your `urls.py`: python from django.conf.urls import include, url urlpatterns = [ url(r'^media-albums/', include('media_albums.urls')), ] Step 4 of 5: Add the database tables Run the following command: bash python manage.py migrate Step 5 of 5: Update your project's `base.html` template (if necessary) If you will be using the templates that come with this app, make sure your project has a `base.html` template and that it has these blocks: content extra_styles ## Configuration To override any of the default settings, create a dictionary named `MEDIA_ALBUMS` in your `settings.py` with each setting you want to override. For example, if you wanted to enable audio and video, but leave all of the other settings alone, you would add this to your `settings.py`: python MEDIA_ALBUMS = { 'audio_files_enabled': True, 'video_files_enabled': True, } These are the settings: `photos_enabled` (default: `True`) When set to `True`, albums may contain photos. `audio_files_enabled` (default: `False`) When set to `True`, albums may contain audio files. `<API key>` (default: `'mp3'`) When an audio file is uploaded, the "Audio file 1" field must have this extension. This setting is only relevant if `audio_files_enabled` is set to `True`. `<API key>` (default: `'ogg'`) When an audio file is uploaded, the "Audio file 2" field must have this extension. This setting is only relevant if `audio_files_enabled` is set to `True`. `<API key>` (default: `False`) When set to `True`, the "Audio file 2" field will be marked as required. This setting is only relevant if `audio_files_enabled` is set to `True`. `video_files_enabled` (default: `False`) When set to `True`, albums may contain video files. `<API key>` (default: `'mp4'`) When an video file is uploaded, the "Video file 1" field must have this extension. This setting is only relevant if `video_files_enabled` is set to `True`. `<API key>` (default: `'webm'`) When an video file is uploaded, the "Video file 2" field must have this extension. This setting is only relevant if `video_files_enabled` is set to `True`. `<API key>` (default: `False`) When set to `True`, the "Video file 2" field will be marked as required. This setting is only relevant if `video_files_enabled` is set to `True`. `<API key>` (default: `False`) When set to `True`, regular (non-staff) users may upload photos. However, they still must be approved by a staff user. `<API key>` (default: `True`) When set to `True`, regular (non-staff) users may only upload photos if they are logged in. This setting is only relevant if `<API key>` is set to `True`. `<API key>` (default: `'User Photos'`) When a staff user approves a photo uploaded by a regular (non-staff) user, the photo will be added to the album with this name. This setting is only relevant if `<API key>` is set to `True`. `<API key>` (default: `'user-photos'`) When a staff user approves a photo uploaded by a regular (non-staff) user, the photo will be added to the album with this slug. This setting is only relevant if `<API key>` is set to `True`. `paginate_by` (default: `10`) This setting determines how many items can be on a single page. This applies to the list of albums as well as the list of items within albums.
<! Safe sample input : get the $_GET['userData'] in an array sanitize : settype (float) File : unsafe, use of untrusted data in a comment <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. <!DOCTYPE html> <html> <head> <! <?php $array = array(); $array[] = 'safe' ; $array[] = $_GET['userData'] ; $array[] = 'safe' ; $tainted = $array[1] ; if(settype($tainted, "float")) $tainted = $tainted ; else $tainted = 0.0 ; echo $tainted ; ?> </head> <body> <h1>Hello World!</h1> </body> </html>
$('#modalUploader').on('show.bs.modal', function (event) { var uploader = new qq.FileUploaderBasic({ element: document.getElementById('file-uploader-demo1'), button: document.getElementById('areaSubir'), action: '/Files/Upload', params: { ruta: $('#RutaActual').val() }, allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'], multiple: false, onComplete: function (id, fileName, responseJSON) { $.gritter.add({ title: 'Upload file', text: responseJSON.message }); }, onSubmit: function (id, fileName) { var strHtml = "<li>" + fileName + "</li>"; $("#dvxArchivos").append(strHtml); } }); }); $('#modalUploader').on('hidden.bs.modal', function () { RecargarRuta(); }) function AbrirCarpeta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function AbrirRuta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function RecargarRuta() { AbrirCarpeta($("#RutaActual").val()); } function EliminarArchivo(pRuta) { if (confirm("Are you sure that want to delete this file?")) { $.gritter.add({ title: 'Delete file', text: "File deleted" }); $("#ArchivoParaEliminar").val(pRuta); AbrirCarpeta($("#RutaActual").val()); } } function SubirNivel() { if ($("#TieneSuperior").val() == "1") { var strRutaAnterior = $("#RutaSuperior").val(); AbrirRuta(strRutaAnterior); } } function IrInicio() { AbrirRuta($("#RutaRaiz").val()); } function AbrirDialogoArchivo() { $("#modalUploader").modal(); } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^& var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); }
// setToken when re-connecting var originalReconnect = Meteor.connection.onReconnect; Meteor.connection.onReconnect = function() { setToken(); if(originalReconnect) { originalReconnect(); } }; if(Meteor.status().connected) { setToken(); } function setToken() { var firewallHumanToken = Cookie.get('sikka-human-token'); Meteor.call('setSikkaHumanToken', firewallHumanToken); } // reloading the page window.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands'); sikkaCommands.find({}).observe({ added: function(command) { if(command._id === "reload") { location.reload(); } } });
<% nameScope = @config['name_scope'] %> </div> </div> </div> <footer class="cortana-footer"> Build with love using Trulia's <a href="https: </footer> </div> <script src="theme-build/js/vendors.min.js"></script> <script type="text/javascript"> var jQuery_no_conflict = $.noConflict(true); </script> <script src="theme-build/js/main.js"></script> <script type="text/javascript"> function TypeaheadCtrl($scope) { $scope.selected = undefined; $scope.searchData = <%= "[" %> <% @pages.each do |file_name, page| %> <% if not page[:blocks].empty? %> <% page[:blocks].each do |block| %> <% file_path = block[:categories][0].to_s.gsub(' ', '_').downcase + '.html' %> <% file_id = "#"+block[:name].to_s %> <%= "{" %> <%= "\"title\": \""+block[:title].to_s+"\"," %> <%= "\"breadcrumb\": \""+block[:categories][0].to_s+" > "+block[:title]+"\"," %> <%= "\"path\": \""+file_path+file_id+"\"" %> <%= "}," %> <% end %> <% end %> <% end %> <%= "{}]" %>; $scope.onSelect = function ($item, $model, $label) { window.location.replace($item.path); }; } </script> <script type="text/ng-template" id="customTemplate.html"> <a href="{{match.model.path}}"> <p class="<API key>">{{match.model.title}}</p> <p class="cortana-search-path">{{match.model.breadcrumb}}</p> </a> </script> <% if @config['js_include'].to_s.strip.length != 0 %> <% @config['js_include'].each do |js| %> <script type="text/javascript" src="<%= js %>"></script> <% end %> <% end %> <!-- Source Components --> <% if @config['components_include'].to_s.strip.length != 0 %> <% @config['components_include'].each do |component| %> <link rel="import" href="<%= component %>"> <% end %> <% end %> </body> </html>
// rbLinkedList.h // rbLinkedList #pragma once #include <string> struct Node { int key; Node *next; }; class rbLinkedList { public: /** Constructor for the rbLinkedList class. */ rbLinkedList(); /** Deconstructor for the rbLinkedList class. */ ~rbLinkedList(); /** Determine if the collection is empty or not. * @return: A bool that will be true if the collection is empty and false * otherwise. */ bool IsEmpty(); /** Determine the number of nodes within the linked list. * @return: An integer that represents the number of nodes between the head * and tail nodes. */ int Size(); void AddKey(int key); void RemoveKey(int key); std::string ToString(); private: Node *h_; Node *z_; };
// KAAppDelegate.h // <API key> #import <UIKit/UIKit.h> @interface KAAppDelegate : UIResponder <<API key>> @property (strong, nonatomic) UIWindow *window; @end
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Basic Example</title> <link rel="stylesheet" href="css/base.css" /> <script src="../../asset/react/react.js"></script> <script src="../../asset/react/react-dom.js"></script> <script src="../../asset/react/browser.min.js"></script> <script src="js/app/index.jsx" type="text/babel"></script> </head> <body> <h1>React component HTML React.createClass </h1> <h1> this.props </h1> <h1> class className for htmlFor class for JavaScript </h1> <div id="message"></div> </body> </html>
using System.Collections.ObjectModel; using System.ComponentModel; using GalaSoft.MvvmLight.Command; namespace Treehopper.Mvvm.ViewModels { <summary> A delegate called when the selected board changes </summary> <param name="sender">The caller</param> <param name="e">The new selected board</param> public delegate void <API key>(object sender, <API key> e); <summary> A delegate called when the selected board has connected </summary> <param name="sender">The caller</param> <param name="e">The connected board</param> public delegate void <API key>(object sender, <API key> e); <summary> A delegate called when the selected board has disconnected </summary> <param name="sender">The caller</param> <param name="e">The disconnected board</param> public delegate void <API key>(object sender, <API key> e); <summary> Base interface for the selector view model </summary> public interface ISelectorViewModel : <API key> { <summary> Get the collection of boards </summary> <API key><TreehopperUsb> Boards { get; } <summary> Whether the board selection can be changed </summary> bool <API key> { get; set; } <summary> The currently selected board </summary> TreehopperUsb SelectedBoard { get; set; } <summary> Occurs when the window closes </summary> RelayCommand WindowClosing { get; set; } <summary> Occurs when the connection occurs </summary> RelayCommand ConnectCommand { get; set; } <summary> Connect button text </summary> string ConnectButtonText { get; set; } <summary> Close command </summary> RelayCommand CloseCommand { get; set; } <summary> Board selection changed </summary> event <API key> <API key>; <summary> Board connected </summary> event <API key> OnBoardConnected; <summary> Board disconnected </summary> event <API key> OnBoardDisconnected; } }
import React from 'react'; import ReactDOM from 'react-dom'; import componentOrElement from 'react-prop-types/lib/componentOrElement'; import ownerDocument from './utils/ownerDocument'; import getContainer from './utils/getContainer'; /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: React.PropTypes.oneOfType([ componentOrElement, React.PropTypes.func ]), /** * Classname to use for the Portal Component */ className: React.PropTypes.string }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, <API key>(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this.<API key>.removeChild(this._overlayTarget); this.<API key> = getContainer(nextProps.container, ownerDocument(this).body); this.<API key>.appendChild(this._overlayTarget); } }, <API key>() { this._unrenderOverlay(); this.<API key>(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); if (this.props.className) { this._overlayTarget.className = this.props.className; } this.<API key> = getContainer(this.props.container, ownerDocument(this).body); this.<API key>.appendChild(this._overlayTarget); } }, <API key>() { if (this._overlayTarget) { this.<API key>.removeChild(this._overlayTarget); this._overlayTarget = null; } this.<API key> = null; }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = ReactDOM.<API key>( this, overlay, this._overlayTarget ); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this.<API key>(); } }, _unrenderOverlay() { if (this._overlayTarget) { ReactDOM.<API key>(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getMountNode(){ return this._overlayTarget; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; } }); export default Portal;
dojo.provide("plugins.dijit.SyncDialog"); // HAS A dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ValidationTextBox"); // INHERITS dojo.require("plugins.core.Common"); dojo.declare( "plugins.dijit.SyncDialog", [ dijit._Widget, dijit._Templated, plugins.core.Common ], { //Path to the template of this widget. templatePath: dojo.moduleUrl("plugins", "dijit/templates/syncdialog.html"), // OR USE @import IN HTML TEMPLATE cssFiles : [ dojo.moduleUrl("plugins", "dijit/css/syncdialog.css") ], // Calls dijit._Templated.widgetsInTemplate widgetsInTemplate : true, // PARENT plugins.workflow.Apps WIDGET parentWidget : null, // DISPLAYED MESSAGE message : null, constructor : function(args) { console.log("SyncDialog.constructor args:"); console.dir({args:args}); // LOAD CSS this.loadCSS(); }, postCreate : function() { ///console.log("SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()"); this.startup(); }, startup : function () { /console.log("SyncDialog.startup plugins.dijit.SyncDialog.startup()"); /console.log("SyncDialog.startup this.parentWidget: " + this.parentWidget); this.inherited(arguments); // SET UP DIALOG this.setDialogue(); // SET KEY LISTENER this.setKeyListener(); // ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING this.setNamespaceClass("syncDialog"); }, setKeyListener : function () { dojo.connect(this.dialog, "onkeypress", dojo.hitch(this, "handleOnKeyPress")); }, handleOnKeyPress: function (event) { var key = event.charOrCode; console.log("SyncDialog.handleOnKeyPress key: " + key); if ( key == null ) return; event.stopPropagation(); if ( key == dojo.keys.ESCAPE ) this.hide(); }, setNamespaceClass : function (ccsClass) { // ADD CSS NAMESPACE CLASS dojo.addClass(this.dialog.domNode, ccsClass); dojo.addClass(this.dialog.titleNode, ccsClass); dojo.addClass(this.dialog.closeButtonNode, ccsClass); }, show: function () { // SHOW THE DIALOGUE this.dialog.show(); this.message.focus(); }, hide: function () { // HIDE THE DIALOGUE this.dialog.hide(); }, doEnter : function(type) { // RUN ENTER CALLBACK IF 'ENTER' CLICKED console.log("SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()"); var inputs = this.validateInputs(["message", "details"]); console.log("SyncDialog.doEnter inputs:"); console.dir({inputs:inputs}); if ( ! inputs ) { console.log("SyncDialog.doEnter inputs is null. Returning"); return; } // RESET this.message.set('value', ""); this.details.value = ""; // HIDE this.hide(); // DO CALLBACK this.dialog.enterCallback(inputs); }, validateInputs : function (keys) { console.log("Hub.validateInputs keys: "); console.dir({keys:keys}); var inputs = new Object; this.isValid = true; for ( var i = 0; i < keys.length; i++ ) { console.log("Hub.validateInputs Doing keys[" + i + "]: " + keys[i]); inputs[keys[i]] = this.verifyInput(keys[i]); } console.log("Hub.validateInputs inputs: "); console.dir({inputs:inputs}); if ( ! this.isValid ) return null; return inputs; }, verifyInput : function (input) { console.log("Aws.verifyInput input: "); console.dir({this_input:this[input]}); var value = this[input].value; console.log("Aws.verifyInput value: " + value); var className = this.getClassName(this[input]); console.log("Aws.verifyInput className: " + className); if ( className ) { console.log("Aws.verifyInput this[input].isValid(): " + this[input].isValid()); if ( ! value || ! this[input].isValid() ) { console.log("Aws.verifyInput input " + input + " value is empty. Adding class 'invalid'"); dojo.addClass(this[input].domNode, 'invalid'); this.isValid = false; } else { console.log("SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'"); dojo.removeClass(this[input].domNode, 'invalid'); return value; } } else { if ( input.match(/;/) || input.match(/`/) ) { console.log("SyncDialog.verifyInput value is INVALID. Adding class 'invalid'"); dojo.addClass(this[input], 'invalid'); this.isValid = false; return null; } else { console.log("SyncDialog.verifyInput value is VALID. Removing class 'invalid'"); dojo.removeClass(this[input], 'invalid'); return value; } } return null; }, doCancel : function() { // RUN CANCEL CALLBACK IF 'CANCEL' CLICKED /console.log("SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()"); this.dialog.cancelCallback(); this.dialog.hide(); }, setDialogue : function () { // APPEND DIALOG TO DOCUMENT document.body.appendChild(this.dialog.domNode); this.dialog.parentWidget = this; // AVOID this._fadeOutDeferred NOT DEFINED ERROR this._fadeOutDeferred = function () {}; }, load : function (args) { console.log("SyncDialog.load args:"); console.dir({args:args}); if ( args.title ) { console.log("SyncDialog.load SETTING TITLE: " + args.title); this.dialog.set('title', args.title); } this.headerNode.innerHTML = args.header; if (args.message) this.message.set('value', args.message); if (args.details) this.details.value = args.details; //if (args.details) this.details.innerHTML(args.details); this.dialog.enterCallback = args.enterCallback; this.show(); } });
namespace TraktApiSharp.Objects.Basic.Json.Factories { using Objects.Basic.Json.Reader; using Objects.Basic.Json.Writer; using Objects.Json; internal class <API key> : IJsonIOFactory<ITraktCommentLike> { public IObjectJsonReader<ITraktCommentLike> CreateObjectReader() => new <API key>(); public IArrayJsonReader<ITraktCommentLike> CreateArrayReader() => new <API key>(); public IObjectJsonWriter<ITraktCommentLike> CreateObjectWriter() => new <API key>(); } }
package com.sdl.selenium.extjs3.button; import com.sdl.selenium.bootstrap.button.Download; import com.sdl.selenium.extjs3.ExtJsComponent; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; public class DownloadLink extends ExtJsComponent implements Download { public DownloadLink() { setClassName("DownloadLink"); setTag("a"); } public DownloadLink(WebLocator container) { this(); setContainer(container); } public DownloadLink(WebLocator container, String text) { this(container); setText(text, SearchType.EQUALS); } /** * Wait for the element to be activated when there is deactivation mask on top of it * * @param seconds time */ @Override public boolean waitToActivate(int seconds) { return getXPath().contains("ext-ux-livegrid") || super.waitToActivate(seconds); } /** * if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT. * Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome * Use only this: button.download("C:\\TestSet.tmx"); * return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false. * * @param fileName e.g. "TestSet.tmx" */ @Override public boolean download(String fileName) { openBrowse(); return executor.download(fileName, 10000L); } private void openBrowse() { executor.browse(this); } }
angular.module('perCapita.controllers', []) .controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService', function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) { $scope.loginData = $localStorage.getObject('userinfo', '{}'); $scope.reservation = {}; $scope.registration = {}; $scope.loggedIn = false; if (AuthService.isAuthenticated()) { $scope.loggedIn = true; $scope.username = AuthService.getUsername(); } // Create the login modal that we will use later $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function (modal) { $scope.modal = modal; }); // Triggered in the login modal to close it $scope.closeLogin = function () { $scope.modal.hide(); }; // Open the login modal $scope.login = function () { $scope.modal.show(); }; // Perform the login action when the user submits the login form $scope.doLogin = function () { console.log('Doing login', $scope.loginData); $localStorage.storeObject('userinfo', $scope.loginData); AuthService.login($scope.loginData); $scope.closeLogin(); }; $scope.logOut = function () { AuthService.logout(); $scope.loggedIn = false; $scope.username = ''; }; $rootScope.$on('login:Successful', function () { $scope.loggedIn = AuthService.isAuthenticated(); $scope.username = AuthService.getUsername(); }); $ionicModal.fromTemplateUrl('templates/register.html', { scope: $scope }).then(function (modal) { $scope.registerform = modal; }); $scope.closeRegister = function () { $scope.registerform.hide(); }; $scope.register = function () { $scope.registerform.show(); }; $scope.doRegister = function () { console.log('Doing registration', $scope.registration); $scope.loginData.username = $scope.registration.username; $scope.loginData.password = $scope.registration.password; AuthService.register($scope.registration); $timeout(function () { $scope.closeRegister(); }, 1000); }; $rootScope.$on('registration:Successful', function () { $localStorage.storeObject('userinfo', $scope.loginData); }); }]) .controller('<API key>', ['$scope', '$rootScope', '$state', '$stateParams', 'Favorites', function ($scope, $rootScope, $state, $stateParams, Favorites) { $scope.showFavButton = false; // Lookup favorites for a given user id Favorites.findById({id: $stateParams.id}) .$promise.then( function (response) { $scope.city = response; }, function (response) { $scope.message = "Error: " + response.status + " " + response.statusText; } ); }]) .controller('HomeController', ['$scope', 'perCapitaService', '$stateParams', '$rootScope', 'Favorites', '$ionicPlatform', '$<API key>', '$cordovaToast', function ($scope, perCapitaService, $stateParams, $rootScope, Favorites, $ionicPlatform, $<API key>, $cordovaToast) { $scope.showFavButton = $rootScope.currentUser; $scope.controlsData = {skills: $rootScope.skills}; // Look up jobs data $scope.doLookup = function () { $rootScope.skills = $scope.controlsData.skills; perCapitaService.lookup($scope.controlsData.skills); }; // Post process the jobs data, by adding Indeeds link and calculating jobsPer1kPeople and jobsRank $scope.updatePerCapitaData = function () { $scope.cities = perCapitaService.response.data.docs; var arrayLength = $scope.cities.length; for (var i = 0; i < arrayLength; i++) { var obj = $scope.cities[i]; obj.jobsPer1kPeople = Math.round(obj.totalResults / obj.population * 1000); obj.url = "https: } // rank jobs var sortedObjs; if (perCapitaService.isSkills) { sortedObjs = _.sortBy($scope.cities, 'totalResults').reverse(); } else { sortedObjs = _.sortBy($scope.cities, 'jobsPer1kPeople').reverse(); } $scope.cities.forEach(function (element) { element.jobsRank = sortedObjs.indexOf(element) + 1; }); if (!$scope.$$phase) { $scope.$apply(); } $rootScope.cities = $scope.cities; console.log("Loaded " + arrayLength + " results.") }; perCapitaService.<API key>($scope.updatePerCapitaData); $scope.addToFavorites = function () { delete $scope.city._id; delete $scope.city._rev; $scope.city.customerId = $rootScope.currentUser.id Favorites.create($scope.city); $ionicPlatform.ready(function () { $<API key>.schedule({ id: 1, title: "Added Favorite", text: $scope.city.city }).then(function () { console.log('Added Favorite ' + $scope.city.city); }, function () { console.log('Failed to add Favorite '); }); $cordovaToast .show('Added Favorite ' + $scope.city.city, 'long', 'center') .then(function (success) { // success }, function (error) { // error }); }); } if ($stateParams.id) { console.log("param " + $stateParams.id); $scope.city = $rootScope.cities.filter(function (obj) { return obj._id === $stateParams.id; })[0]; console.log($scope.city); } else { $scope.doLookup(); } }]) .controller('AboutController', ['$scope', function ($scope) { }]) .controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) { $scope.shouldShowDelete = false; $scope.refreshItems = function () { if ($rootScope.currentUser) { Favorites.find({ filter: { where: { customerId: $rootScope.currentUser.id } } }).$promise.then( function (response) { $scope.favorites = response; console.log("Got favorites"); }, function (response) { console.log(response); }); } else { $scope.message = "You are not logged in" } } $scope.refreshItems(); $scope.toggleDelete = function () { $scope.shouldShowDelete = !$scope.shouldShowDelete; console.log($scope.shouldShowDelete); } $scope.deleteFavorite = function (favoriteid) { var confirmPopup = $ionicPopup.confirm({ title: '<h3>Confirm Delete</h3>', template: '<p>Are you sure you want to delete this item?</p>' }); confirmPopup.then(function (res) { if (res) { console.log('Ok to delete'); Favorites.deleteById({id: favoriteid}).$promise.then( function (response) { $scope.favorites = $scope.favorites.filter(function (el) { return el.id !== favoriteid; }); $state.go($state.current, {}, {reload: false}); // $window.location.reload(); }, function (response) { console.log(response); $state.go($state.current, {}, {reload: false}); }); } else { console.log('Canceled delete'); } }); $scope.shouldShowDelete = false; } }]) ;
# VBA.ModernTheme Windows Phone Colour Palette and<p>Colour Selector using WithEvents Version 1.0.1 The *Windows Phone Theme Colours* is a tight, powerful, and well balanced palette. This tiny Microsoft Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing *WithEvents*, one of Access' hidden gems. ![General](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/ModernThemeHeader.png) Full documentation is found here: ![EE Logo](https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/EE%20Logo.png) [Create Windows Phone Colour Palette and Selector using WithEvents](https: <hr> *If you wish to support my work or need extended support or advice, feel free to:* <p> [<img src="https:
var http = require("http"); var querystring = require("querystring"); var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(preHeaders,preAnalysisFields,logName){ this.headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** * * @param * @return object */ ProxyAgent.prototype.getReqConfig = function(logName){ var _self=this; var Obj={}; Obj=Config[logName]; Obj.logger=Analysis.getLogger(logName); Obj.name=logName; return Obj; } ProxyAgent.prototype.doRequest=function(_req,_res){ var _self=this; _self.reqConf=_self.getReqConfig(this.logName); logger.debug(''+_self.reqConf.desc+""); var header_obj =this.packageHeaders(_req.headers,this.headNeeds); var url_obj = url.parse(request.url, true); var query_obj = url_obj.query; var postData = request.body|| ""; _res.setHeader("Content-Type", config.contentType); _res.setHeader(config.headerkey, config.headerval); var opts=_self.packData(header_obj,query_obj,postData); logger.debug(header_obj.mobileid +_self.reqConf.desc+ ''+opts[0].path +" data:"+ opts[1]); if(typeof(postData) =="object" && postData.redis_key.length>0){ this.getRedis(opts[0],opts[1]); } else{ this.httpProxy(opts[0],opts[1]); } } /** * get post * @param headers * @param query * @param body * @return [] */ ProxyAgent.prototype.packData=function(headers,query,body){ var _self=this; //resType ""==>GET,"body"==>POST,"json"==>poi,"raw"==> var type=_self.reqConf.resType || ""; body = body || ""; var len=0; var query_str=""; var body_str=""; if(type==""){ query=common.extends(query,headers); query_str = querystring.stringify(query, '&', '='); } else if(type=="body"){ body=common.extends(body,headers); body_str = querystring.stringify(body, '&', '='); len=body_str.length; if(body.redis_key){ this.redis={}; this.redis.redis_key=body.redis_key; } } else if(type=="json"){ query=common.extends(query,headers); query_str = 'json='+querystring.stringify(query, '&', '='); } else if(type=="raw"){ len=body.length; body_str=body; } var actionlocation = headers.actionlocation || ""; if(actionlocation==""){ actionlocation=query.actionlocation||""; } var opts=_self.getRequestOptions(len,actionlocation); opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str; return [opts,body_str]; } /** * * @param len * @param actiontion * @return object */ ProxyAgent.prototype.getRequestOptions=function(lenactionlocation){ var _self=this; var options = { //http host: _self.reqConf.host, port: _self.reqConf.port, path: _self.reqConf.path||"", headers : {'Connection' : 'keep-alive'} }; if(actionlocation.length>0){ options.path=actionlocation; } var rtype= _self.reqConf.reqType || ""; if(rtype.length>0){ options.headers['Content-Type']=rtype; } if(len>0){ options.headers['Content-Length']=len; } return options; } ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){ var obj={}; return obj; } /** * * @param request.headers * @param need fields ;split with ',' * @return object headers */ ProxyAgent.prototype.packageHeaders = function(headers) { var fields=arguments[1]||""; var query_obj = {}; var reqip = headers['x-real-ip'] || '0'; var forward = headers['x-forwarded-for'] || '0'; var osversion = headers['osversion'] || '0'; var devicemodel = headers['devicemodel'] || '0'; var manufacturername = headers['manufacturername'] || '0'; var actionlocation = headers['actionlocation']; var dpi = headers['dpi'] || '2.0'; var imsi = headers['imsi'] || '0'; // imsi var mobileid = headers['mobileid'] || '0'; // mibileid var version = headers['version'] || '0';// version var selflon = headers['selflon'] || '0'; var selflat = headers['selflat'] || '0'; var uid = headers['uid'] || '0'; var radius=headers['radius']||'0'; var platform=headers['platform']||"";// ios ,android var gender= headers['gender'] || '0'; query_obj.gender = gender; query_obj.reqip = reqip; query_obj.forward = forward; query_obj.osversion = osversion; query_obj.devicemodel = devicemodel; query_obj.manufacturername = manufacturername; query_obj.actionlocation = actionlocation; query_obj.dpi = dpi; query_obj.imsi = imsi; query_obj.mobileid = mobileid; query_obj.version = version; query_obj.selflon = selflon; query_obj.selflat = selflat; query_obj.uid = uid; query_obj.radius=radius; query_obj.platform=platform; if(fields.length > 0){ var afields = fields.split(","); var newObj = {}; for(var i = 0; i < afields.length ; i ++){ newObj[afields[i]] = query_obj[afields[i]] || ""; } return newObj; } else{ return query_obj; } } /** * http * @param options * @param reqData req.method== get */ ProxyAgent.prototype.httpProxy = function (options,reqData){ var _self=this; var TongjiObj={}; var req = http.request(options, function(res) { TongjiObj.statusCode = res.statusCode ||500; var tmptime=Date.now(); TongjiObj.restime = tmptime; TongjiObj.resEnd =tmptime; TongjiObj.ends = tmptime; TongjiObj.length = 0; TongjiObj.last = tmptime; var sbuffer=new SBuffer(); res.setEncoding("utf-8"); res.on('data', function (trunk) { sbuffer.append(trunk); }); res.on('end', function () { TongjiObj.resEnd = Date.now(); //doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt); _self.emmit("onDone",sbuffer,TongjiObj); }); }); req.setTimeout(timeout,function(){ req.emit('timeOut',{message:'have been timeout...'}); }); req.on('error', function(e) { TongjiObj.statusCode=500; _self.emmit("onDone","",500,TongjiObj); }); req.on('timeOut', function(e) { req.abort(); TongjiObj.statusCode=500; TongjiObj.last = Date.now(); _self.emmit("onDone","",500,TongjiObj); }); req.end(reqData); } /** * * @param redis_key * @param redis_time * @param resultBuffer */ ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) { redis_pool.acquire(function(err, client) { if (!err) { client.setex(redis_key, redis_time, resultBuffer, function(err, repliy) { redis_pool.release(client); }); logger.debug(redis_key + ''); } else { writeLogs.logs(Analysis.getLogger('error'), 'error', { msg : 'redis_generalredisredis', err : 14 }); logger.debug(redis_key + ''); } }); } /** * redis * redis_keyself * @param options * @param reqData */ ProxyAgent.prototype.getRedis = function ( options, reqData) { var _self=this; var redis_key=this.redis.redis_key || ""; redis_pool.acquire(function(err, client) { if (!err) { client.get(redis_key, function(err, date) { redis_pool.release(client) if (!err && date != null) { var resultBuffer = new Buffer(date); _self.response.statusCode = 200; _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); _self.response.end(); logger.debug(redis_key + ':' + date); } else { _self.httpProxy(options, reqData); } }); } else { _self.httpProxy(options, reqData); } }); } /** * gzip * response * @param resultBuffer */ ProxyAgent.prototype.gzipOutPut = function (resultBuffer){ var _self=this; zlib.gzip(resultBuffer, function(code, buffer){ if (code != null) { logger.debug(',:'+resultBuffer.length+',:'+buffer.length); _self.response.setHeader('Content-Encoding', 'gzip'); } else { buffer = new Buffer( '{"msg":["JSON"]}'); _self.response.statusCode=500; } _self.response.setHeader("Content-Length", buffer.length); _self.response.write(buffer); _self.response.end(); }); } /** * * @param buffer type buffer/string * @param status http * @param tongji object */ ProxyAgent.prototype.onDone =function(buffer,status){ var tongji=arguments[2] ||""; var _self=this; var resultStr = typeof(buffer)=="object"?buffer.toString():buffer; if(this.reqConf.isjson==1){ var resultObj = common.isJson( resultStr, _self.reqConf.logName); // json if (resultObj) { // json resultStr = JSON.stringify(resultObj); _self.response.statusCode = status; } else { resultStr = '{"msg":["gisJSON"]}'; _self.response.statusCode = 500; } } else{ _self.response.statusCode = status; } var resultBuffer = new Buffer(resultStr); if(tongji!=""){ tongji.ends = Date.now(); tongji.length = resultBuffer.length; } if(resultBuffer.length > 500 ){ _self.gzipOutPut(resultBuffer); }else{ _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); _self.response.end(); } if(tongji!=""){ tongji.last= Date.now(); tongji=common.extends(tongji,_self.preAnalysisFields); logger.debug(':' + (tongji.last - tongji.start)+'ms statusCode='+status); writeLogs.logs(poiDetailServer,'poiDetailServer',obj); } }); ProxyAgent.prototype.onDones =function(buffer,status){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); ProxyAgent.prototype.dealDones =function(){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); //ProxyAgent event //utils.inherit(ProxyAgent,event); exports.ProxyAgent=ProxyAgent;
layout: post title: "Hello World" image: feature: nomadsland.jpg date: 2016-09-19 20:24:11 +0200 categories: personal, coding I enjoy tinkering - building little electronic gadgets and apps - especially if it has something to do with [cryptocurrencies]. Currently my day-job is building Bitcoin infrastructure. The purpose of this weblog is to record the progress on various projects outside my normal scope of work. Working with software, I seem to hit a lot of **"Hmmm, I wonder how this works?"** moments. Hopefully these pages provide some useful information to somebody working on and wondering about the same things. ## Begin I'm a fan of the maxim "Done is better than perfect" so my current goal is to get this blog up and running as quickly as possible. Instead of wondering about which software or host to use, I decided to power it with [Jekyll] and host it on [Github pages]. I already have a code/text editor I like using and git is already part of my daily workflow so it seemed like a natural fit. I picked a theme I liked but just as I got something that looked vaguely OK, I ran into the first **"Hmmm, I wonder"** moment. It turns out Jekyll/Github pages deployments are not intuitive. [Jekyll's Basic Usage Guide] does a pretty good job of explaining how to get up and running locally, but trying to find GH-Pages deployment instructions (and failing miserably) made me realise things don't work as I'd expect. ## Jekyll & Github Jekyll uses plugins and templates to help authors perform dynamic blog-related things like themeing, categorising and indexing posts, generating "about" pages and more. `jekyll build` produces a static "render" of the blog at the time it is called so that you can just upload the HTML/JS/CSS contents of the generated `_site` directory to a server that serves static content. You could host it on dropbox if you wanted to, there's no server-side scripts like PHP or Rails to generate content from data stored in a database. `_site` gets destroyed and re-created every time you call `jekyll build` and it is listed in `.gitignore` so it's not part of the repo, so how in the world do you tell Github to serve the contents of `_site`? Am I supposed to create a manual deploy script that adds `_site` to a repo and push that? ## Hmmm, I wonder... So which is it? Turns out you simply push your jekyll source repo to `master`. You don't even need to call `jekyll build`. Your site just magically appears on Github. That leaves only two possibilities: 1. Either Github calls `jekyll build` and serves the `_site` directory after each push, or 2. Github is running `jekyll serve` to generate content every request. Turns out it's the latter. Github actually runs Jekyll, and supports [some Jekyll plugins]. ## Done So, one "git push" later and these pages should be live! *"Done is better than perfect"* [BitX]: https: [cryptocurrencies]: https://en.wikipedia.org/wiki/Cryptocurrency [jekyll]: https://jekyllrb.com [Jekyll's Basic Usage Guide]: https://jekyllrb.com/docs/usage/ [Github pages]: https://pages.github.com/ [some Jekyll plugins]: https://help.github.com/articles/<API key>/
<?php namespace RobotsTxtParser; class CommentsTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider generateDataForTest */ public function testRemoveComments($robotsTxtContent) { $parser = new RobotsTxtParser($robotsTxtContent); $rules = $parser->getRules('*'); $this->assertEmpty($rules, 'expected remove comments'); } /** * @dataProvider <API key> */ public function <API key>($robotsTxtContent, $<API key>) { $parser = new RobotsTxtParser($robotsTxtContent); $rules = $parser->getRules('*'); $this->assertNotEmpty($rules, 'expected data'); $this->assertArrayHasKey('disallow', $rules); $this->assertNotEmpty($rules['disallow'], 'disallow expected'); $this->assertEquals($<API key>, $rules['disallow'][0]); } /** * Generate test case data * @return array */ public function generateDataForTest() { return array( array( " User-agent: * #Disallow: /tech " ), array( " User-agent: * Disallow: #/tech " ), array( " User-agent: * Disal # low: /tech " ), array( " User-agent: * Disallow#: /tech # ds " ), ); } /** * Generate test case data * @return array */ public function <API key>() { return array( array( "User-agent: * Disallow: /tech #comment", 'disallowValue' => '/tech', ), ); } }
package org.nfpj.utils.arrays; import java.util.Iterator; import java.util.<API key>; import java.util.function.Predicate; import org.nfpj.utils.predicates.TruePredicate; /** * * @author njacinto * @param <T> the type of object being returned by this iterator */ public class ArrayFilterIterator<T> implements Iterator<T> { protected static final int END_OF_ITERATION = -2; private int nextIndex; protected final T[] array; protected final Predicate<T> predicate; // <editor-fold defaultstate="expanded" desc="Constructors"> /** * Creates an instance of this class * * @param array the array from where this instance will extract the elements * @param predicate the filter to be applied to the elements */ public ArrayFilterIterator(T[] array, Predicate<T> predicate) { this(array, predicate, -1); } /** * * @param array * @param predicate * @param prevIndex */ protected ArrayFilterIterator(T[] array, Predicate<T> predicate, int prevIndex) { this.array = array!=null ? array : ArrayUtil.empty(); this.predicate = predicate!=null ? predicate : TruePredicate.getInstance(); this.nextIndex = getNextIndex(prevIndex); } // </editor-fold> // <editor-fold defaultstate="expanded" desc="Public methods"> /** * {@inheritDoc} */ @Override public boolean hasNext() { return nextIndex != END_OF_ITERATION; } /** * {@inheritDoc} */ @Override public T next() { if(nextIndex==END_OF_ITERATION){ throw new <API key>("The underline collection has no elements."); } int index = nextIndex; nextIndex = getNextIndex(nextIndex); return array[index]; } /** * {@inheritDoc} */ @Override public void remove() { throw new <API key>("The iterator doesn't allow changes."); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Protected methods"> /** * Searches for the next element that matches the filtering conditions and * returns it. * * @param currIndex * @return the next element that matches the filtering conditions or null * if no more elements are available */ protected int getNextIndex(int currIndex){ if(currIndex!=END_OF_ITERATION){ for(int i=currIndex+1; i<array.length; i++){ if(predicate.test(array[i])){ return i; } } } return END_OF_ITERATION; } // </editor-fold> }
layout: post title: slacker slack bot comments: true tags: - python - slack - - slacker &nbsp;&nbsp;&nbsp; `notification` . `slack` . . . <img src="/images/commit-bell.jpeg" alt=" " style="width: 480px; margin-left: auto; margin-right: auto; "/> &nbsp;&nbsp;&nbsp; . [Slack Apps](https://studytcp.slack.com/apps) `Build` . . `Something just for my team` . ![slackbot ]({{ site.url }}/images/slackbot_0.png) &nbsp;&nbsp;&nbsp; `Bots` . ![slackbot ]({{ site.url }}/images/slackbot_1.png) &nbsp;&nbsp;&nbsp; `token` () . &nbsp;&nbsp;&nbsp; pip . [github3.py](https: <pre>$ pip install slacker $ pip install github3.py $ pip install datetime $ pip install pytz</pre> &nbsp;&nbsp;&nbsp; . python from slacker import Slacker import github3 import datetime import pytz local_tz = pytz.timezone('Asia/Seoul') token = 'xoxb slack = Slacker(token) channels = ['#1', '#2'] def post_to_channel(message): slack.chat.post_message(channels[0], message, as_user=True) def <API key>(owner, repo): repo = github3.repository(owner, repo) return repo.pushed_at.astimezone(local_tz) def get_delta_time(last_commit): now = datetime.datetime.now(local_tz) delta = now - last_commit return delta.days def main(): members = ( # (git , repo , ), ) reports = [] for owner, repo, name in members: last_commit = <API key>(owner, repo) delta_time = get_delta_time(last_commit) if(delta_time == 0): reports.append('*%s* !' % (name)) else: reports.append('*%s* *%s* !' % (name, delta_time)) post_to_channel('\n ! \n' + '\n'.join(reports)) if __name__ == '__main__': main() * **X-RateLimit-Limit ** &nbsp;&nbsp;&nbsp; . . <pre>github3.models.GitHubError: 403 API rate limit exceeded for 106.246.181.100. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)</pre> &nbsp;&nbsp;&nbsp; IP . . `X-RateLimit-Limit` 60 5000 . (?) . <pre>[...] Status: 403 Forbidden X-RateLimit-Limit: 60 <API key>: 0 X-RateLimit-Reset: 1475913003 [...]</pre> * ** .** &nbsp;&nbsp;&nbsp; 2-3? . .. AWS . * [https: * [https: * [https:
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosHeart extends React.Component { render() { if(this.props.bare) { return <g> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </g>; } return <IconBase> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </IconBase>; } };IosHeart.defaultProps = {bare: false}
<?php require('includes/application_top.php'); require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_SPECIALS); $breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_SPECIALS)); require(DIR_WS_INCLUDES . 'template_top.php'); ?> <h1><?php echo HEADING_TITLE; ?></h1> <div class="contentContainer"> <div class="contentText"> <?php // BOF Enable & Disable Categories $specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.<API key>, p.products_image, s.<API key> from " . TABLE_PRODUCTS . " p, " . <API key> . " pd, " . TABLE_SPECIALS . " s, " . TABLE_CATEGORIES . " c, " . <API key> . " p2c where c.categories_status='1' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and p.products_status = '1' and p.products_id = s.products_id and pd.products_id = s.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; // EOF Enable & Disable Categories //$specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.<API key>, p.products_image, s.<API key> from " . TABLE_PRODUCTS . " p, " . <API key> . " pd, " . TABLE_SPECIALS . " s where p.products_status = '1' and s.products_id = p.products_id and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC"; $specials_split = new splitPageResults($specials_query_raw, <API key>); if (($specials_split->number_of_rows > 0) && ((<API key> == '1') || (<API key> == '3'))) { ?> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(<API key>, <API key>(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(<API key>); ?></span> </div> <br /> <?php } ?> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <?php $row = 0; $specials_query = tep_db_query($specials_split->sql_query); while ($specials = tep_db_fetch_array($specials_query)) { $row++; echo '<td align="center" width="33%"><a href="' . tep_href_link(<API key>, 'products_id=' . $specials['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $specials['products_image'], $specials['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a><br /><a href="' . tep_href_link(<API key>, 'products_id=' . $specials['products_id']) . '">' . $specials['products_name'] . '</a><br /><del>' . $currencies->display_price($specials['products_price'], tep_get_tax_rate($specials['<API key>'])) . '</del><br /><span class="productSpecialPrice">' . $currencies->display_price($specials['<API key>'], tep_get_tax_rate($specials['<API key>'])) . '</span></td>' . "\n"; if ((($row / 3) == floor($row / 3))) { ?> </tr> <tr> <?php } } ?> </tr> </table> <?php if (($specials_split->number_of_rows > 0) && ((<API key> == '2') || (<API key> == '3'))) { ?> <br /> <div> <span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(<API key>, <API key>(array('page', 'info', 'x', 'y'))); ?></span> <span><?php echo $specials_split->display_count(<API key>); ?></span> </div> <?php } ?> </div> </div> <?php require(DIR_WS_INCLUDES . 'template_bottom.php'); require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
{% extends "admin/base.html" %} {% load i18n %} {% block title %}{{ title }} | {% trans 'lab purchase management' %}{% endblock %} {% block branding %} <h1 id="site-name">{% trans 'LabHamster' %}</h1> {% endblock %} {% block nav-global %}{% endblock %}
package org.mockitousage.verification; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.atMostOnce; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.<API key>; import java.util.List; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.<API key>; import org.mockito.exceptions.verification.<API key>; import org.mockitoutil.TestBase; public class <API key> extends TestBase { @Mock private List<String> mock; @Test public void <API key>() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(2)).clear(); verify(mock, atMost(3)).clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (<API key> e) { } } @Test public void <API key>() throws Exception { mock.add("one"); verify(mock, atMost(5)).add(anyString()); try { verify(mock, atMost(0)).add(anyString()); fail(); } catch (<API key> e) { } } @Test public void <API key>() throws Exception { try { verify(mock, atMost(-1)).clear(); fail(); } catch (MockitoException e) { assertEquals("Negative value is not allowed here", e.getMessage()); } } @Test public void <API key>() throws Exception { mock.clear(); mock.clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (<API key> e) { assertEquals("\nWanted at most 1 time but was 2", e.getMessage()); } } @Test public void <API key>() throws Exception { mock.clear(); InOrder inOrder = inOrder(mock); try { inOrder.verify(mock, atMostOnce()).clear(); fail(); } catch (MockitoException e) { assertEquals("AtMost is not implemented to work with InOrder", e.getMessage()); } } @Test public void <API key>() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(3)).clear(); <API key>(mock); } @Test public void <API key>() throws Exception { mock.clear(); mock.clear(); <API key>(); verify(mock, atMost(3)).clear(); try { <API key>(mock); fail(); } catch (<API key> e) { assertThat(e).<API key>("<API key>("); } } private void <API key>() { mock.add(""); } }
<?php declare(strict_types=1); namespace Atk4\Ui\Demos; use Atk4\Ui\Crud; use Atk4\Ui\UserAction\ExecutorFactory; // Test for hasOne Lookup as dropdown control. /** @var \Atk4\Ui\App $app */ require_once __DIR__ . '/../init-app.php'; $model = new Product($app->db); $model->addCondition($model->fieldName()->name, '=', 'Mustard'); // use default. $app->getExecutorFactory()->useTriggerDefault(ExecutorFactory::TABLE_BUTTON); $edit = $model->getUserAction('edit'); $edit->callback = function (Product $model) { return $model->product_category_id->getTitle() . ' - ' . $model-><API key>->getTitle(); }; $crud = Crud::addTo($app); $crud->setModel($model, [$model->fieldName()->name]);
#ifndef HardwareSerial_h #define HardwareSerial_h #include <inttypes.h> #include "Print.h" struct ring_buffer; #if defined(__AVR_ATmega103__) class HardwareSerial : public Print { private: ring_buffer *_rx_buffer; volatile uint8_t *_ubrr; volatile uint8_t *_ucr; volatile uint8_t *_usr; volatile uint8_t *_udr; uint8_t _rxen; uint8_t _txen; uint8_t _rxcie; uint8_t _udre; public: HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrr, volatile uint8_t *ucr, volatile uint8_t *usr, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre); void begin(long); void end(); uint8_t available(void); int read(void); void flush(void); virtual void write(uint8_t); using Print::write; // pull in write(str) and write(buf, size) from Print }; #else class HardwareSerial : public Print { private: ring_buffer *_rx_buffer; volatile uint8_t *_ubrrh; volatile uint8_t *_ubrrl; volatile uint8_t *_ucsra; volatile uint8_t *_ucsrb; volatile uint8_t *_udr; uint8_t _rxen; uint8_t _txen; uint8_t _rxcie; uint8_t _udre; uint8_t _u2x; public: HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x); void begin(long); void end(); uint8_t available(void); int read(void); void flush(void); virtual void write(uint8_t); using Print::write; // pull in write(str) and write(buf, size) from Print }; #endif extern HardwareSerial Serial; #if defined(__AVR_ATmega1280__) extern HardwareSerial Serial1; extern HardwareSerial Serial2; extern HardwareSerial Serial3; #endif #endif
import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as courseActions from '../../actions/courseActions'; import CourseForm from './CourseForm'; import {<API key>} from '../../selectors/selectors'; import toastr from 'toastr'; export class ManageCoursePage extends React.Component { constructor(props, context) { super(props, context); this.state = { course: Object.assign({}, props.course), errors: {}, saving: false }; this.updateCourseState = this.updateCourseState.bind(this); this.saveCourse = this.saveCourse.bind(this); } <API key>(nextProps) { if (this.props.course.id != nextProps.course.id) { // Necessary to populate form when existing course is loaded directly. this.setState({course: Object.assign({}, nextProps.course)}); } } updateCourseState(event) { // handler for each form field const field = event.target.name; let course = this.state.course; course[field] = event.target.value; return this.setState({course: course}); } courseFormValid() { let formIsValid = true; let errors = {}; if (this.state.course.title.length < 5) { errors.title = 'Title must be at least 5 characters.'; formIsValid = false; } this.setState({errors: errors}); return formIsValid; } saveCourse(event) { event.preventDefault(); if (!this.courseFormValid()) { return; } this.setState({saving: true}); this.props.actions.saveCourse(this.state.course) .then(() => this.redirect()) .catch(error => { toastr.error(error); this.setState({saving: false}); }); } redirect() { // redirect to courses route this.setState({saving: false}); toastr.success('Course saved!'); this.context.router.push('/courses'); } render() { return ( <CourseForm allAuthors={this.props.authors} onChange={this.updateCourseState} onSave={this.saveCourse} errors={this.state.errors} course={this.state.course} saving={this.state.saving}/> ); } } ManageCoursePage.propTypes = { course: PropTypes.object.isRequired, authors: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; //Pull in the React Router context so router is available on this.context.router. ManageCoursePage.contextTypes = { router: PropTypes.object }; function getCourseById(courses, id) { const course = courses.filter(course => course.id == id); if (course.length) return course[0]; //since filter returns an array, have to grab the first. return null; } function mapStateToProps(state, ownProps) { let course = { id: "", title: "", watchHref: "", authorId: "", length: "23", category: "" }; const courseId = ownProps.params.id; // from the path `/course/:id` if (courseId && state.courses.length > 0) { course = getCourseById(state.courses, courseId); } return { course: course, authors: <API key>(state.authors) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(courseActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
.sessionForm{ padding: 10px; } .carapaceForm{ padding: 10px; border: 3px solid #000000; min-width: 960px; margin-bottom: 10px; } label{ margin: 5px; } input{ margin: 5px; } button{ margin: 5px; } .section{ border: 1px solid #000000; margin-bottom: 10px; } .carapaceSection{ padding: 10px; background-color #eeeeee; } .itemForm{ padding: 10px; border: 3px solid #000000; } .selectedItem{ padding: 10px; border: 3px solid #000000; } .itemSection{ padding: 10px; background-color #eeeeee; } .prospit{ background-color:black; } .derse{ background-color: white; }
<API key> = Class.create(<API key>, { attributeHandler: null, process: function() { if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (!this.load()) { return ''; } this.<API key>(); if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) { return ''; } if (this.specificHandler.isSpecificRendered(this.indexedXPath)) { if (this.isValueForceSet()) { this.<API key>(this.getForceSetValue()); this.hideButton($(this.indexedXPath + '_remove_button')); var myEvent = new CustomEvent('<API key>'); $(this.<API key>()).dispatchEvent(myEvent); } return ''; } this.renderSelf(); if (this.isValueForceSet()) { this.<API key>(this.getForceSetValue()); } this.observeToolTips(this.indexedXPath); this.checkSelection(); this.<API key>(); }, load: function($super) { this.attributeHandler = AttributeHandlerObj; return $super(); }, // <API key>: function() { if (this.specific.parent_specific_id == null) { return ''; } if (!this.dictionaryHelper.<API key>(this.parentSpecific)) { return ''; } var parentBlockRenderer = new <API key>(); parentBlockRenderer.setSpecificsHandler(this.specificHandler); parentBlockRenderer.setIndexedXpath(this.<API key>()); parentBlockRenderer.process(); }, renderSelf: function() { this.renderLabel(); this.renderChooseMode(); this.renderValueInputs(); // affects the appearance of the actions buttons this.specificHandler.<API key>(this.indexedXPath); this.renderButtons(); $(this.indexedXPath).observe('<API key>', this.<API key>.bind(this)); // like grid visibility or view of 'Add Specific' container this.<API key>(); }, <API key>: function() { var self = this; if (!this.specific.params.hasOwnProperty('attributes')) { return ''; } this.specific.params.attributes.each(function(attribute, index) { var renderer = new <API key>(); renderer.setSpecificsHandler(self.specificHandler); renderer.setIndexedXpath(self.indexedXPath); renderer.attribute = attribute; renderer.attributeIndex = index; renderer.process(); }); }, // renderLabel: function() { var td = new Element('td'); var title = this.specific.title; if (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) { title += ' <span class="required">*</span>'; } else if (this.dictionaryHelper.isSpecificDesired(this.specific)) { title += ' <span style="color: grey; font-style: italic;">(' + M2ePro.translator.translate('Desired') + ')</span>'; } td.appendChild((new Element('span').insert(title))); var note = this.getDefinitionNote(this.specific.data_definition); if (note) { var toolTip = this.getToolTipBlock(this.indexedXPath + '_definition_note', note); toolTip.show(); td.appendChild(toolTip); } var notice = this.<API key>(); if (notice) td.appendChild(notice); notice = this.<API key>(); if (notice) td.appendChild(notice); this.getRowContainer().appendChild(td); }, renderChooseMode: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_mode', 'indexedxpath': this.indexedXPath, 'class' : '<API key>', 'style' : 'width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none'})); if (this.specific.recommended_values.length > 0) { select.appendChild(new Element('option', {'value': this.<API key>})) .insert(M2ePro.translator.translate('Recommended Values')); } select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_VALUE})) .insert(M2ePro.translator.translate('Custom Value')); select.appendChild(new Element('option', {'value': this.<API key>})) .insert(M2ePro.translator.translate('Custom Attribute')); select.observe('change', this.onChangeChooseMode.bind(this)); this.getRowContainer().appendChild(new Element('td')).appendChild(select); }, onChangeChooseMode: function(event) { var customValue = $(this.indexedXPath + '_' + this.MODE_CUSTOM_VALUE), customValueNote = $(this.indexedXPath + '_custom_value_note'), <API key> = $('<API key>-' + customValue.id); var customAttribute = $(this.indexedXPath + '_' + this.<API key>), customAttributeNote = $(this.indexedXPath + '<API key>'), <API key> = $('<API key>-' + customAttribute.id); var recommendedValue = $(this.indexedXPath + '_' + this.<API key>); customValue && customValue.hide(); customValueNote && customValueNote.hide(); <API key> && <API key>.hide(); customAttribute && customAttribute.hide(); customAttributeNote && customAttributeNote.hide(); <API key> && <API key>.hide(); recommendedValue && recommendedValue.hide(); if (event.target.value == this.MODE_CUSTOM_VALUE) { customValue && customValue.show(); customValueNote && customValueNote.show(); <API key> && <API key>.show(); } if (event.target.value == this.<API key>) { customAttribute && customAttribute.show(); customAttributeNote && customAttributeNote.show(); <API key> && <API key>.show(); } if (event.target.value == this.<API key>) { recommendedValue && recommendedValue.show(); } }, renderValueInputs: function() { var td = this.getRowContainer().appendChild(new Element('td')); if (this.dictionaryHelper.isSpecificTypeText(this.specific)) { var note = this.<API key>(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_value_note', note)); td.appendChild(this.getTextTypeInput()); } if (this.dictionaryHelper.<API key>(this.specific)) { td.appendChild(this.getSelectTypeInput()); } note = this.<API key>(); if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '<API key>', note)); td.appendChild(this.<API key>()); td.appendChild(this.<API key>()); }, getTextTypeInput: function() { if (this.dictionaryHelper.<API key>(this.specific)) { var input = new Element('textarea', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : '<API key> <API key>', 'style' : 'width: 91.4%; display: none;' }); } else { var input = new Element('input', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'specific_type' : this.specific.params.type, 'type' : 'text', 'class' : 'input-text <API key> <API key>', 'style' : 'display: none; width: 91.4%;' }); this.specific.params.type == 'date_time' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d %H:%M:%S", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); this.specific.params.type == 'date' && Calendar.setup({ 'inputField': input, 'ifFormat': "%Y-%m-%d", 'showsTime': true, 'button': input, 'align': 'Bl', 'singleClick': true }); } input.observe('change', this.onChangeValue.bind(this)); return input; }, getSelectTypeInput: function() { var self = this; var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.MODE_CUSTOM_VALUE, 'class' : '<API key>', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none;'})); var specificOptions = this.specific.values; specificOptions.each(function(option) { var label = option == 'true' ? 'Yes' : (option == 'false' ? 'No' : option), tempOption = new Element('option', {'value': option}); select.appendChild(tempOption).insert(label); }); select.observe('change', this.onChangeValue.bind(this)); return select; }, <API key>: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.<API key>, 'indexedxpath' : this.indexedXPath, 'specific_id' : this.specific.specific_id, 'specific_type' : this.specific.params.type, 'mode' : this.<API key>, 'class' : 'attributes <API key>', 'style' : 'display: none; width: 93.2%;', '<API key>' : '0' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.attributeHandler.availableAttributes.each(function(el) { select.appendChild(new Element('option', {'value': el.code})).insert(el.label); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); var handlerObj = new AttributeCreator(select.id); handlerObj.setSelectObj(select); handlerObj.injectAddOption(); return select; }, <API key>: function() { var select = new Element('select', { 'id' : this.indexedXPath +'_'+ this.<API key>, 'indexedxpath': this.indexedXPath, 'specific_id' : this.specific.specific_id, 'mode' : this.<API key>, 'class' : '<API key>', 'style' : 'display: none; width: 93.2%;' }); select.appendChild(new Element('option', {'style': 'display: none', 'value': ''})); this.specific.recommended_values.each(function(value) { select.appendChild(new Element('option', {'value': value})).insert(value); }); select.value = ''; select.observe('change', this.onChangeValue.bind(this)); return select; }, onChangeValue: function(event) { var selectedObj = {}; selectedObj['mode'] = event.target.getAttribute('mode'); selectedObj['type'] = event.target.getAttribute('specific_type'); selectedObj['is_required'] = (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) ? 1 : 0; selectedObj[selectedObj.mode] = event.target.value; this.specificHandler.<API key>(this.indexedXPath, selectedObj); }, renderButtons: function() { var td = this.getRowContainer().appendChild(new Element('td')); var cloneButton = this.getCloneButton(); if(cloneButton !== null) td.appendChild(cloneButton); var removeButton = this.getRemoveButton(); if(removeButton !== null) td.appendChild(removeButton); }, <API key>: function() { var myEvent, parentXpath; myEvent = new CustomEvent('<API key>'); parentXpath = this.<API key>(); $(parentXpath + '_grid').dispatchEvent(myEvent); $(parentXpath + '_add_row').dispatchEvent(myEvent); // my duplicate is already rendered this.touchMyNeighbors(); if (this.isValueForceSet()) { this.hideButton($(this.indexedXPath + '_remove_button')); myEvent = new CustomEvent('<API key>'); $(this.<API key>()).dispatchEvent(myEvent); } }, // checkSelection: function() { if (this.specific.values.length == 1) { this.<API key>(this.specific.values[0]); return ''; } if (!this.specificHandler.isMarkedAsSelected(this.indexedXPath) && !this.specificHandler.isInFormData(this.indexedXPath)) { return ''; } var selectionInfo = this.specificHandler.getSelectionInfo(this.indexedXPath); var id = this.indexedXPath + '_mode'; $(id).value = selectionInfo.mode; this.simulateAction($(id), 'change'); if (selectionInfo.mode == this.MODE_CUSTOM_VALUE) { id = this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE; $(id).value = selectionInfo['custom_value']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.<API key>) { id = this.indexedXPath +'_'+ this.<API key>; $(id).value = selectionInfo['custom_attribute']; this.simulateAction($(id), 'change'); } if (selectionInfo.mode == this.<API key>) { id = this.indexedXPath +'_'+ this.<API key>; $(id).value = selectionInfo['recommended_value']; this.simulateAction($(id), 'change'); } }, <API key>: function(value) { if (!value) { return; } var modeSelect = $(this.indexedXPath + '_mode'); modeSelect.value = this.MODE_CUSTOM_VALUE; this.simulateAction(modeSelect, 'change'); modeSelect.setAttribute('disabled','disabled'); var valueObj = $(this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE); valueObj.value = value; this.simulateAction(valueObj, 'change'); valueObj.setAttribute('disabled', 'disabled'); }, // getToolTipBlock: function(id, messageHtml) { var container = new Element('div', { 'id' : id, 'style': 'float: right; display: none;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/tool-tip-icon.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px;' })); htmlCont.appendChild(new Element('img', { 'src': M2ePro.url.get('m2epro_skin_url') + '/images/help.png' })); htmlCont.appendChild(new Element('span')).insert(messageHtml); return container; }, <API key>: function() { if (this.specific.data_definition.definition) { return null; } if (this.specific.params.type == 'int') return this.getIntTypeNote(this.specific.params); if (this.specific.params.type == 'float') return this.getFloatTypeNote(this.specific.params); if (this.specific.params.type == 'string') return this.getStringTypeNote(this.specific.params); if (this.specific.params.type == 'date_time') return this.getDatTimeTypeNote(this.specific.params); return this.getAnyTypeNote(this.specific.params); }, getIntTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'total_digits': function(restriction) { notes[3] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getFloatTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: Numeric floating point.') + ' '; }, 'min_value': function(restriction) { notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. '; }, 'max_value': function(restriction) { notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. '; }, 'decimal_places': function(restriction) { notes[3] = M2ePro.translator.translate('Decimal places (not more):') + ' ' + restriction.value + '. '; }, 'total_digits': function(restriction) { notes[4] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. '; } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getStringTypeNote: function(params) { var notes = []; var handler = { 'type': function() { notes[0] = M2ePro.translator.translate('Type: String.') + ' '; }, 'min_length': function(restriction) { notes[1] = restriction != 1 ? M2ePro.translator.translate('Min length:') + ' ' + restriction : ''; }, 'max_length': function(restriction) { notes[2] = M2ePro.translator.translate('Max length:') + ' ' + restriction; }, 'pattern': function(restriction) { if (restriction == '[a-zA-Z][a-zA-Z]|unknown') { notes[3] = M2ePro.translator.translate('Two uppercase letters or "unknown".'); } } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getDatTimeTypeNote: function(params) { var notes = []; var handler = { 'type': function(restriction) { notes.push(M2ePro.translator.translate('Type: Date time. Format: YYYY-MM-DD hh:mm:ss')); } }; for (var paramName in params) { params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]); } return notes.join(''); }, getAnyTypeNote: function(params) { return M2ePro.translator.translate('Can take any value.'); }, <API key>: function() { if (this.specific.values.length <= 0 && this.specific.recommended_values.length <= 0) { return null; } var span = new Element('span'); var title = this.specific.values.length > 0 ? M2ePro.translator.translate('Allowed Values') : M2ePro.translator.translate('Recommended Values'); span.appendChild(new Element('span')).insert('<b>' + title + ': </b>'); var ul = span.appendChild(new Element('ul')); var noteValues = this.specific.values.length > 0 ? this.specific.values : this.specific.recommended_values; noteValues.each(function(value) { ul.appendChild(new Element('li')).insert(value); }); return span.outerHTML; }, getDefinitionNote: function(definitionPart) { if (!definitionPart.definition) { return; } var div = new Element('div'); div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Definition:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.definition); if (definitionPart.tips && definitionPart.tips.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Tips:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.tips); } if (definitionPart.example && definitionPart.example.match(/[a-z0-9]/i)) { div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'})) .insert('<b>' + M2ePro.translator.translate('Examples:') + '</b>'); div.appendChild(new Element('div')) .insert(definitionPart.example); } return div.outerHTML; }, <API key>: function() { if (!this.specificHandler.<API key>(this.specific)) { return null; } var variationThemesList = this.specificHandler.themeAttributes[this.specific.xml_tag]; var message = '<b>' + M2ePro.translator.translate('Value of this Specific can be automatically overwritten by M2E Pro.') + '</b>'; message += '<br/><br/>' + variationThemesList.join(', '); return this.constructNotice(message); }, <API key>: function() { if (this.specific.xml_tag != 'Parentage') { return null; } return this.constructNotice(M2ePro.translator.translate('Amazon Parentage Specific will be overridden notice.')); }, constructNotice: function(message) { var container = new Element('div', { 'style': 'float: right; margin-right: 3px; margin-top: 1px;' }); container.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/warning.png', 'class' : 'tool-tip-image' })); var htmlCont = container.appendChild(new Element('span', { 'class' : 'tool-tip-message tip-left', 'style' : 'display: none; max-width: 500px; border-color: #ffd967; background-color: #fffbf0;' })); htmlCont.appendChild(new Element('img', { 'src' : M2ePro.url.get('m2epro_skin_url') + '/images/i_notice.gif', 'style' : 'margin-top: -21px;' })); htmlCont.appendChild(new Element('span')).insert(message); return container; }, // observeToolTips: function(indexedXpath) { $$('tr[id="' + indexedXpath + '"] .tool-tip-image').each(function(element) { element.observe('mouseover', MagentoFieldTipObj.showToolTip); element.observe('mouseout', MagentoFieldTipObj.<API key>); }); $$('tr[id="' + indexedXpath + '"] .tool-tip-message').each(function(element) { element.observe('mouseout', MagentoFieldTipObj.onToolTipMouseLeave); element.observe('mouseover', MagentoFieldTipObj.onToolTipMouseEnter); }); }, // removeAction: function($super, event) { // for attributes removing var myEvent = new CustomEvent('<API key>'); $(this.indexedXPath).dispatchEvent(myEvent); var deleteResult = $super(event); this.<API key>(); return deleteResult; }, cloneAction: function($super, event) { var newIndexedXpath = $super(event); this.observeToolTips(newIndexedXpath); var myEvent = new CustomEvent('<API key>', { 'new_indexed_xpath': newIndexedXpath }); $(this.indexedXPath).dispatchEvent(myEvent); return newIndexedXpath; }, getRowContainer: function() { if ($(this.indexedXPath)) { return $(this.indexedXPath); } var grid = $$('table[id="'+ this.<API key>() +'_grid"] table.border tbody').first(); return grid.appendChild(new Element('tr', {id: this.indexedXPath})); } });
Rails.application.config.middleware.use OmniAuth::Builder do provider :provider, ENV["KEY"], ENV["SECRET"] end
package controller.server; import controller.LibraryService; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.rmi.RemoteException; public class RMIServer { public static void main(String[] args) throws RemoteException, NamingException { LibraryService service = new DBController(); Context namingContext = new InitialContext(); namingContext.rebind("rmi:books", service); System.out.println("RMI-server is working..."); } }
define([ 'angular' ], function (ng) { 'use strict'; return ng.module('backgroundModule', []); });
const pkg = state => state.pkg const app = state => state.app const device = state => state.app.device const sidebar = state => state.app.sidebar const effect = state => state.app.effect const menuitems = state => state.menu.items const componententry = state => { return state.menu.item.filter(c => c.meta && c.meta.label === 'Components')[0] } export { pkg, app, device, sidebar, effect, menuitems, componententry }
title: HOWTO: Install Ubuntu on Your Eee PC author: Rami Taibah permalink: <API key> tags: eee-pc, ubuntu, howto I have [posted]({filename}/blog/<API key>.markdown) earlier that the "easy mode" of the Eee PC is like living on the bottom bunker in a basement cell of the Alcatraz. Liberating it to the default Xandros "advanced mode" is just like going out to yard with sweaty inmates, which isn't saying much. I initially installed eeexubuntu on that little critter, but soon was disenchanted. XFCE is just not for me. Solution? Install everybody's favorite! Ubuntu! ## USB disk or CD drive? Installing a different distro on your Eee PC is done either by using a USB thumb drive or an external CD drive. I expect that the Eee PC is the first Linux experience to a lot of Eee PC users, so I would recommend getting an external CD drive, it's much less of a hassle. ## Downloading, burning, and preperation First of all you will need to get Ubuntu. At the time of writing this, Ubuntu 7.10 (Gutsy) is the latest so get it either through direct [download](http: Then you will need to burn it on a CD using your favorite image burner. (there are many guides for that, google it) You will also probably need to edit the boot sequence in your bios. So restart your Eee PC and press F2 to enter the bios menu and change the primary boot to "USB Optical Drive". Pop in the Ubuntu CD in your external drive and restart. Then press enter when you get the list of options (first option). A couple of minutes later you will be on your default Ubuntu desktop. Before clicking the "install" icon, you will need to disable the desktop effects. Since the installer doesn't fit into the small Eee PC screen, you will need to use the ALT+Right click option to move the installer window. So System --> Prefrences --> Appearence and then go to the last tab "Visual Effects" and then select none. ## Installation Now you are ready for installing, so click on the "Install" icon located on your desktop (pictures are eclipsed due to screen size): ![Eee PC Ubuntu Install]({filename}/images/<API key>.png) Select your language. ![Eee PC Ubuntu Install]({filename}/images/<API key>.png) Select your keyboard layout. ![Eee PC Ubuntu Install]({filename}/images/<API key>.png) Select manual partitioning. ![Eee PC Ubuntu Install]({filename}/images/<API key>.png) This is the tricky part, basically you will need to set a root partition for the system to be installed in. So we are going to partition /dev/sda1 and make it our root. Click on /dev/sda1 and then delete whatever partitions under it. Then click on new and in filesystem choose ext2 (we are not going to use ext3 because we want to limit writes due to the solid state disk nature of the Eee PC). Also set mount point to "/" (without the quotes). If you have an SDHC card click on it and edit the mount point to "/media/\*whatever\*". If you have nothing interesting in that card you might want to just delete whatever partitions and make a new partition, and choosing the filesystem as "fat32″. Since you never know when you might want to use it on Windows machine ;). ![Eee PC Ubuntu Install]({filename}/images/<API key>.png) Enter your details. Name, user name, password, and machine name. Click next. You will be prompted with a warning that all your data will be wiped out, click OK. Now sit back and relax, your system will be ready in 30 minutes or so. Thats it! Now just click restart system when prompted, you will then asked to eject CD. Now your golden :) A lot of functionality will be missing with this out of the box Ubuntu installation. For example your wireless won't function. Visit my [Perfect Eee PC Ubuntu Installation Guide]({filename}/blog/<API key>.markdown) for a complete guide on how to get things up and running.
using System; using System.Collections.Generic; using System.Linq; using BlackBox.Service; using EbInstanceModel; using IFC2X3; namespace BlackBox.Predefined { public partial class BbProduct : BbBase { [<API key>] public virtual IfcRelAggregates IfcRelAggregates { get; protected set; } public BbLocalPlacement3D <API key> { get; protected set; } public virtual IfcObject IfcObject { get; protected set; } public string Name { get { return IfcObject.Name; } protected set { IfcObject.Name = value; } } public string Description { get { return IfcObject.Description; } protected set { IfcObject.Description = value; } } public string ObjectType { get { return IfcObject.ObjectType; } protected set { IfcObject.ObjectType = value; } } [<API key>] public BbProduct HostObject { get; protected set; } protected BbProduct() : this(Guid.NewGuid()) { } protected BbProduct(Guid guid) : base(guid) { } public void AddToHostObject(BbProduct hostObject) { HostObject = hostObject; var a = <API key>.<API key>(hostObject.IfcObject.EIN).Values; var b = (from x in a.OfType<IfcRelAggregates>() where x.RelatingObject.EIN == hostObject.IfcObject.EIN select x).ToList(); switch (b.Count) { case 0: IfcRelAggregates = new IfcRelAggregates { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostObject.IfcObject.OwnerHistory, RelatingObject = hostObject.IfcObject, RelatedObjects = new List<IfcObjectDefinition>() { }, }; break; case 1: IfcRelAggregates = b[0]; break; default: throw new <API key>(); } var aa = GetType().GetProperty("IfcObject").GetValue(this, null) as IfcObject; IfcRelAggregates.RelatedObjects.Add(aa); } } }
""" symbols(name(s), assumptions...) Calls `sympy.symbols` to produce symbolic variables and symbolic functions. An alternate to the recommended `@syms`, (when applicable) In sympy `sympy.symbols` and `sympy.Symbol` both allow the construction of symbolic variables and functions. The `Julia` function `symbols` is an alias for `sympy.symbols`. * Variables are created through `x=symbols("x")`; * Assumptions on variables by `x=symbols("x", real=true)`; * Multiple symbols `x1,x2 = symbols("x[1:3]")` can be created. Unlike `@syms`, the number of variables can be specified with a variable through interpolation. * Symbolic functions can be created py passing `cls=sympy.Function`, `symbols("F", cls=sympy.Function, real=true)` """ function symbols(x::AbstractString; kwargs...) out = sympy.symbols(x; kwargs...) end symbols(x::Symbol; kwargs...) = symbols(string(x); kwargs...) symbols(xs::T...; kwargs...) where {T <: SymbolicObject} = xs macro vars(x...) q = Expr(:block) as = [] # running list of assumptions to be applied ss = [] # running list of symbols created for s in reverse(x) if isa(s, Expr) # either an assumption or a named variable if s.head == :(=) s.head = :kw push!(as, s) elseif s.head == :call && s.args[1] == :(=>) push!(ss, s.args[2]) push!(q.args, Expr(:(=), esc(s.args[2]), Expr(:call, :symbols, s.args[3], map(esc,as)...))) end elseif isa(s, Symbol) # raw symbol to be created push!(ss, s) push!(q.args, Expr(:(=), esc(s), Expr(:call, :symbols, Expr(:quote, s), map(esc,as)...))) else throw(AssertionError("@vars expected a list of symbols and assumptions")) end end push!(q.args, Expr(:tuple, map(esc,reverse(ss))...)) # return all of the symbols we created q end macro syms(xs...) # If the user separates declaration with commas, the top-level expression is a tuple if length(xs) == 1 && isa(xs[1], Expr) && xs[1].head == :tuple _gensyms(xs[1].args...) elseif length(xs) > 0 _gensyms(xs...) end end function _gensyms(xs...) asstokw(a) = Expr(:kw, esc(a), true) # Each declaration is parsed and generates a declaration using `symbols` symdefs = map(xs) do expr decl = parsedecl(expr) symname = sym(decl) symname, gendecl(decl) end syms, defs = collect(zip(symdefs...)) # The macro returns a tuple of Symbols that were declared Expr(:block, defs..., :(tuple($(map(esc,syms)...)))) end ## avoid PyObject conversion as possible Sym(x::T) where {T <: Number} = sympify(x) Sym(x::Rational{T}) where {T} = Sym(numerator(x))/Sym(denominator(x)) function Sym(x::Complex{Bool}) !x.re && x.im && return IM !x.re && !x.im && return zero(Sym) x.re && !x.im && return Sym(1) x.re && x.im && return Sym(1) + IM end Sym(x::Complex{T}) where {T} = Sym(real(x)) + Sym(imag(x)) * IM Sym(xs::Symbol...) = Tuple(Sym.((string(x) for x in xs))) Sym(x::AbstractString) = sympy.symbols(x) Sym(s::SymbolicObject) = s Sym(x::Irrational{T}) where {T} = convert(Sym, x) convert(::Type{Sym}, s::AbstractString) = Sym(s) sympify(s, args...; kwargs...) = pycall(sympy.sympify::PyCall.PyObject, Sym, s) #sympy.sympify(s, args...; kwargs...) SymMatrix(s::SymMatrix) = s SymMatrix(s::Sym) = sympy.ImmutableMatrix([s]) SymMatrix(A::Matrix) = sympy.ImmutableMatrix([A[i,:] for i in 1:size(A)[1]])
using UnityEngine; public class Crouch : MonoBehaviour { public float <API key> = 0.75f; private bool crouching; private float colliderCenterY, centerOffsetY; private ChipmunkBoxShape box; private Jump jump; private Sneak sneak; private WalkAbs move; private AnimateTiledConfig crouchAC; void Awake () { crouching = false; // take the collider and some useful values box = GetComponent<ChipmunkBoxShape>(); colliderCenterY = box.center.y; centerOffsetY = ((1f - <API key>)*0.5f) * box.size.y; jump = GetComponent<Jump>(); sneak = GetComponent<Sneak>(); move = GetComponent<WalkAbs>(); crouchAC = AnimateTiledConfig.getByName(gameObject, <API key>.Crouch, true); } // Update is called once per frame public void crouch () { // is it jumping? bool jumping = false; if (jump != null && jump.isJumping()) jumping = true; // is it moving? bool moving = false; if (move != null && move.isWalking()) moving = true; // if crouching then update accordingly if (sneak != null && crouching) { // while in the air we can't sneak if (jumping) { if (sneak.isSneaking()) { sneak.stopSneaking(); crouchAC.setupAndPlay(); } } // if not jumping and not moving and sneaking: stop sneaking and do crouch else if (!moving) { if (sneak.isSneaking()) { sneak.stopSneaking(); crouchAC.setupAndPlay(); } } // if not jumping and moving: sneak else sneak.sneak(); } // don't update if (crouching || jumping) return; crouching = true; // resize the collider Vector3 theSize = box.size; theSize.y *= <API key>; box.size = theSize; // transform the collider Vector3 theCenter = box.center; theCenter.y -= centerOffsetY; box.center = theCenter; // set the correct sprite animation crouchAC.setupAndPlay(); } public void noCrouch () { if (sneak != null) sneak.stopSneaking(); if (!crouching) return; move.stop(); // this force the reset of the sprite animation crouchAC.stop(); crouching = false; // transform the collider Vector3 theCenter = box.center; theCenter.y = colliderCenterY; box.center = theCenter; // resize the collider Vector3 theSize = box.size; theSize.y /= <API key>; box.size = theSize; } public bool isCrouching () { return crouching; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Plato - lib/cmds/nt.js</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif] <link href="../../assets/css/vendor/morris.css" rel="stylesheet"> <link href="../../assets/css/vendor/bootstrap.css" rel="stylesheet"> <link href="../../assets/css/vendor/font-awesome.css" rel="stylesheet"> <link href="../../assets/css/vendor/codemirror.css" rel="stylesheet"> <link href="../../assets/css/plato.css" rel="stylesheet"> <link href="../../assets/css/plato-file.css" rel="stylesheet"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="container"> <a class="navbar-brand" href="http://github.com/es-analysis/plato">Plato on Github</a> <ul class="nav navbar-nav"> <li> <a href="../../index.html">Report Home</a> </li> </ul> </div> </div> <div class="jumbotron"> <div class="container"> <h1>lib/cmds/nt.js</h1> </div> </div> <div class="container aggregate-stats"> <div class="row"> <div class="col-md-6"> <h2 class="header">Maintainability <a href="http://blogs.msdn.com/b/codeanalysis/archive/2007/11/20/<API key>.aspx"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="A value between 0 and 100 that represents the relative ease of maintaining the code. A high value means better maintainability." data-original-title="Maintainability Index" data-container="body"></i></a></h2> <p class="stat">64.69</p> </div> <div class="col-md-6"> <h2 class="header">Lines of code <i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Source Lines of Code / Logical Lines of Code" data-original-title="SLOC/LSLOC" data-container="body"></i></h2> <p class="stat">179</p> </div> </div> <div class="row historical"> <div class="col-md-6"> <p id="<API key>" class="chart"></p> </div> <div class="col-md-6"> <p id="<API key>" class="chart"></p> </div> </div> <div class="row"> <div class="col-md-6"> <h2 class="header">Difficulty <a href="http://en.wikipedia.org/wiki/<API key>"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="The difficulty measure is related to the difficulty of the program to write or understand." data-original-title="Difficulty" data-container="body"></i></a></h2> <p class="stat">21.07</p> </div> <div class="col-md-6"> <h2 class="header">Estimated Errors <a href="http://en.wikipedia.org/wiki/<API key>"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Halstead's delivered bugs is an estimate for the number of errors in the implementation." data-original-title="Delivered Bugs" data-container="body"></i></a></h2> <p class="stat">1.21</p> </div> </div> </div> <div class="container charts"> <div class="row"> <h2 class="header">Function weight</h2> </div> <div class="row"> <div class="col-md-6"> <h3 class="chart-header">By Complexity <a href="http://en.wikipedia.org/wiki/<API key>"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="This metric counts the number of distinct paths through a block of code. Lower values are better." data-original-title="Cyclomatic Complexity" data-container="body"></i></a></h3> <div id="fn-by-complexity" class="stat"></div> </div> <div class="col-md-6"> <h3 class="chart-header">By SLOC <i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Source Lines of Code / Logical Lines of Code" data-original-title="SLOC/LSLOC" data-container="body"></i></h3> <div id="fn-by-sloc" class="stat"></div> </div> </div> </div> <div class="container"> <div class="row"> var async = require(&#039;async&#039;), base = require(&#039;../base&#039;), clc = require(&#039;cli-color&#039;), logger = require(&#039;../logger&#039;), printed = {}; function Notifications(options) { this.options = options; if (!options.repo) { logger.error(&#039;You must specify a Git repository to run this command&#039;); } } Notifications.DETAILS = { options: { &#039;latest&#039;: Boolean, &#039;repo&#039; : String, &#039;user&#039; : String, &#039;watch&#039; : Boolean }, shorthands: { &#039;l&#039;: [ &#039;--latest&#039; ], &#039;r&#039;: [ &#039;--repo&#039; ], &#039;u&#039;: [ &#039;--user&#039; ], &#039;w&#039;: [ &#039;--watch&#039; ] }, description: &#039;Provides a set of util commands to work with Notifications.&#039; }; Notifications.prototype.run = function() { var instance = this, options = instance.options; if (options.latest) { logger.logTemplate(&#039;{{prefix}} [info] Listing activities on {{greenBright options.user &quot;/&quot; options.repo}}&#039;, { options: options }); instance.latest(); } if (options.watch) { logger.logTemplate(&#039;{{prefix}} [info] Watching any activity on {{greenBright options.user &quot;/&quot; options.repo}}&#039;, { options: options }); instance.watch(); } }; Notifications.prototype.latest = function(opt_watch) { var instance = this, options = instance.options, operations, payload, listEvents, filteredListEvents = []; operations = [ function(callback) { payload = { user: options.user, repo: options.repo }; base.github.events.getFromRepo(payload, function(err, data) { if (!err) { listEvents = data; } callback(err); }); }, function(callback) { listEvents.forEach(function(event) { event.txt = instance.getMessage_(event); if (options.watch) { if (!printed[event.created_at]) { filteredListEvents.push(event); } } else { filteredListEvents.push(event); } printed[event.created_at] = true; }); callback(); } ]; async.series(operations, function(err) { if (filteredListEvents.length) { logger.logTemplateFile(&#039;nt.handlebars&#039;, { user: options.user, repo: options.repo, latest: options.latest, watch: opt_watch, events: filteredListEvents }); } logger.defaultCallback(err, null, false); }); }; Notifications.prototype.watch = function() { var instance = this, intervalTime = 3000; instance.latest(); setInterval(function() { instance.latest(true); }, intervalTime); }; Notifications.prototype.getMessage_ = function(event) { var instance = this, txt = &#039;&#039;, type = event.type, payload = event.payload; switch (type) { case &#039;CommitCommentEvent&#039;: txt = &#039;commented on a commit at&#039;; break; case &#039;CreateEvent&#039;: txt = &#039;created a &#039; + payload.ref_type + &#039; at&#039;; break; case &#039;DeleteEvent&#039;: txt = &#039;removed &#039; + payload.ref_type + &#039; at&#039;; break; case &#039;DownloadEvent&#039;: txt = &#039;downloaded&#039;; break; case &#039;ForkEvent&#039;: txt = &#039;forked&#039;; break; case &#039;ForkApplyEvent&#039;: txt = &#039;applied patch &#039; + payload.head + &#039; at&#039;; break; case &#039;IssueCommentEvent&#039;: txt = &#039;commented on an issue at&#039;; break; case &#039;IssuesEvent&#039;: txt = payload.action + &#039; an issue at&#039;; break; case &#039;MemberEvent&#039;: txt = &#039;added &#039; + payload.member + &#039; as a collaborator to&#039;; break; case &#039;PublicEvent&#039;: txt = &#039;open sourced&#039;; break; case &#039;PullRequestEvent&#039;: txt = payload.action + &#039; pull request #&#039; + payload.number + &#039; at&#039;; break; case &#039;<API key>&#039;: txt = &#039;commented on a pull request at&#039;; break; case &#039;PushEvent&#039;: txt = &#039;pushed &#039; + payload.commits.length + &#039; commit(s) to&#039;; break; case &#039;WatchEvent&#039;: txt = &#039;is now watching&#039;; break; default: logger.error(&#039;event type not found: &#039; + clc.red(type)); break; } return txt; }; exports.Impl = Notifications;</textarea> </div> </div> <footer class="footer"> <div class="container"> <p>.</p> </div> </footer> <script type="text/html" id="<API key>"> <div class="complexity-notice"> Complexity : {{ complexity.cyclomatic }} <br> Length : {{ complexity.halstead.length }} <br> Difficulty : {{ complexity.halstead.difficulty.toFixed(2) }} <br> Est # bugs : {{ complexity.halstead.bugs.toFixed(2) }}<br> </div> </script> <script type="text/javascript" src="../../assets/scripts/bundles/core-bundle.js"></script> <script type="text/javascript" src="../../assets/scripts/bundles/codemirror.js"></script> <script type="text/javascript" src="../../assets/scripts/codemirror.markpopovertext.js"></script> <script type="text/javascript" src="report.js"></script> <script type="text/javascript" src="report.history.js"></script> <script type="text/javascript" src="../../assets/scripts/plato-file.js"></script> </body> </html>
// Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.applicationinsights.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** User assigned identity properties. */ @Immutable public class <API key> { @JsonIgnore private final ClientLogger logger = new ClientLogger(<API key>.class); /* * The principal ID of the assigned identity. */ @JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY) private UUID principalId; /* * The client ID of the assigned identity. */ @JsonProperty(value = "clientId", access = JsonProperty.Access.WRITE_ONLY) private UUID clientId; /** * Get the principalId property: The principal ID of the assigned identity. * * @return the principalId value. */ public UUID principalId() { return this.principalId; } /** * Get the clientId property: The client ID of the assigned identity. * * @return the clientId value. */ public UUID clientId() { return this.clientId; } /** * Validates the instance. * * @throws <API key> thrown if the instance is not valid. */ public void validate() { } }
angular.module('MetronicApp').controller('UsuariosCtrl', function ($scope, GetSv, $rootScope, PostSv,toaster) { $scope.usuarios = []; $scope.add = false; $scope.edit = false; $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers = function () { GetSv.getData("usuarios").then(function (data) { if (data.Error) { $scope.error = true; } else { $scope.usuarios = data; $scope.error = false; } }, function (e) { $scope.error = true; }); }; $scope.getUsers(); $scope.closeEdit = function () { $scope.a_editar = {}; $scope.edit = false; }; $scope.openEdit = function (item) { $scope.a_editar = item; $scope.edit = true; }; $scope.closeAdd = function () { $scope.add = false; }; $scope.openAdd = function (item) { $scope.a_editar = {}; $scope.add = true; }; $scope.sendUser = function (servlet, user) { PostSv.postData(servlet, {usuario: JSON.stringify(user)}).then(function (data) { if (data.Error) { toaster.pop('error', "Error", data.Error); } else { toaster.pop('success', "Exito", data.Exito); $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers(); $scope.add = false; $scope.edit = false; } }, function (e) { toaster.pop('error', "Error", "Error fatal"); } ); }; $scope.roles = $rootScope.roles; });
#include <vector> #include <memory> #include <iostream> using namespace std; shared_ptr<vector<int>> make() { return make_shared<vector<int>>(); } shared_ptr<vector<int>> read(shared_ptr<vector<int>> p) { cout << "Enter values: " << endl; int x; while (cin >> x) { p->push_back(x); } return p; } void print(shared_ptr<vector<int>> p) { for (int i : *p) { cout << i << " "; } } int main() { auto p = read(make()); print(p); return 0; }