answer
stringlengths
15
1.25M
[http: 1. forkgithub 2. `username.github.io` 3. clone`_posts` 4. CNAME 5. `_config.yml` 6. It's done! []http://yansu.org
// This is the main include file for the gcode library // It parses and executes G-code functions // gcode.h #ifndef GCODE_H #define GCODE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdarg.h> #ifndef NRF51 // G-code debug print unsigned int debug(const char *format, ...); #else #include "uart.h" #endif // Single G-code parameter typedef struct { char type; float value; } gcode_parameter_t; // Parse G-code command int gcode_parse(const char *s); // Extract G-code parameter (similar to strtok) int gcode_get_parameter(char **s, gcode_parameter_t *gp); #endif
import { DOCUMENT } from '@angular/common'; import { ApplicationRef, <API key>, Inject, Injectable, Injector } from '@angular/core'; import { BaseService } from 'ngx-weui/core'; import { ToptipsComponent, ToptipsType } from './toptips.component'; @Injectable({ providedIn: 'root' }) export class ToptipsService extends BaseService { constructor( protected readonly resolver: <API key>, protected readonly applicationRef: ApplicationRef, protected readonly injector: Injector, @Inject(DOCUMENT) protected readonly doc: any, ) { super(); } /** * Toptips * * @param text * @param type * @param ms */ show(text: string, type: ToptipsType, time: number = 2000): ToptipsComponent { const componentRef = this.build(ToptipsComponent); if (type) { componentRef.instance.type = type; } if (text) { componentRef.instance.text = text; } componentRef.instance.time = time; componentRef.instance.hide.subscribe(() => { setTimeout(() => { this.destroy(componentRef); }, 100); }); return componentRef.instance.onShow(); } /** * Warn Toptips * * @param text * @param time ms */ warn(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'warn', time); } /** * Info Toptips * * @param text * @param time ms */ info(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'info', time); } /** * Primary Toptips * * @param text * @param time ms */ primary(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'primary', time); } /** * Success Toptips * * @param text * @param time ms */ success(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'primary', time); } /** * Default Toptips * * @param text * @param time ms */ default(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'default', time); } }
require 'test_helper' class <API key> < ActiveSupport::TestCase # test "the truth" do # assert true # end end
var loadJsons = require('../lib/loadJsons'); describe("Get a recursive directory load of JSONs", function() { var data; beforeEach(function(done) { if(data) done(); else { loadJsons("./specs")(function(d) { data = d; done(); }); } }); it("Should return right number of jsons", function() { expect(data.length).toBe(6); }); it("Should have a @type field on all objects", function() { data.forEach(function(d) { expect(d['@type']).toBeDefined(); }); }); });
layout: post status: publish published: true title: Moved to Jekyll blog engine date: 2015-10-20 22:31:25.000000000 +05:30 comments: [] I have been using wordpress since the time I started blogging. I decided to make a move to the Jekyll static templating engine after I came to know about its simplicity and ability to host on github. Blogs are usually immutable once they are written. There is no reason use dynamic pages for blogs. The theme of this blog is based on [jekyll-incorporated](https://github.com/kippt/jekyll-incorporated). I generally don't like the WYSWYG editor that comes with the wordpress. I would prefer to write blog posts on vim as I write code. WYSWYG editors add lots of junk into the generated html. I had to to spend a lot of time migrating those editor generator markup into jekyll plain text. Blog is now hosted on [github](github.com/t3rm1n4l/t3rm1n4l.github.io). Luckly, I could import most of the comments into discuss. I hope to blog more frequently with this transition.
using System; using System.Diagnostics; using System.Text; namespace BgeniiusUniversity.Logging { public class Logger : ILogger { public void Information(string message) { Trace.TraceInformation(message); } public void Information(string fmt, params object[] vars) { Trace.TraceInformation(fmt, vars); } public void Information(Exception exception, string fmt, params object[] vars) { Trace.TraceInformation(<API key>(exception, fmt, vars)); } public void Warning(string message) { Trace.TraceWarning(message); } public void Warning(string fmt, params object[] vars) { Trace.TraceWarning(fmt, vars); } public void Warning(Exception exception, string fmt, params object[] vars) { Trace.TraceWarning(<API key>(exception, fmt, vars)); } public void Error(string message) { Trace.TraceError(message); } public void Error(string fmt, params object[] vars) { Trace.TraceError(fmt, vars); } public void Error(Exception exception, string fmt, params object[] vars) { Trace.TraceError(<API key>(exception, fmt, vars)); } public void TraceApi(string componentName, string method, TimeSpan timespan) { TraceApi(componentName, method, timespan, ""); } public void TraceApi(string componentName, string method, TimeSpan timespan, string fmt, params object[] vars) { TraceApi(componentName, method, timespan, string.Format(fmt, vars)); } public void TraceApi(string componentName, string method, TimeSpan timespan, string properties) { string message = String.Concat("Component:", componentName, ";Method:", method, ";Timespan:", timespan.ToString(), ";Properties:", properties); Trace.TraceInformation(message); } private static string <API key>(Exception exception, string fmt, object[] vars) { // Simple exception formatting: for a more comprehensive version see var sb = new StringBuilder(); sb.Append(string.Format(fmt, vars)); sb.Append(" Exception: "); sb.Append(exception.ToString()); return sb.ToString(); } } }
layout: article title: "The Zen of Design Patterns (2nd Edition)" categories: programing tags: [java, reading] toc: false image: teaser: programing/<API key>-(2nd-Edition)/teaser.jpg date: 2017-11-05 * SRPSingle Responsibility Principle * RBACRole-Based Access Control * BOBusiness Object * BizBusiness Logic (SRP) * LSPLiskov Substitution Principle (LSP) 1. 2. 3. (Override) 4. (Override) (Override)@Override(Overload) * DIPDependence Inversion Principle * OODObject-Oriented Design * TDDTest-Driven Development (OOD)“” 1. 2. 3. 1. {% highlight java %} {% raw %} Public interface IDriver { public void drive(); } public class Driver implements IDriver { private ICar car; public Driver(ICar _car) { this.car = _car; } public void drive() { this.car.run(); } } {% endraw %} {% endhighlight %} 2. Setter {% highlight java %} {% raw %} public interface IDriver { public void setCar(Icar car); public void drive(); } public class Driver implements IDriver { private ICar car; // Setter public void setCar(ICar _car) { this.car = _car; } public void drive() { this.car.run(); } } {% endraw %} {% endhighlight %} 3. {% highlight java %} {% raw %} public interface IDriver { public void drive(ICar car); } public class Driver implements IDriver { public void drive(ICar car) { car.run(); } } {% endraw %} {% endhighlight %} IDriverICar(TDD)JMock {% highlight java %} {% raw %} Public class DriverTest extends TestCase { Mockery context = new JUnit4Mockery(); @Test public void testDriver() { final ICar car = context.mock(ICar.class); IDriver driver = new Driver(); context.checking(new Expectations(){{ oneOf(car).run(); }}); driver.drive(car); } } {% endraw %} {% endhighlight %} 1. 2. clone 3. 4. 5. * ISPInterface Segregation Principle * LoDLaw of DemeterLKPLeast Knowledge Principle * RMIRemote Method Invocation * VOValue Object public 1. JDK API 2. publicpublic 3. 4. Serializable(RMI)(VO)SerializableNotSerializableExceptionVOprivatepublic * OCPOpen Closed Principle Java 3 1. public 2. (metadata)(Inversion of Control)Spring 3. BeanAnnotation 4. 623 6 1. Single Responsibility Principle: 2. Open Closed Principle: 3. Liskov Substitution Principle: 4. Law of Demeter: 5. Interface Segregation Principle: 6. Dependence Inversion Principle: 6SolidL5 (Singleton Pattern) ![1-singleton](/images/programing/<API key>-(2nd-Edition)/1-singleton.png) 1. 2. 3. 4. SpringBeanSringBean ![2-factory](/images/programing/<API key>-(2nd-Edition)/2-factory.png) 1. 2. 3. 4. static Map ![3-abstract-factory](/images/programing/<API key>-(2nd-Edition)/3-abstract-factory.png) 1. 2. A1.2B CAbstractCreatorcreateProductC() ![4-template](/images/programing/<API key>-(2nd-Edition)/4-template.png) final (Hook Method) 1. 2. 3. “” ![5-builder](/images/programing/<API key>-(2nd-Edition)/5-builder.png) 4 1. 2. 3. AOPAspect Oriented Programming ![6-proxy](/images/programing/<API key>-(2nd-Edition)/6-proxy.png) 1. 2. 3. new (AOP) InvocationHandlerJDKinvoke AOP(Aspect)(JoinPoint)(Advice)(Weave) new ![7-prototype](/images/programing/<API key>-(2nd-Edition)/7-prototype.png) cloneJavaCloneablecloneCloneableclonecloneObjectObject 1. 2. Objectclone intlongcharStringJavaclone(stringpool) cloneJDKArrayListclone clonefinal clone ![8-mediator](/images/programing/<API key>-(2nd-Edition)/8-mediator.png) StrutsMVCC(Controller)MModelVViewMV ![9-command](/images/programing/<API key>-(2nd-Edition)/9-command.png) 1. Commandexecute 2. Command 3. Command Command Command ![<API key>](/images/programing/<API key>-(2nd-Edition)/<API key>.png) clientHandlersetNextresponsegetHandlerLevel Component ![11-decorator](/images/programing/<API key>-(2nd-Edition)/11-decorator.png) 1. ComponentDecoratorDecoratorComponentComponent 2. Componentis-a 3. FatherSonhGrandSonSonGrandSonGrandSonSonDecoratorSon ContextStrategy ![12-strategy](/images/programing/<API key>-(2nd-Edition)/12-strategy.png) 1. 2. 3. ![13-adapter](/images/programing/<API key>-(2nd-Edition)/13-adapter.png) 1. 2. Target 3. Target 4. CollectionSet ![14-interator](/images/programing/<API key>-(2nd-Edition)/14-interator.png) Javajava.util.iteratorhasNextnextremoveremoveJavaiterator JavaAPI “-” ![15-composite](/images/programing/<API key>-(2nd-Edition)/15-composite.png) 1. Component 2. Component Operation()ComponentComponentgetChildren XML / ![16-observer](/images/programing/<API key>-(2nd-Edition)/16-observer.png) 1. 2. EJB(Enterprise JavaBean)3BeanSession BeanEntity BeanMessageDriven Bean(MDB)MDBBeanEJBMessage Queue JDKjava.util.Observablejava.util.Observer ![17-facade](/images/programing/<API key>-(2nd-Edition)/17-facade.png) 1. 2. 3. ClassAClassB ![18-memento](/images/programing/<API key>-(2nd-Edition)/18-memento.png) cloneCloneable“”Clone MapMap ![19-visitor](/images/programing/<API key>-(2nd-Edition)/19-visitor.png) 1. Vistor 2. 3. Vistor Java {% highlight java %} {% raw %} public abstract class AbsActor { //act public void act(Role role){ System.out.println(""); } public void act(KungFuRole role){ System.out.println(""); } } public class YoungActor extends AbsActor { public void act(KungFuRole role){ System.out.println(""); } } public class OldActor extends AbsActor { public void act(KungFuRole role){ System.out.println(""); } } public class Client { public static void main(String[] args) { AbsActor actor = new OldActor(); Role role = new KungFuRole(); actor.act(role); actor.act(new KungFuRole()); } } {% endraw %} {% endhighlight %} {% raw %} {% endraw %} actor {% highlight java %} {% raw %} //AbsActorRole public interface Role { public void accept(AbsActor actor); } public class KungFuRole implements Role { public void accept(AbsActor actor){ actor.act(this); } } public class IdiotRole implements Role { public void accept(AbsActor actor){ actor.act(this); } } public class Client { public static void main(String[] args) { AbsActor actor = new OldActor(); Role role = new KungFuRole(); role.accept(actor); } } {% endraw %} {% endhighlight %} {% raw %} {% endraw %} Java UI ![20-state](/images/programing/<API key>-(2nd-Edition)/20-state.png) 1. 2. 3. 5 () ![21-interpreter](/images/programing/<API key>-(2nd-Edition)/21-interpreter.png) ()() shellJRubyGroovyJavaExpression4JMESP(Math Expression String Prser)Jep (Flyweight Pattern) ![22-flyweight](/images/programing/<API key>-(2nd-Edition)/22-flyweight.png) (intrinsic)(extrinsic) id + finalSession JavaMapequalshashCodehashCodeequalsturekey JavaStringintern AB“”“” ()()() ![23-bridge](/images/programing/<API key>-(2nd-Edition)/23-bridge.png) N The End. zhlinh Email: zhlinhng@gmail.com 2017-11-05
<?php /** * Rule checking that the form field is not empty */ require_once 'HTML/QuickForm2/Rule/Nonempty.php'; /** * Rule for required elements * * The main difference from "nonempty" Rule is that * - elements to which this Rule is attached will be considered required * ({@link <API key>::isRequired()} will return true for them) and * marked accordingly when outputting the form * - this Rule can only be added directly to the element and other Rules can * only be added to it via and_() method * * @category HTML * @package HTML_QuickForm2 * @author Alexey Borzov <avb@php.net> * @author Bertrand Mansion <golgote@mamasam.com> * @version Release: 0.4.0 */ class <API key> extends <API key> { /** * Disallows adding a rule to the chain with an "or" operator * * Required rules are different from all others because they affect the * visual representation of an element ("* denotes required field"). * Therefore we cannot allow chaining other rules to these via or_(), since * this will effectively mean that the field is not required anymore and the * visual difference is bogus. * * @param <API key> * @throws <API key> */ public function or_(<API key> $next) { throw new <API key>( 'or_(): Cannot add a rule to "required" rule' ); } } ?>
class String def split_on_unescaped(str) self.split(/\s*(?<!\\)#{str}\s*/).map{|s| s.gsub(/\\(?=#{str})/, '') } end end
import axios from 'axios'; import { updateRadius } from './radius-reducer'; import { AddBType } from './b-type-reducer'; // import { create as createUser } from './users'; // import history from '../history'; const ADD_B_TYPE = 'ADD_B_TYPE'; const ADD_LNG_LAT = 'ADD_LNG_LAT'; const UPDATE_RADIUS = 'UPDATE_RADIUS'; const SWITCH_MEASUREMENT = 'SWITCH_MEASUREMENT'; export const addLngLat = (latitude, longitude) => ({ type: ADD_LNG_LAT, latitude, longitude }); export const switchMeasurement = measurement => ({ type: SWITCH_MEASUREMENT, measurement }); export default function reducer (state = { latitude: null, longitude: null, radius: null, businessType: null, distanceMeasurement: 'miles' }, action) { switch (action.type) { case ADD_B_TYPE: state.businessType = action.typeStr; break; case ADD_LNG_LAT: state.latitude = action.latitude; state.longitude = action.longitude; break; case UPDATE_RADIUS: state.radius = action.radInt; break; case SWITCH_MEASUREMENT: state.distanceMeasurement = action.measurement; break; default: return state; } return state; }
<h4>Lists</h4> <h5>Simple List</h5> <mdl-list> <mdl-list-item> <<API key>> Bryan Cranston </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> Aaron Paul </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> Bob Odenkirk </<API key>> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item> <<API key>> Bryan Cranston </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> Aaron Paul </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> Bob Odenkirk </<API key>> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Icons</h5> <mdl-list> <mdl-list-item> <<API key>> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bryan Cranston </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon mdl-list-item-icon>person</mdl-icon> Aaron Paul </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bob Odenkirk </<API key>> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item> <<API key>> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bryan Cranston </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon mdl-list-item-icon>person</mdl-icon> Aaron Paul </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bob Odenkirk </<API key>> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Avatars and actions</h5> <mdl-list> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bryan Cranston</span> </<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Aaron Paul</span> </<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bob Odenkirk</span> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bryan Cranston</span> </<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Aaron Paul</span> </<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bob Odenkirk</span> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Avatars and controls</h5> <mdl-list> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> Bryan Cranston </<API key>> <<API key>> <mdl-checkbox mdl-ripple></mdl-checkbox> </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> Aaron Paul </<API key>> <<API key>> <mdl-radio ngModel="false" mdl-ripple></mdl-radio> </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> Bob Odenkirk </<API key>> <<API key>> <mdl-switch mdl-ripple></mdl-switch> </<API key>> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <style> mdl-radio, mdl-checkbox, mdl-switch { display: inline; } </style> <mdl-list> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> Bryan Cranston </<API key>> <<API key>> <mdl-checkbox mdl-ripple></mdl-checkbox> </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> Aaron Paul </<API key>> <<API key>> <mdl-radio ngModel="false" mdl-ripple></mdl-radio> </<API key>> </mdl-list-item> <mdl-list-item> <<API key>> <mdl-icon <API key>>person</mdl-icon> Bob Odenkirk </<API key>> <<API key>> <mdl-switch mdl-ripple></mdl-switch> </<API key>> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Two line</h5> <mdl-list> <mdl-list-item lines="2"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bryan Cranston</span> <<API key>>62 Episodes</<API key>> </<API key>> <<API key>> <<API key>>Actor</<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="2"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Aaron Paul</span> <<API key>>62 Episodes</<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="2"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bob Odenkirk</span> <<API key>>62 Episodes</<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item lines="2"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bryan Cranston</span> <<API key>>62 Episodes</<API key>> </<API key>> <<API key>> <<API key>>Actor</<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="2"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Aaron Paul</span> <<API key>>62 Episodes</<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="2"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bob Odenkirk</span> <<API key>>62 Episodes</<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Three line</h5> <mdl-list style="width:650px"> <mdl-list-item lines="3"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bryan Cranston</span> <<API key>> Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle. </<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="3"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Aaron Paul</span> <<API key>> Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie. </<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="3"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bob Odenkirk</span> <<API key>> Bob Odinkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul". </<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list style="width:650px"> <mdl-list-item lines="3"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bryan Cranston</span> <<API key>> Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle. </<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="3"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Aaron Paul</span> <<API key>> Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie. </<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> <mdl-list-item lines="3"> <<API key>> <mdl-icon <API key>>person</mdl-icon> <span>Bob Odenkirk</span> <<API key>> Bob Odinkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul". </<API key>> </<API key>> <<API key>> <a href="#"><mdl-icon>star</mdl-icon></a> </<API key>> </mdl-list-item> </mdl-list> ]]> </pre> <h5> List components</h5> <table class="docu" mdl-shadow="2"> <thead> <tr> <th>Component</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>mdl-list</td> <td> Basic container for any <i>mdl-list</i> component. </td> </tr> <tr> <td>mdl-list-item</td> <td> Defines a item in the list. The attribute <i>lines</i> will be used to specify of how many individual lines a list item consist. You can use <i>1</i>, <i>2</i> and <i>3</i>. <i>1</i> is the default value. </td> </tr> <tr> <td><API key></td> <td> Defines the primary content sub-division. </td> </tr> <tr> <td><API key></td> <td> Defines the Action sub-division. Needs a 2 or 3 line list-item. </td> </tr> <tr> <td><API key></td> <td> Defines the secondary content sub-division. Needs a 2 or 3 line list-item. </td> </tr> <tr> <td><API key></td> <td> Defines the information sub-division. Needs a 2 or 3 line list-item. </td> </tr> <tr> <td><API key></td> <td> Defines the sub title in the <i><API key></i> component. </td> </tr> <tr> <td><API key></td> <td> Defines the text-section in the <i><API key></i> component. </td> </tr> </tbody> </table> <h5>Additional attributes for mdl-icon</h5> <p>These attributes can be used to style <i>mdl-icons</i> in lists</p> <table class="docu" mdl-shadow="2"> <thead> <tr> <th>Attribute</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><API key>></td> <td> avatar icon. </td> </tr> <tr> <td>mdl-list-item-icon</td> <td> Small icon. </td> </tr> <tr> <td>mdl-ripple</td> <td>Add <i>mdl-ripple</i> to the <i>mdl-list-item</i> component to create a ripple effect.</td> </tr> </tbody> </table>
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace RS.TimeLogger { [global::System.Runtime.CompilerServices.<API key>()] [global::System.CodeDom.Compiler.<API key>("Microsoft.VisualStudio.Editors.SettingsDesigner.<API key>", "15.1.0.0")] internal sealed partial class Settings : global::System.Configuration.<API key> { private static Settings defaultInstance = ((Settings)(global::System.Configuration.<API key>.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.<API key>()] [global::System.Diagnostics.<API key>()] [global::System.Configuration.<API key>("")] public string LastUser { get { return ((string)(this["LastUser"])); } set { this["LastUser"] = value; } } [global::System.Configuration.<API key>()] [global::System.Diagnostics.<API key>()] [global::System.Configuration.<API key>("<API key>")] public global::System.Guid LastActivity { get { return ((global::System.Guid)(this["LastActivity"])); } set { this["LastActivity"] = value; } } } }
(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'module', 'skatejs'], factory); } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') { factory(exports, module, require('skatejs')); } else { var mod = { exports: {} }; factory(mod.exports, mod, global.skate); global.skate = mod.exports; } })(this, function (exports, module, _skatejs) { 'use strict'; function <API key>(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _skate = <API key>(_skatejs); var auiSkate = _skate['default'].noConflict(); module.exports = auiSkate; }); //# sourceMappingURL=../../../js/aui/internal/skate.js.map
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIButton : MonoBehaviour { [SerializeField] private GameObject targetObject; [SerializeField] private string targetMessage; public Color highlightColor = Color.cyan; public void OnMouseOver() { SpriteRenderer sprite = GetComponent<SpriteRenderer>(); if (sprite != null) { sprite.color = highlightColor; } } public void OnMouseExit() { SpriteRenderer sprite = GetComponent<SpriteRenderer>(); if (sprite != null) { sprite.color = Color.white; } } public void OnMouseDown() { transform.localScale *= 1.1f; } public void OnMouseUp() { transform.localScale = Vector3.one; if (targetObject != null) { targetObject.SendMessage(targetMessage); } } }
<footer class="main-footer"> <div class="pull-right hidden-xs"> </div> <strong>Orange TV.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 2.2.3 --> <script src="assets/plugins/jQuery/jquery-2.2.3.min.js"></script> <!-- jQuery UI 1.11.4 --> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button); </script> <!-- DataTables --> <script src="assets/plugins/datatables/jquery.dataTables.min.js"></script> <script src="assets/plugins/datatables/dataTables.bootstrap.min.js"></script> <!--<script src="assets/plugins/ckeditor/adapters/jquery.js"></script>--> <!-- Bootstrap 3.3.6 --> <script src="assets/bootstrap/js/bootstrap.min.js"></script> <!-- Morris.js charts --> <! <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="assets/plugins/morris/morris.min.js"></script> <!-- Sparkline --> <script src="assets/plugins/sparkline/jquery.sparkline.min.js"></script> <!-- jvectormap --> <script src="assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script> <script src="assets/plugins/jvectormap/<API key>.js"></script> <!-- jQuery Knob Chart --> <script src="assets/plugins/knob/jquery.knob.js"></script> <!-- daterangepicker --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script> <script src="assets/plugins/daterangepicker/daterangepicker.js"></script> <!-- datepicker --> <script src="assets/plugins/datepicker/<API key>.js"></script> <!-- Bootstrap WYSIHTML5 --> <script src="assets/plugins/bootstrap-wysihtml5/<API key>.all.min.js"></script> <!-- Slimscroll --> <script src="assets/plugins/slimScroll/jquery.slimscroll.min.js"></script> <!-- FastClick --> <script src="assets/plugins/fastclick/fastclick.js"></script> <!-- AdminLTE App --> <script src="assets/dist/js/app.min.js"></script> <!-- AdminLTE dashboard demo (This is only for demo purposes) --> <!--<script src="assets/dist/js/pages/dashboard.js"></script>--> <!-- AdminLTE for demo purposes --> <script src="assets/dist/js/demo.js"></script> <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.flash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script> <! <script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script> <script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script> <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.print.min.js"></script> <script src="assets/dist/js/custom.js"></script> <script> $(function () { /* var table = $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] } ); table.buttons().container() .appendTo( $('div.eight.column:eq(0)', table.table().container()) ); $('#example2').DataTable( { buttons: [ { extend: 'excel', text: 'Save current page', exportOptions: { modifier: { page: 'current' } } } ] } ); */ $('#example').DataTable( { dom: 'Bfrtip', pageLength: 5, //dom : 'Bflit', buttons: ['copy', 'csv', 'excel', 'pdf', 'print'], responsive: true } ); $("#example1").DataTable(); $("#example2").DataTable({ "paging": false }); $('#example3').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": true, "info": true, "autoWidth": false }); $('#example30').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": true, "info": true, "autoWidth": false }); }); // datatable paging $(function() { table = $('#example2c').DataTable({ "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. // Load data for the table's content from an Ajax source "ajax": { "url": "<?php if(isset($url)) {echo $url; } ?>", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [ { "targets": [ 0 ], //first column / numbering column "orderable": false, //set not orderable }, ], }); }); </script> </body> </html>
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace Neo.Properties { using System; <summary> A strongly-typed resource class, for looking up localized strings, etc. </summary> // This class was auto-generated by the <API key> // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.<API key>("System.Resources.Tools.<API key>", "4.0.0.0")] [global::System.Diagnostics.<API key>()] [global::System.Runtime.CompilerServices.<API key>()] internal class Strings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.<API key>("Microsoft.Performance", "CA1811:<API key>")] internal Strings() { } <summary> Returns the cached ResourceManager instance used by this class. </summary> [global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Neo.Properties.Strings", typeof(Strings).Assembly); resourceMan = temp; } return resourceMan; } } <summary> Overrides the current thread's CurrentUICulture property for all resource lookups using this strongly typed resource class. </summary> [global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } <summary> Looks up a localized string similar to About. </summary> internal static string About { get { return ResourceManager.GetString("About", resourceCulture); } } <summary> Looks up a localized string similar to AntShares. </summary> internal static string AboutMessage { get { return ResourceManager.GetString("AboutMessage", resourceCulture); } } <summary> Looks up a localized string similar to Version:. </summary> internal static string AboutVersion { get { return ResourceManager.GetString("AboutVersion", resourceCulture); } } <summary> Looks up a localized string similar to Failed to add smart contract, corresponding private key missing in this wallet.. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Address. </summary> internal static string Address { get { return ResourceManager.GetString("Address", resourceCulture); } } <summary> Looks up a localized string similar to Change password successful.. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Confirmation. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Upon deletion, assets in these addresses will be permanently lost, are you sure to proceed?. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Assets cannot be recovered once deleted, are you sure to delete the assets?. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Confirmation. </summary> internal static string DeleteConfirmation { get { return ResourceManager.GetString("DeleteConfirmation", resourceCulture); } } <summary> Looks up a localized string similar to Enter remark here, which will be recorded on the blockchain. </summary> internal static string EnterRemarkMessage { get { return ResourceManager.GetString("EnterRemarkMessage", resourceCulture); } } <summary> Looks up a localized string similar to Transaction Remark. </summary> internal static string EnterRemarkTitle { get { return ResourceManager.GetString("EnterRemarkTitle", resourceCulture); } } <summary> Looks up a localized string similar to Execution terminated in fault state.. </summary> internal static string ExecutionFailed { get { return ResourceManager.GetString("ExecutionFailed", resourceCulture); } } <summary> Looks up a localized string similar to Expired. </summary> internal static string ExpiredCertificate { get { return ResourceManager.GetString("ExpiredCertificate", resourceCulture); } } <summary> Looks up a localized string similar to Failed. </summary> internal static string Failed { get { return ResourceManager.GetString("Failed", resourceCulture); } } <summary> Looks up a localized string similar to Import Watch-Only Address. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Transaction initiated, but the signature is incomplete.. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Incomplete signature. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to You have cancelled the certificate installation.. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Install the certificate. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Anthares must install Onchain root certificate to validate assets on the blockchain, install it now?. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Insufficient funds, transaction cannot be initiated.. </summary> internal static string InsufficientFunds { get { return ResourceManager.GetString("InsufficientFunds", resourceCulture); } } <summary> Looks up a localized string similar to Invalid. </summary> internal static string InvalidCertificate { get { return ResourceManager.GetString("InvalidCertificate", resourceCulture); } } <summary> Looks up a localized string similar to Migrate Wallet. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Opening wallet files in older versions, update to newest format? Note: updated files cannot be openned by clients in older versions!. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Wallet file relocated. New wallet file has been saved at: . </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Password Incorrect. </summary> internal static string PasswordIncorrect { get { return ResourceManager.GetString("PasswordIncorrect", resourceCulture); } } <summary> Looks up a localized string similar to Data broadcast success, the hash is shown as follows:. </summary> internal static string RelaySuccessText { get { return ResourceManager.GetString("RelaySuccessText", resourceCulture); } } <summary> Looks up a localized string similar to Broadcast Success. </summary> internal static string RelaySuccessTitle { get { return ResourceManager.GetString("RelaySuccessTitle", resourceCulture); } } <summary> Looks up a localized string similar to Raw:. </summary> internal static string RelayTitle { get { return ResourceManager.GetString("RelayTitle", resourceCulture); } } <summary> Looks up a localized string similar to Transaction sent, TXID:. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Transaction successful. </summary> internal static string SendTxSucceedTitle { get { return ResourceManager.GetString("SendTxSucceedTitle", resourceCulture); } } <summary> Looks up a localized string similar to The private key that can sign the data is not found.. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to You must input JSON object pending signature data.. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to System. </summary> internal static string SystemIssuer { get { return ResourceManager.GetString("SystemIssuer", resourceCulture); } } <summary> Looks up a localized string similar to Validation failed, the counterparty falsified the transaction content!. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Validation failed, the counterparty generated illegal transaction content!. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Validation failed, invalid transaction or unsynchronized blockchain, please try again when synchronized!. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Need Signature. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Transaction generated, please send the following information to the counterparty for signing:. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Trade Request. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Transaction request generated, please send it to the counterparty or merge it with the counterparty&apos;s request.. </summary> internal static string <API key> { get { return ResourceManager.GetString("<API key>", resourceCulture); } } <summary> Looks up a localized string similar to Trade Success. </summary> internal static string TradeSuccessCaption { get { return ResourceManager.GetString("TradeSuccessCaption", resourceCulture); } } <summary> Looks up a localized string similar to Transaction sent, this is the TXID:. </summary> internal static string TradeSuccessMessage { get { return ResourceManager.GetString("TradeSuccessMessage", resourceCulture); } } <summary> Looks up a localized string similar to unconfirmed. </summary> internal static string Unconfirmed { get { return ResourceManager.GetString("Unconfirmed", resourceCulture); } } <summary> Looks up a localized string similar to unknown issuer. </summary> internal static string UnknownIssuer { get { return ResourceManager.GetString("UnknownIssuer", resourceCulture); } } <summary> Looks up a localized string similar to Blockchain unsynchronized, transaction cannot be sent.. </summary> internal static string UnsynchronizedBlock { get { return ResourceManager.GetString("UnsynchronizedBlock", resourceCulture); } } } }
# Velocity Library last modified: 5/1/2019 9:00 AM. A reusable library in Velocity for Cascade with examples. This is the code base the Upstate team use to implement our Brisk site. The other part of the Upstate library: https://github.com/drulykg/Cascade-CMS/tree/master/_brisk A note about filenames. All files whose filenames with a "chanw-" prefix contain code reusable by anyone. Those with the "upstate-" prefix contain business logic specific to Upstate. <ul> <li> <a href="http: <li><a href="https: <li><a href="https: <li><a href="http: </ul>
using Newtonsoft.Json; using System.Collections.Generic; namespace EaToGliffy.Gliffy.Model { public class GliffyParentObject : GliffyObject { [JsonProperty(PropertyName = "children")] public List<GliffyObject> Children { get; set; } } }
#include "<API key>.h" #include <cassert> #include <stdexcept> #include "Common/StringTools.h" using Common::JsonValue; using namespace CryptoNote; namespace CryptoNote { std::ostream& operator<<(std::ostream& out, const <API key>& enumerator) { out << enumerator.root; return out; } } namespace { template <typename T> void insertOrPush(JsonValue& js, Common::StringView name, const T& value) { if (js.isArray()) { js.pushBack(JsonValue(value)); } else { js.insert(std::string(name), JsonValue(value)); } } } <API key>::<API key>() : root(JsonValue::OBJECT) { chain.push_back(&root); } <API key>::~<API key>() { } ISerializer::SerializerType <API key>::type() const { return ISerializer::OUTPUT; } bool <API key>::beginObject(Common::StringView name) { JsonValue& parent = *chain.back(); JsonValue obj(JsonValue::OBJECT); if (parent.isObject()) { chain.push_back(&parent.insert(std::string(name), obj)); } else { chain.push_back(&parent.pushBack(obj)); } return true; } void <API key>::endObject() { assert(!chain.empty()); chain.pop_back(); } bool <API key>::beginArray(size_t& size, Common::StringView name) { JsonValue val(JsonValue::ARRAY); JsonValue& res = chain.back()->insert(std::string(name), val); chain.push_back(&res); return true; } void <API key>::endArray() { assert(!chain.empty()); chain.pop_back(); } bool <API key>::operator()(uint64_t& value, Common::StringView name) { int64_t v = static_cast<int64_t>(value); return operator()(v, name); } bool <API key>::operator()(uint16_t& value, Common::StringView name) { uint64_t v = static_cast<uint64_t>(value); return operator()(v, name); } bool <API key>::operator()(int16_t& value, Common::StringView name) { int64_t v = static_cast<int64_t>(value); return operator()(v, name); } bool <API key>::operator()(uint32_t& value, Common::StringView name) { uint64_t v = static_cast<uint64_t>(value); return operator()(v, name); } bool <API key>::operator()(int32_t& value, Common::StringView name) { int64_t v = static_cast<int64_t>(value); return operator()(v, name); } bool <API key>::operator()(int64_t& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool <API key>::operator()(double& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool <API key>::operator()(std::string& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool <API key>::operator()(uint8_t& value, Common::StringView name) { insertOrPush(*chain.back(), name, static_cast<int64_t>(value)); return true; } bool <API key>::operator()(bool& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool <API key>::binary(void* value, size_t size, Common::StringView name) { std::string hex = Common::toHex(value, size); return (*this)(hex, name); } bool <API key>::binary(std::string& value, Common::StringView name) { return binary(const_cast<char*>(value.data()), value.size(), name); }
# Be sure to restart your server when you modify this file. Refinery::Application.config.session_store :cookie_store, :key => '_skwarcan_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # Refinery::Application.config.session_store :active_record_store
function base64Encode(input) { var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "="; var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function base64Decode(input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; var base64test = /[^A-Za-z0-9/+ if (base64test.exec(input)) { alert("There were invalid base64 characters in the input text./n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='/n" + "Expect errors in decoding."); } input = input.replace(/[^A-Za-z0-9/+ output=new Array(); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output.push(chr1); if (enc3 != 64) { output.push(chr2); } if (enc4 != 64) { output.push(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function UTF8Encode(str){ var temp = "",rs = ""; for( var i=0 , len = str.length; i < len; i++ ){ temp = str.charCodeAt(i).toString(16); rs += "\\u"+ new Array(5-temp.length).join("0") + temp; } return rs; } function UTF8Decode(str){ return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){ return String.fromCharCode(parseInt($2,16)); }); } exports.base64Encode = base64Encode; exports.base64Decode = base64Decode; exports.UTF8Encode = UTF8Encode; exports.UTF8Decode = UTF8Decode;
<?php namespace ShinyDeploy\Domain\Database; use ShinyDeploy\Core\Crypto\PasswordCrypto; use ShinyDeploy\Core\Helper\StringHelper; use ShinyDeploy\Exceptions\DatabaseException; use ShinyDeploy\Exceptions\<API key>; use ShinyDeploy\Traits\CryptableDomain; class ApiKeys extends DatabaseDomain { use CryptableDomain; /** * Generates new API key and stores it to database. * * @param int $deploymentId * @throws DatabaseException * @throws <API key> * @throws \ShinyDeploy\Exceptions\<API key> * @return array */ public function addApiKey(int $deploymentId): array { if (empty($this->encryptionKey)) { throw new <API key>('Encryption key not set.'); } if (empty($deploymentId)) { throw new <API key>('Deployment id can not be empty.'); } $apiKey = StringHelper::getRandomString(20); $passwordForUrl = StringHelper::getRandomString(16); $password = $passwordForUrl . $this->config->get('auth.secret'); $passwordHash = hash('sha256', $password); $encryption = new PasswordCrypto(); $encryptionKeySave = $encryption->encrypt($this->encryptionKey, $password); $statement = "INSERT INTO api_keys (`api_key`,`deployment_id`,`password`,`encryption_key`)" . " VALUES (%s,%i,%s,%s)"; $result = $this->db->prepare($statement, $apiKey, $deploymentId, $passwordHash, $encryptionKeySave)->execute(); if ($result === false) { throw new DatabaseException('Could not store API key to database.'); } return [ 'apiKey' => $apiKey, 'apiPassword' => $passwordForUrl ]; } /** * Deletes all existing API keys for specified deployment. * * @param int $deploymentId * @throws <API key> * @return bool */ public function <API key>(int $deploymentId): bool { if (empty($deploymentId)) { throw new <API key>('Deployment id can not be empty.'); } try { $statement = "DELETE FROM api_keys WHERE `deployment_id` = %i"; return $this->db->prepare($statement, $deploymentId)->execute(); } catch (DatabaseException $e) { return false; } } /** * Fetches API key data by api-key. * * @param string $apiKey * @return array * @throws <API key> * @throws DatabaseException */ public function getDataByApiKey(string $apiKey): array { if (empty($apiKey)) { throw new <API key>('API key can not be empty.'); } $statement = "SELECT * FROM api_keys WHERE `api_key` = %s"; return $this->db->prepare($statement, $apiKey)->getResult(); } }
require File.dirname(__FILE__) + '/../spec_helper' describe "Standard Tags" do dataset :users_and_pages, :file_not_found, :snippets it '<r:page> should allow access to the current page' do page(:home) page.should render('<r:page:title />').as('Home') page.should render(%{<r:find url="/radius"><r:title /> | <r:page:title /></r:find>}).as('Radius | Home') end [:breadcrumb, :slug, :title, :url].each do |attr| it "<r:#{attr}> should render the '#{attr}' attribute" do value = page.send(attr) page.should render("<r:#{attr} />").as(value.to_s) end end it "<r:url> with a nil relative URL root should scope to the relative root of /" do ActionController::Base.relative_url_root = nil page(:home).should render("<r:url />").as("/") end it '<r:url> with a relative URL root should scope to the relative root' do page(:home).should render("<r:url />").with_relative_root("/foo").as("/foo/") end it '<r:parent> should change the local context to the parent page' do page(:parent) page.should render('<r:parent><r:title /></r:parent>').as(pages(:home).title) page.should render('<r:parent><r:children:each by="title"><r:title /></r:children:each></r:parent>').as(<API key>(pages(:home)).collect(&:title).join("")) page.should render('<r:children:each><r:parent:title /></r:children:each>').as(@page.title * page.children.count) end it '<r:if_parent> should render the contained block if the current page has a parent page' do page.should render('<r:if_parent>true</r:if_parent>').as('true') page(:home).should render('<r:if_parent>true</r:if_parent>').as('') end it '<r:unless_parent> should render the contained block unless the current page has a parent page' do page.should render('<r:unless_parent>true</r:unless_parent>').as('') page(:home).should render('<r:unless_parent>true</r:unless_parent>').as('true') end it '<r:if_children> should render the contained block if the current page has child pages' do page(:home).should render('<r:if_children>true</r:if_children>').as('true') page(:childless).should render('<r:if_children>true</r:if_children>').as('') end it '<r:unless_children> should render the contained block if the current page has no child pages' do page(:home).should render('<r:unless_children>true</r:unless_children>').as('') page(:childless).should render('<r:unless_children>true</r:unless_children>').as('true') end describe "<r:children:each>" do it "should iterate through the children of the current page" do page(:parent) page.should render('<r:children:each><r:title /> </r:children:each>').as('Child Child 2 Child 3 ') page.should render('<r:children:each><r:page><r:slug />/<r:child:slug /> </r:page></r:children:each>').as('parent/child parent/child-2 parent/child-3 ') page(:assorted).should render(<API key>).as('a b c d e f g h i j ') end it 'should not list draft pages' do page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ') end it 'should include draft pages with status="all"' do page.should render('<r:children:each status="all" by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ') end it "should include draft pages by default on the dev host" do page.should render('<r:children:each by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ').on('dev.site.com') end it 'should not list draft pages on dev.site.com when Radiant::Config["dev.host"] is set to something else' do Radiant::Config['dev.host'] = 'preview.site.com' page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ').on('dev.site.com') end it 'should paginate results when "paginated" attribute is "true"' do page.<API key> = {:page => 1, :per_page => 10} page.should render('<r:children:each paginated="true" per_page="10"><r:slug /> </r:children:each>').as('a b c d e f g h i j ') page.should render('<r:children:each paginated="true" per_page="2"><r:slug /> </r:children:each>').matching(/div class="pagination"/) end it 'should error with invalid "limit" attribute' do message = "`limit' attribute of `each' tag must be a positive number between 1 and 4 digits" page.should render(<API key>(%{limit="a"})).with_error(message) page.should render(<API key>(%{limit="-10"})).with_error(message) page.should render(<API key>(%{limit="50000"})).with_error(message) end it 'should error with invalid "offset" attribute' do message = "`offset' attribute of `each' tag must be a positive number between 1 and 4 digits" page.should render(<API key>(%{offset="a"})).with_error(message) page.should render(<API key>(%{offset="-10"})).with_error(message) page.should render(<API key>(%{offset="50000"})).with_error(message) end it 'should error with invalid "by" attribute' do message = "`by' attribute of `each' tag must be set to a valid field name" page.should render(<API key>(%{by="non-existant-field"})).with_error(message) end it 'should error with invalid "order" attribute' do message = %{`order' attribute of `each' tag must be set to either "asc" or "desc"} page.should render(<API key>(%{order="asdf"})).with_error(message) end it "should limit the number of children when given a 'limit' attribute" do page.should render(<API key>(%{limit="5"})).as('a b c d e ') end it "should limit and offset the children when given 'limit' and 'offset' attributes" do page.should render(<API key>(%{offset="3" limit="5"})).as('d e f g h ') end it "should change the sort order when given an 'order' attribute" do page.should render(<API key>(%{order="desc"})).as('j i h g f e d c b a ') end it "should sort by the 'by' attribute" do page.should render(<API key>(%{by="breadcrumb"})).as('f e d c b a j i h g ') end it "should sort by the 'by' attribute according to the 'order' attribute" do page.should render(<API key>(%{by="breadcrumb" order="desc"})).as('g h i j a b c d e f ') end describe 'with "status" attribute' do it "set to 'all' should list all children" do page.should render(<API key>(%{status="all"})).as("a b c d e f g h i j draft ") end it "set to 'draft' should list only children with 'draft' status" do page.should render(<API key>(%{status="draft"})).as('draft ') end it "set to 'published' should list only children with 'draft' status" do page.should render(<API key>(%{status="published"})).as('a b c d e f g h i j ') end it "set to an invalid status should render an error" do page.should render(<API key>(%{status="askdf"})).with_error("`status' attribute of `each' tag must be set to a valid status") end end end describe "<r:children:each:if_first>" do it "should render for the first child" do tags = '<r:children:each><r:if_first>FIRST:</r:if_first><r:slug /> </r:children:each>' expected = "FIRST:article article-2 article-3 article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:unless_first>" do it "should render for all but the first child" do tags = '<r:children:each><r:unless_first>NOT-FIRST:</r:unless_first><r:slug /> </r:children:each>' expected = "article NOT-FIRST:article-2 NOT-FIRST:article-3 NOT-FIRST:article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:if_last>" do it "should render for the last child" do tags = '<r:children:each><r:if_last>LAST:</r:if_last><r:slug /> </r:children:each>' expected = "article article-2 article-3 LAST:article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:unless_last>" do it "should render for all but the last child" do tags = '<r:children:each><r:unless_last>NOT-LAST:</r:unless_last><r:slug /> </r:children:each>' expected = "NOT-LAST:article NOT-LAST:article-2 NOT-LAST:article-3 article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:header>" do it "should render the header when it changes" do tags = '<r:children:each><r:header>[<r:date format="%b/%y" />] </r:header><r:slug /> </r:children:each>' expected = "[Dec/00] article [Feb/01] article-2 article-3 [Mar/01] article-4 " page(:news).should render(tags).as(expected) end it 'with "name" attribute should maintain a separate header' do tags = %{<r:children:each><r:header name="year">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>} expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 " page(:news).should render(tags).as(expected) end it 'with "restart" attribute set to one name should restart that header' do tags = %{<r:children:each><r:header name="year" restart="month">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>} expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 " page(:news).should render(tags).as(expected) end it 'with "restart" attribute set to two names should restart both headers' do tags = %{<r:children:each><r:header name="year" restart="month;day">[<r:date format='%Y' />] </r:header><r:header name="month" restart="day">(<r:date format="%b" />) </r:header><r:header name="day"><<r:date format='%d' />> </r:header><r:slug /> </r:children:each>} expected = "[2000] (Dec) <01> article [2001] (Feb) <09> article-2 <24> article-3 (Mar) <06> article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:count>" do it 'should render the number of children of the current page' do page(:parent).should render('<r:children:count />').as('3') end it "should accept the same scoping conditions as <r:children:each>" do page.should render('<r:children:count />').as('10') page.should render('<r:children:count status="all" />').as('11') page.should render('<r:children:count status="draft" />').as('1') page.should render('<r:children:count status="hidden" />').as('0') end end describe "<r:children:first>" do it 'should render its contents in the context of the first child page' do page(:parent).should render('<r:children:first:title />').as('Child') end it 'should accept the same scoping attributes as <r:children:each>' do page.should render(<API key>).as('a') page.should render(<API key>(%{limit="5"})).as('a') page.should render(<API key>(%{offset="3" limit="5"})).as('d') page.should render(<API key>(%{order="desc"})).as('j') page.should render(<API key>(%{by="breadcrumb"})).as('f') page.should render(<API key>(%{by="breadcrumb" order="desc"})).as('g') end it "should render nothing when no children exist" do page(:first).should render('<r:children:first:title />').as('') end end describe "<r:children:last>" do it 'should render its contents in the context of the last child page' do page(:parent).should render('<r:children:last:title />').as('Child 3') end it 'should accept the same scoping attributes as <r:children:each>' do page.should render(<API key>).as('j') page.should render(<API key>(%{limit="5"})).as('e') page.should render(<API key>(%{offset="3" limit="5"})).as('h') page.should render(<API key>(%{order="desc"})).as('a') page.should render(<API key>(%{by="breadcrumb"})).as('g') page.should render(<API key>(%{by="breadcrumb" order="desc"})).as('f') end it "should render nothing when no children exist" do page(:first).should render('<r:children:last:title />').as('') end end describe "<r:content>" do it "should render the 'body' part by default" do page.should render('<r:content />').as('Assorted body.') end it "with 'part' attribute should render the specified part" do page(:home).should render('<r:content part="extended" />').as("Just a test.") end it "should prevent simple recursion" do page(:recursive_parts).should render('<r:content />').with_error("Recursion error: already rendering the `body' part.") end it "should prevent deep recursion" do page(:recursive_parts).should render('<r:content part="one"/>').with_error("Recursion error: already rendering the `one' part.") page(:recursive_parts).should render('<r:content part="two"/>').with_error("Recursion error: already rendering the `two' part.") end it "should allow repetition" do page(:recursive_parts).should render('<r:content part="repeat"/>').as('xx') end it "should not prevent rendering a part more than once in sequence" do page(:home).should render('<r:content /><r:content />').as('Hello world!Hello world!') end describe "with inherit attribute" do it "missing or set to 'false' should render the current page's part" do page.should render('<r:content part="sidebar" />').as('') page.should render('<r:content part="sidebar" inherit="false" />').as('') end describe "set to 'true'" do it "should render an ancestor's part" do page.should render('<r:content part="sidebar" inherit="true" />').as('Assorted sidebar.') end it "should render nothing when no ancestor has the part" do page.should render('<r:content part="<API key>" inherit="true" />').as('') end describe "and contextual attribute" do it "set to 'true' should render the part in the context of the current page" do page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Parent sidebar.') page(:child).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Child sidebar.') page(:grandchild).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Grandchild sidebar.') end it "set to 'false' should render the part in the context of its containing page" do page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="false" />').as('Home sidebar.') end it "should maintain the global page" do page(:first) page.should render('<r:content part="titles" inherit="true" contextual="true"/>').as('First First') page.should render('<r:content part="titles" inherit="true" contextual="false"/>').as('Home First') end end end it "set to an erroneous value should render an error" do page.should render('<r:content part="sidebar" inherit="weird value" />').with_error(%{`inherit' attribute of `content' tag must be set to either "true" or "false"}) end it "should render parts with respect to the current contextual page" do expected = "Child body. Child 2 body. Child 3 body. " page(:parent).should render('<r:children:each><r:content /> </r:children:each>').as(expected) end end end describe "<r:if_content>" do it "without 'part' attribute should render the contained block if the 'body' part exists" do page.should render('<r:if_content>true</r:if_content>').as('true') end it "should render the contained block if the specified part exists" do page.should render('<r:if_content part="body">true</r:if_content>').as('true') end it "should not render the contained block if the specified part does not exist" do page.should render('<r:if_content part="asdf">true</r:if_content>').as('') end describe "with more than one part given (separated by comma)" do it "should render the contained block only if all specified parts exist" do page(:home).should render('<r:if_content part="body, extended">true</r:if_content>').as('true') end it "should not render the contained block if at least one of the specified parts does not exist" do page(:home).should render('<r:if_content part="body, madeup">true</r:if_content>').as('') end describe "with inherit attribute set to 'true'" do it 'should render the contained block if the current or ancestor pages have the specified parts' do page(:guests).should render('<r:if_content part="favors, extended" inherit="true">true</r:if_content>').as('true') end it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do page(:guests).should render('<r:if_content part="favors, madeup" inherit="true">true</r:if_content>').as('') end describe "with find attribute set to 'any'" do it 'should render the contained block if the current or ancestor pages have any of the specified parts' do page(:guests).should render('<r:if_content part="favors, madeup" inherit="true" find="any">true</r:if_content>').as('true') end it 'should still render the contained block if first of the specified parts has not been found' do page(:guests).should render('<r:if_content part="madeup, favors" inherit="true" find="any">true</r:if_content>').as('true') end end end describe "with inherit attribute set to 'false'" do it 'should render the contained block if the current page has the specified parts' do page(:guests).should render('<r:if_content part="favors, games" inherit="false">true</r:if_content>').as('') end it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do page(:guests).should render('<r:if_content part="favors, madeup" inherit="false">true</r:if_content>').as('') end end describe "with the 'find' attribute set to 'any'" do it "should render the contained block if any of the specified parts exist" do page.should render('<r:if_content part="body, asdf" find="any">true</r:if_content>').as('true') end end describe "with the 'find' attribute set to 'all'" do it "should render the contained block if all of the specified parts exist" do page(:home).should render('<r:if_content part="body, sidebar" find="all">true</r:if_content>').as('true') end it "should not render the contained block if all of the specified parts do not exist" do page.should render('<r:if_content part="asdf, madeup" find="all">true</r:if_content>').as('') end end end end describe "<r:unless_content>" do describe "with inherit attribute set to 'true'" do it 'should not render the contained block if the current or ancestor pages have the specified parts' do page(:guests).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('') end it 'should render the contained block if the current or ancestor pages do not have the specified parts' do page(:guests).should render('<r:unless_content part="madeup, imaginary" inherit="true">true</r:unless_content>').as('true') end it "should not render the contained block if the specified part does not exist but does exist on an ancestor" do page.should render('<r:unless_content part="sidebar" inherit="true">false</r:unless_content>').as('') end describe "with find attribute set to 'any'" do it 'should not render the contained block if the current or ancestor pages have any of the specified parts' do page(:guests).should render('<r:unless_content part="favors, madeup" inherit="true" find="any">true</r:unless_content>').as('') end it 'should still not render the contained block if first of the specified parts has not been found' do page(:guests).should render('<r:unless_content part="madeup, favors" inherit="true" find="any">true</r:unless_content>').as('') end end end it "without 'part' attribute should not render the contained block if the 'body' part exists" do page.should render('<r:unless_content>false</r:unless_content>').as('') end it "should not render the contained block if the specified part exists" do page.should render('<r:unless_content part="body">false</r:unless_content>').as('') end it "should render the contained block if the specified part does not exist" do page.should render('<r:unless_content part="asdf">false</r:unless_content>').as('false') end it "should render the contained block if the specified part does not exist but does exist on an ancestor" do page.should render('<r:unless_content part="sidebar">false</r:unless_content>').as('false') end describe "with more than one part given (separated by comma)" do it "should not render the contained block if all of the specified parts exist" do page(:home).should render('<r:unless_content part="body, extended">true</r:unless_content>').as('') end it "should render the contained block if at least one of the specified parts exists" do page(:home).should render('<r:unless_content part="body, madeup">true</r:unless_content>').as('true') end describe "with the 'inherit' attribute set to 'true'" do it "should render the contained block if the current or ancestor pages have none of the specified parts" do page.should render('<r:unless_content part="imaginary, madeup" inherit="true">true</r:unless_content>').as('true') end it "should not render the contained block if all of the specified parts are present on the current or ancestor pages" do page(:party).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('') end end describe "with the 'find' attribute set to 'all'" do it "should not render the contained block if all of the specified parts exist" do page(:home).should render('<r:unless_content part="body, sidebar" find="all">true</r:unless_content>').as('') end it "should render the contained block unless all of the specified parts exist" do page.should render('<r:unless_content part="body, madeup" find="all">true</r:unless_content>').as('true') end end describe "with the 'find' attribute set to 'any'" do it "should not render the contained block if any of the specified parts exist" do page.should render('<r:unless_content part="body, madeup" find="any">true</r:unless_content>').as('') end end end end describe "<r:author>" do it "should render the author of the current page" do page.should render('<r:author />').as('Admin') end it "should render nothing when the page has no author" do page(:no_user).should render('<r:author />').as('') end end describe "<r:gravatar>" do it "should render the Gravatar URL of author of the current page" do page.should render('<r:gravatar />').as('http: end it "should render the Gravatar URL of the name user" do page.should render('<r:gravatar name="Admin" />').as('http: end it "should render the default avatar when the user has not set an email address" do page.should render('<r:gravatar name="Designer" />').as('http://testhost.tld/images/admin/avatar_32x32.png') end it "should render the specified size" do page.should render('<r:gravatar name="Designer" size="96px" />').as('http://testhost.tld/images/admin/avatar_96x96.png') end it "should render the specified rating" do page.should render('<r:gravatar rating="X" />').as('http: end end describe "<r:date>" do before :each do page(:dated) end it "should render the published date of the page" do page.should render('<r:date />').as('Wednesday, January 11, 2006') end it "should format the published date according to the 'format' attribute" do page.should render('<r:date format="%d %b %Y" />').as('11 Jan 2006') end describe "with 'for' attribute" do it "set to 'now' should render the current date in the current Time.zone" do page.should render('<r:date for="now" />').as(Time.zone.now.strftime("%A, %B %d, %Y")) end it "set to 'created_at' should render the creation date" do page.should render('<r:date for="created_at" />').as('Tuesday, January 10, 2006') end it "set to 'updated_at' should render the update date" do page.should render('<r:date for="updated_at" />').as('Thursday, January 12, 2006') end it "set to 'published_at' should render the publish date" do page.should render('<r:date for="published_at" />').as('Wednesday, January 11, 2006') end it "set to an invalid attribute should render an error" do page.should render('<r:date for="blah" />').with_error("Invalid value for 'for' attribute.") end end it "should use the currently set timezone" do Time.zone = "Tokyo" format = "%H:%m" expected = page.published_at.in_time_zone(ActiveSupport::TimeZone['Tokyo']).strftime(format) page.should render(%Q(<r:date format="#{format}" />) ).as(expected) end end describe "<r:link>" do it "should render a link to the current page" do page.should render('<r:link />').as('<a href="/assorted/">Assorted</a>') end it "should render its contents as the text of the link" do page.should render('<r:link>Test</r:link>').as('<a href="/assorted/">Test</a>') end it "should pass HTML attributes to the <a> tag" do expected = '<a href="/assorted/" class="test" id="assorted">Assorted</a>' page.should render('<r:link class="test" id="assorted" />').as(expected) end it "should add the anchor attribute to the link as a URL anchor" do page.should render('<r:link anchor="test">Test</r:link>').as('<a href="/assorted/#test">Test</a>') end it "should render a link for the current contextual page" do expected = %{<a href="/parent/child/">Child</a> <a href="/parent/child-2/">Child 2</a> <a href="/parent/child-3/">Child 3</a> } page(:parent).should render('<r:children:each><r:link /> </r:children:each>' ).as(expected) end it "should scope the link within the relative URL root" do page(:assorted).should render('<r:link />').with_relative_root('/foo').as('<a href="/foo/assorted/">Assorted</a>') end end describe "<r:snippet>" do it "should render the contents of the specified snippet" do page.should render('<r:snippet name="first" />').as('test') end it "should render an error when the snippet does not exist" do page.should render('<r:snippet name="non-existant" />').with_error('snippet not found') end it "should render an error when not given a 'name' attribute" do page.should render('<r:snippet />').with_error("`snippet' tag must contain `name' attribute") end it "should filter the snippet with its assigned filter" do page.should render('<r:page><r:snippet name="markdown" /></r:page>').matching(%r{<p><strong>markdown</strong></p>}) end it "should maintain the global page inside the snippet" do page(:parent).should render('<r:snippet name="global_page_cascade" />').as("#{@page.title} " * @page.children.count) end it "should maintain the global page when the snippet renders recursively" do page(:child).should render('<r:snippet name="recursive" />').as("Great <API key>") end it "should render the specified snippet when called as an empty double-tag" do page.should render('<r:snippet name="first"></r:snippet>').as('test') end it "should capture contents of a double tag, substituting for <r:yield/> in snippet" do page.should render('<r:snippet name="yielding">inner</r:snippet>'). as('Before...inner...and after') end it "should do nothing with contents of double tag when snippet doesn't yield" do page.should render('<r:snippet name="first">content disappears!</r:snippet>'). as('test') end it "should render nested yielding snippets" do page.should render('<r:snippet name="div_wrap"><r:snippet name="yielding">Hello, World!</r:snippet></r:snippet>'). as('<div>Before...Hello, World!...and after</div>') end it "should render double-tag snippets called from within a snippet" do page.should render('<r:snippet name="nested_yields">the content</r:snippet>'). as('<snippet name="div_wrap">above the content below</snippet>') end it "should render contents each time yield is called" do page.should render('<r:snippet name="yielding_often">French</r:snippet>'). as('French is Frencher than French') end end it "should do nothing when called from page body" do page.should render('<r:yield/>').as("") end it '<r:random> should render a randomly selected contained <r:option>' do page.should render("<r:random> <r:option>1</r:option> <r:option>2</r:option> <r:option>3</r:option> </r:random>").matching(/^(1|2|3)$/) end it '<r:random> should render a randomly selected, dynamically set <r:option>' do page(:parent).should render("<r:random:children:each:option:title />").matching(/^(Child|Child\ 2|Child\ 3)$/) end it '<r:comment> should render nothing it contains' do page.should render('just a <r:comment>small </r:comment>test').as('just a test') end describe "<r:navigation>" do it "should render the nested <r:normal> tag by default" do tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/"> <r:normal><r:title /></r:normal> </r:navigation>} expected = %{Home Assorted Parent} page.should render(tags).as(expected) end it "should render the nested <r:selected> tag for URLs that match the current page" do tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/ | Radius: /radius/"> <r:normal><r:title /></r:normal> <r:selected><strong><r:title/></strong></r:selected> </r:navigation>} expected = %{<strong>Home</strong> Assorted <strong>Parent</strong> Radius} page(:parent).should render(tags).as(expected) end it "should render the nested <r:here> tag for URLs that exactly match the current page" do tags = %{<r:navigation urls="Home: Boy: / | Assorted: /assorted/ | Parent: /parent/"> <r:normal><a href="<r:url />"><r:title /></a></r:normal> <r:here><strong><r:title /></strong></r:here> <r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected> <r:between> | </r:between> </r:navigation>} expected = %{<strong><a href="/">Home: Boy</a></strong> | <strong>Assorted</strong> | <a href="/parent/">Parent</a>} page.should render(tags).as(expected) end it "should render the nested <r:between> tag between each link" do tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/"> <r:normal><r:title /></r:normal> <r:between> :: </r:between> </r:navigation>} expected = %{Home :: Assorted :: Parent} page.should render(tags).as(expected) end it 'without urls should render nothing' do page.should render(%{<r:navigation><r:normal /></r:navigation>}).as('') end it 'without a nested <r:normal> tag should render an error' do page.should render(%{<r:navigation urls="something:here"></r:navigation>}).with_error( "`navigation' tag must include a `normal' tag") end it 'with urls without trailing slashes should match corresponding pages' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><r:title /></r:normal> <r:here><strong><r:title /></strong></r:here> </r:navigation>} expected = %{Home <strong>Assorted</strong> Parent Radius} page.should render(tags).as(expected) end it 'should prune empty blocks' do tags = %{<r:navigation urls="Home: Boy: / | Archives: /archive/ | Radius: /radius/ | Docs: /documentation/"> <r:normal><a href="<r:url />"><r:title /></a></r:normal> <r:here></r:here> <r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected> <r:between> | </r:between> </r:navigation>} expected = %{<strong><a href="/">Home: Boy</a></strong> | <a href="/archive/">Archives</a> | <a href="/documentation/">Docs</a>} page(:radius).should render(tags).as(expected) end it 'should render text under <r:if_first> and <r:if_last> only on the first and last item, respectively' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><r:if_first>(</r:if_first><a href="<r:url />"><r:title /></a><r:if_last>)</r:if_last></r:normal> <r:here><r:if_first>(</r:if_first><r:title /><r:if_last>)</r:if_last></r:here> <r:selected><r:if_first>(</r:if_first><strong><a href="<r:url />"><r:title /></a></strong><r:if_last>)</r:if_last></r:selected> </r:navigation>} expected = %{(<strong><a href=\"/\">Home</a></strong> <a href=\"/assorted\">Assorted</a> <a href=\"/parent\">Parent</a> Radius)} page(:radius).should render(tags).as(expected) end it 'should render text under <r:unless_first> on every item but the first' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><r:unless_first>&gt; </r:unless_first><a href="<r:url />"><r:title /></a></r:normal> <r:here><r:unless_first>&gt; </r:unless_first><r:title /></r:here> <r:selected><r:unless_first>&gt; </r:unless_first><strong><a href="<r:url />"><r:title /></a></strong></r:selected> </r:navigation>} expected = %{<strong><a href=\"/\">Home</a></strong> &gt; <a href=\"/assorted\">Assorted</a> &gt; <a href=\"/parent\">Parent</a> &gt; Radius} page(:radius).should render(tags).as(expected) end it 'should render text under <r:unless_last> on every item but the last' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><a href="<r:url />"><r:title /></a><r:unless_last> &gt;</r:unless_last></r:normal> <r:here><r:title /><r:unless_last> &gt;</r:unless_last></r:here> <r:selected><strong><a href="<r:url />"><r:title /></a></strong><r:unless_last> &gt;</r:unless_last></r:selected> </r:navigation>} expected = %{<strong><a href=\"/\">Home</a></strong> &gt; <a href=\"/assorted\">Assorted</a> &gt; <a href=\"/parent\">Parent</a> &gt; Radius} page(:radius).should render(tags).as(expected) end end describe "<r:find>" do it "should change the local page to the page specified in the 'url' attribute" do page.should render(%{<r:find url="/parent/child/"><r:title /></r:find>}).as('Child') end it "should render an error without the 'url' attribute" do page.should render(%{<r:find />}).with_error("`find' tag must contain `url' attribute") end it "should render nothing when the 'url' attribute does not point to a page" do page.should render(%{<r:find url="/asdfsdf/"><r:title /></r:find>}).as('') end it "should render nothing when the 'url' attribute does not point to a page and a custom 404 page exists" do page.should render(%{<r:find url="/gallery/asdfsdf/"><r:title /></r:find>}).as('') end it "should scope contained tags to the found page" do page.should render(%{<r:find url="/parent/"><r:children:each><r:slug /> </r:children:each></r:find>}).as('child child-2 child-3 ') end it "should accept a path relative to the current page" do page(:great_grandchild).should render(%{<r:find url="../../../child-2"><r:title/></r:find>}).as("Child 2") end end it '<r:escape_html> should escape HTML-related characters into entities' do page.should render('<r:escape_html><strong>a bold move</strong></r:escape_html>').as('&lt;strong&gt;a bold move&lt;/strong&gt;') end it '<r:rfc1123_date> should render an RFC1123-compatible date' do page(:dated).should render('<r:rfc1123_date />').as('Wed, 11 Jan 2006 00:00:00 GMT') end describe "<r:breadcrumbs>" do it "should render a series of breadcrumb links separated by &gt;" do expected = %{<a href="/">Home</a> &gt; <a href="/parent/">Parent</a> &gt; <a href="/parent/child/">Child</a> &gt; <a href="/parent/child/grandchild/">Grandchild</a> &gt; Great Grandchild} page(:great_grandchild).should render('<r:breadcrumbs />').as(expected) end it "with a 'separator' attribute should use the separator instead of &gt;" do expected = %{<a href="/">Home</a> :: Parent} page(:parent).should render('<r:breadcrumbs separator=" :: " />').as(expected) end it "with a 'nolinks' attribute set to 'true' should not render links" do expected = %{Home &gt; Parent} page(:parent).should render('<r:breadcrumbs nolinks="true" />').as(expected) end it "with a relative URL root should scope links to the relative root" do expected = '<a href="/foo/">Home</a> &gt; Assorted' page(:assorted).should render('<r:breadcrumbs />').with_relative_root('/foo').as(expected) end end describe "<r:if_url>" do describe "with 'matches' attribute" do it "should render the contained block if the page URL matches" do page.should render('<r:if_url matches="a.sorted/$">true</r:if_url>').as('true') end it "should not render the contained block if the page URL does not match" do page.should render('<r:if_url matches="fancypants">true</r:if_url>').as('') end it "set to a malformatted regexp should render an error" do page.should render('<r:if_url matches="as(sorted/$">true</r:if_url>').with_error("Malformed regular expression in `matches' argument of `if_url' tag: unmatched (: /as(sorted\\/$/") end it "without 'ignore_case' attribute should ignore case by default" do page.should render('<r:if_url matches="asSorted/$">true</r:if_url>').as('true') end describe "with 'ignore_case' attribute" do it "set to 'true' should use a case-insensitive match" do page.should render('<r:if_url matches="asSorted/$" ignore_case="true">true</r:if_url>').as('true') end it "set to 'false' should use a case-sensitive match" do page.should render('<r:if_url matches="asSorted/$" ignore_case="false">true</r:if_url>').as('') end end end it "with no attributes should render an error" do page.should render('<r:if_url>test</r:if_url>').with_error("`if_url' tag must contain a `matches' attribute.") end end describe "<r:unless_url>" do describe "with 'matches' attribute" do it "should not render the contained block if the page URL matches" do page.should render('<r:unless_url matches="a.sorted/$">true</r:unless_url>').as('') end it "should render the contained block if the page URL does not match" do page.should render('<r:unless_url matches="fancypants">true</r:unless_url>').as('true') end it "set to a malformatted regexp should render an error" do page.should render('<r:unless_url matches="as(sorted/$">true</r:unless_url>').with_error("Malformed regular expression in `matches' argument of `unless_url' tag: unmatched (: /as(sorted\\/$/") end it "without 'ignore_case' attribute should ignore case by default" do page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('') end describe "with 'ignore_case' attribute" do it "set to 'true' should use a case-insensitive match" do page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('') end it "set to 'false' should use a case-sensitive match" do page.should render('<r:unless_url matches="asSorted/$" ignore_case="false">true</r:unless_url>').as('true') end end end it "with no attributes should render an error" do page.should render('<r:unless_url>test</r:unless_url>').with_error("`unless_url' tag must contain a `matches' attribute.") end end describe "<r:cycle>" do it "should render passed values in succession" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second') end it "should return to the beginning of the cycle when reaching the end" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second first') end it "should use a default cycle name of 'cycle'" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" name="cycle" />').as('first second') end it "should maintain separate cycle counters" do page.should render('<r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" /> <r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" />').as('first one second two') end it "should reset the counter" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" reset="true"/>').as('first first') end it "should require the values attribute" do page.should render('<r:cycle />').with_error("`cycle' tag must contain a `values' attribute.") end end describe "<r:if_dev>" do it "should render the contained block when on the dev site" do page.should render('-<r:if_dev>dev</r:if_dev>-').as('-dev-').on('dev.site.com') end it "should not render the contained block when not on the dev site" do page.should render('-<r:if_dev>dev</r:if_dev>-').as(' end describe "on an included page" do it "should render the contained block when on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('-dev-').on('dev.site.com') end it "should not render the contained block when not on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as(' end end end describe "<r:unless_dev>" do it "should not render the contained block when not on the dev site" do page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('--').on('dev.site.com') end it "should render the contained block when not on the dev site" do page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('-not dev-') end describe "on an included page" do it "should not render the contained block when not on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('--').on('dev.site.com') end it "should render the contained block when not on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('-not dev-') end end end describe "<r:status>" do it "should render the status of the current page" do status_tag = "<r:status/>" page(:a).should render(status_tag).as("Published") page(:hidden).should render(status_tag).as("Hidden") page(:draft).should render(status_tag).as("Draft") end describe "with the downcase attribute set to 'true'" do it "should render the lowercased status of the current page" do status_tag_lc = "<r:status downcase='true'/>" page(:a).should render(status_tag_lc).as("published") page(:hidden).should render(status_tag_lc).as("hidden") page(:draft).should render(status_tag_lc).as("draft") end end end describe "<r:if_ancestor_or_self>" do it "should render the tag's content when the current page is an ancestor of tag.locals.page" do page(:radius).should render(%{<r:find url="/"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('true') end it "should not render the tag's content when current page is not an ancestor of tag.locals.page" do page(:parent).should render(%{<r:find url="/radius"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('') end end describe "<r:<API key>>" do it "should render the tag's content when the current page is not an ancestor of tag.locals.page" do page(:parent).should render(%{<r:find url="/radius"><r:<API key>>true</r:<API key>></r:find>}).as('true') end it "should not render the tag's content when current page is an ancestor of tag.locals.page" do page(:radius).should render(%{<r:find url="/"><r:<API key>>true</r:<API key>></r:find>}).as('') end end describe "<r:if_self>" do it "should render the tag's content when the current page is the same as the local contextual page" do page(:home).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('true') end it "should not render the tag's content when the current page is not the same as the local contextual page" do page(:radius).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('') end end describe "<r:unless_self>" do it "should render the tag's content when the current page is not the same as the local contextual page" do page(:radius).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('true') end it "should not render the tag's content when the current page is the same as the local contextual page" do page(:home).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('') end end describe "<r:meta>" do it "should render <meta> tags for the description and keywords" do page(:home).should render('<r:meta/>').as(%{<meta name="description" content="The homepage" /><meta name="keywords" content="Home, Page" />}) end it "should render <meta> tags with escaped values for the description and keywords" do page.should render('<r:meta/>').as(%{<meta name="description" content="sweet &amp; harmonious biscuits" /><meta name="keywords" content="sweet &amp; harmonious biscuits" />}) end describe "with 'tag' attribute set to 'false'" do it "should render the contents of the description and keywords" do page(:home).should render('<r:meta tag="false" />').as(%{The homepageHome, Page}) end it "should escape the contents of the description and keywords" do page.should render('<r:meta tag="false" />').as("sweet &amp; harmonious biscuitssweet &amp; harmonious biscuits") end end end describe "<r:meta:description>" do it "should render a <meta> tag for the description" do page(:home).should render('<r:meta:description/>').as(%{<meta name="description" content="The homepage" />}) end it "should render a <meta> tag with escaped value for the description" do page.should render('<r:meta:description />').as(%{<meta name="description" content="sweet &amp; harmonious biscuits" />}) end describe "with 'tag' attribute set to 'false'" do it "should render the contents of the description" do page(:home).should render('<r:meta:description tag="false" />').as(%{The homepage}) end it "should escape the contents of the description" do page.should render('<r:meta:description tag="false" />').as("sweet &amp; harmonious biscuits") end end end describe "<r:meta:keywords>" do it "should render a <meta> tag for the keywords" do page(:home).should render('<r:meta:keywords/>').as(%{<meta name="keywords" content="Home, Page" />}) end it "should render a <meta> tag with escaped value for the keywords" do page.should render('<r:meta:keywords />').as(%{<meta name="keywords" content="sweet &amp; harmonious biscuits" />}) end describe "with 'tag' attribute set to 'false'" do it "should render the contents of the keywords" do page(:home).should render('<r:meta:keywords tag="false" />').as(%{Home, Page}) end it "should escape the contents of the keywords" do page.should render('<r:meta:keywords tag="false" />').as("sweet &amp; harmonious biscuits") end end end private def page(symbol = nil) if symbol.nil? @page ||= pages(:assorted) else @page = pages(symbol) end end def <API key>(attr = nil) attr = ' ' + attr unless attr.nil? "<r:children:each#{attr}><r:slug /> </r:children:each>" end def <API key>(attr = nil) attr = ' ' + attr unless attr.nil? "<r:children:first#{attr}><r:slug /></r:children:first>" end def <API key>(attr = nil) attr = ' ' + attr unless attr.nil? "<r:children:last#{attr}><r:slug /></r:children:last>" end def <API key>(page) page.children.select(&:published?).reject(&:virtual) end end
class CreateMappableMaps < ActiveRecord::Migration def change create_table :mappable_maps do |t| t.string :subject t.string :attr t.string :from t.string :to t.timestamps end end end
<!DOCTYPE HTML PUBLIC "- <html> <head> <META http-equiv="Content-Type" content="text/html; charset=ASCII"> <link rel="stylesheet" href="style.css" type="text/css"> <title>MXML Only Components - Adobe Flex 2 Language Reference</title> </head> <body class="classFrameContent"> <h3>MXML Only Components</h3> <a href="mxml/binding.html" target="classFrame">&lt;mx:Binding&gt;</a> <br> <a href="mxml/component.html" target="classFrame">&lt;mx:Component&gt;</a> <br> <a href="mxml/metadata.html" target="classFrame">&lt;mx:Metadata&gt;</a> <br> <a href="mxml/model.html" target="classFrame">&lt;mx:Model&gt;</a> <br> <a href="mxml/script.html" target="classFrame">&lt;mx:Script&gt;</a> <br> <a href="mxml/style.html" target="classFrame">&lt;mx:Style&gt;</a> <br> <a href="mxml/xml.html" target="classFrame">&lt;mx:XML&gt;</a> <br> <a href="mxml/xmlList.html" target="classFrame">&lt;mx:XMLList&gt;</a> <br> </body> </html>
LinkLuaModifier("<API key>", "heroes/cleric/cleric_modifiers.lua", <API key>) LinkLuaModifier("<API key>", "heroes/cleric/cleric_modifiers.lua", <API key>) LinkLuaModifier("<API key>", "heroes/cleric/cleric_modifiers.lua", <API key>) LinkLuaModifier("<API key>", "heroes/cleric/cleric_modifiers.lua", <API key>) function ClericMeteorShower(keys) <API key>(keys.caster) local iMeteorCount = keys.ability:GetSpecialValueFor("meteor_count") local vTarget= keys.target_points[1] local fMeteorRadius = keys.ability:GetSpecialValueFor("meteor_radius") AddFOWViewer(keys.caster:GetTeamNumber(), vTarget, 500, 3, true) local fCastRadius = keys.ability:GetSpecialValueFor("cast_radius") local iDamage if keys.caster:FindAbilityByName("<API key>") then iDamage = keys.ability:GetSpecialValueFor("damage")+keys.caster:FindAbilityByName("<API key>"):GetSpecialValueFor("value") else iDamage = keys.ability:GetSpecialValueFor("damage") end local fStunDuration if keys.caster:FindAbilityByName("<API key>") then fStunDuration = keys.ability:GetSpecialValueFor("stun_duration")+keys.caster:FindAbilityByName("<API key>"):GetSpecialValueFor("value") else fStunDuration = keys.ability:GetSpecialValueFor("stun_duration") end for i = 1, iMeteorCount do Timers:CreateTimer(0.2*(i-1), function () local vRelative = Vector(RandomFloat(-fCastRadius, fCastRadius), RandomFloat(-fCastRadius, fCastRadius), 0) while vRelative:Length2D() > fCastRadius do vRelative = Vector(RandomFloat(-fCastRadius, fCastRadius), RandomFloat(-fCastRadius, fCastRadius), 0) end local iParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_invoker/<API key>.vpcf", <API key>, PlayerResource:GetPlayer(0):GetAssignedHero()) ParticleManager:SetParticleControl(iParticle, 0, vTarget+vRelative+Vector(0,0,2000)) ParticleManager:SetParticleControl(iParticle, 1, vTarget+vRelative+Vector(0,0,-2250)) ParticleManager:SetParticleControl(iParticle, 2, Vector(0.7,0,0)) local hThinker = <API key>(keys.caster, keys.ability, "modifier_stunned", {Duration = 1}, vTarget+vRelative+Vector(0,0,2000), keys.caster:GetTeamNumber(), false) hThinker:EmitSound("Hero_Invoker.ChaosMeteor.Cast") hThinker:EmitSound("Hero_Invoker.ChaosMeteor.Loop") Timers:CreateTimer(0.6,function () <API key>("Hero_Invoker.ChaosMeteor.Impact", vTarget+vRelative) hThinker:StopSound("Hero_Invoker.ChaosMeteor.Loop") GridNav:<API key>(vTarget+vRelative, fMeteorRadius, true) local tTargets = FindUnitsInRadius(keys.caster:GetTeamNumber(), vTarget+vRelative, nil, fMeteorRadius, <API key>, <API key>+<API key>, <API key>, FIND_ANY_ORDER, false) local damageTable = { damage = iDamage, attacker = keys.caster, damage_type = DAMAGE_TYPE_MAGICAL, ability = keys.ability } for k, v in ipairs(tTargets) do damageTable.victim = v ApplyDamage(damageTable) v:AddNewModifier(keys.caster, keys.ability, "modifier_stunned", {Duration = fStunDuration*<API key>(v)}) end end) end) end end cleric_berserk = class({}) function cleric_berserk:GetBehavior() if not self.bSpecial2 then self.hSpecial2 = Entities:First() while self.hSpecial2 and (self.hSpecial2:GetName() ~= "<API key>" or self.hSpecial2:GetCaster() ~= self:GetCaster()) do self.hSpecial2 = Entities:Next(self.hSpecial2) end self.bSpecial2 = true end if self.hSpecial2 and self.hSpecial2:GetLevel() > 0 then return <API key>+<API key> else return <API key> end end function cleric_berserk:GetAOERadius() if self.hSpecial2 then return self.hSpecial2:GetSpecialValueFor("value") else return 0 end end function cleric_berserk:OnSpellStart() if self.hSpecial2 and self.hSpecial2:GetLevel() > 0 then local hCaster = self:GetCaster() local tTargets = FindUnitsInRadius(hCaster:GetTeamNumber(), self:GetCursorPosition(), nil, self.hSpecial2:GetSpecialValueFor("value"), <API key>, <API key>, <API key>, FIND_ANY_ORDER, false) for k, v in ipairs(tTargets) do v:EmitSound("Hero_Axe.Berserkers_Call") v:AddNewModifier(hCaster, self, "<API key>", {Duration = self:GetSpecialValueFor("duration")*<API key>(v)}) end else local hTarget = self:GetCursorTarget() if hTarget:TriggerSpellAbsorb( self ) then return end hTarget:EmitSound("Hero_Axe.Berserkers_Call") hTarget:AddNewModifier(self:GetCaster(), self, "<API key>", {Duration = self:GetSpecialValueFor("duration")*<API key>(hTarget)}) end end function cleric_berserk:GetCooldown(iLevel) if not self.bSpecial then self.hSpecial = Entities:First() while self.hSpecial and (self.hSpecial:GetName() ~= "<API key>" or self.hSpecial:GetCaster() ~= self:GetCaster()) do self.hSpecial = Entities:Next(self.hSpecial) end self.bSpecial = true end if self.hSpecial then return self.BaseClass.GetCooldown(self, iLevel)-self.hSpecial:GetSpecialValueFor("value") else return self.BaseClass.GetCooldown(self, iLevel) end end function ClericPrayer(keys) <API key>(keys.caster) local hSpecial = Entities:First() while hSpecial and hSpecial:GetName() ~= "<API key>" do hSpecial = Entities:Next(hSpecial) end keys.caster:EmitSound("Hero_Omniknight.GuardianAngel.Cast") local iDuration = keys.ability:GetSpecialValueFor("duration") for k, v in pairs(keys.target_entities) do local hModifier = v:FindModifierByName("<API key>") if not hModifier then v:AddNewModifier(keys.caster, keys.ability, "<API key>", {Duration = iDuration}) v:EmitSound("Hero_Omniknight.GuardianAngel") v:EmitSound("DOTA_Item.Refresher.Activate") ParticleManager:<API key>(ParticleManager:CreateParticle("particles/items2_fx/refresher.vpcf", <API key>, v), 0, v, <API key>, "attach_hitloc", v:GetAbsOrigin(), true) for i = 0, 23 do if v:GetAbilityByIndex(i) then v:GetAbilityByIndex(i):EndCooldown() end end for j,i in ipairs(<API key>) do if v:GetItemInSlot(i) then v:GetItemInSlot(i):EndCooldown() end end elseif hSpecial and hModifier:GetStackCount() < hSpecial:GetSpecialValueFor("value") then local iOriginalStackCount = hModifier:GetStackCount() v:AddNewModifier(keys.caster, keys.ability, "<API key>", {Duration = iDuration}) v:FindModifierByName("<API key>"):SetStackCount(iOriginalStackCount+1) v:EmitSound("Hero_Omniknight.GuardianAngel") v:EmitSound("DOTA_Item.Refresher.Activate") ParticleManager:<API key>(ParticleManager:CreateParticle("particles/items2_fx/refresher.vpcf", <API key>, v), 0, v, <API key>, "attach_hitloc", v:GetAbsOrigin(), true) for i = 0, 23 do if v:GetAbilityByIndex(i) then v:GetAbilityByIndex(i):EndCooldown() end end for j,i in ipairs(<API key>) do if v:GetItemInSlot(i) then v:GetItemInSlot(i):EndCooldown() end end end end end cleric_magic_mirror = class({}) function cleric_magic_mirror:GetCooldown(iLevel) if IsClient() then if self:GetCaster():HasScepter() then return 20-iLevel*5 end else if self:GetCaster():HasScepter() then return self:<API key>("scepter_cooldown", iLevel) end end return self.BaseClass.GetCooldown(self, iLevel) end
export function mockGlobalFile() { // @ts-ignore global.File = class MockFile { name: string; size: number; type: string; parts: (string | Blob | ArrayBuffer | ArrayBufferView)[]; properties?: FilePropertyBag; lastModified: number; constructor( parts: (string | Blob | ArrayBuffer | ArrayBufferView)[], name: string, properties?: FilePropertyBag ) { this.parts = parts; this.name = name; this.size = parts.join('').length; this.type = 'txt'; this.properties = properties; this.lastModified = 1234567890000; // Sat Feb 13 2009 23:31:30 GMT+0000. } }; } export function testFile(filename: string, size: number = 42) { return new File(['x'.repeat(size)], filename, undefined); }
package net.talayhan.android.vibeproject.Controller; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.ipaulpro.afilechooser.utils.FileUtils; import net.talayhan.android.vibeproject.R; import net.talayhan.android.vibeproject.Util.Constants; import java.io.File; import butterknife.ButterKnife; import butterknife.InjectView; import cn.pedant.SweetAlert.SweetAlertDialog; public class MainActivity extends Activity { @InjectView(R.id.fileChooser_bt) Button mFileChooser_bt; @InjectView(R.id.playBack_btn) Button mPlayback_bt; @InjectView(R.id.chart_bt) Button mChart_bt; private String videoPath; private String vidAddress = "https://archive.org/download/<API key>/<API key>.mp4"; private SweetAlertDialog pDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mFileChooser_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Progress dialog */ pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE); pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86")); pDialog.setTitleText("Network Type"); pDialog.setContentText("How would you like to watch video?"); pDialog.setConfirmText("Local"); pDialog.<API key>(new SweetAlertDialog.<API key>() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { // Local // Create the ACTION_GET_CONTENT Intent Intent getContentIntent = FileUtils.<API key>(); Intent intent = Intent.createChooser(getContentIntent, "Select a file"); <API key>(intent, Constants.REQUEST_CHOOSER); sweetAlertDialog.<API key>(); } }); pDialog.setCancelText("Internet"); pDialog.<API key>(new SweetAlertDialog.<API key>() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { /* check the device network state */ if (!isOnline()){ new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE) .setContentText("Your device is now offline!\n" + "Please open your Network.") .setTitleText("Open Network Connection") .<API key>(new SweetAlertDialog.<API key>() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { <API key>(MainActivity.this); sweetAlertDialog.<API key>(); } }) .show(); }else { // Create the intent to start video activity Intent i = new Intent(MainActivity.this, LocalVideoActivity.class); i.putExtra(Constants.<API key>, vidAddress); startActivity(i); sweetAlertDialog.<API key>(); } } }); pDialog.setCancelable(true); pDialog.show(); } }); mPlayback_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE) .setContentText("Please first label some video!\n" + "Later come back here!.") .setTitleText("Playback") .<API key>(new SweetAlertDialog.<API key>() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { sweetAlertDialog.<API key>(); } }) .show(); } }); mChart_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, ChartRecyclerView.class); <API key>(i, Constants.REQUEST_CHART); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Constants.REQUEST_CHOOSER: if (resultCode == RESULT_OK) { final Uri uri = data.getData(); // Get the File path from the Uri String path = FileUtils.getPath(this, uri); Toast.makeText(this, "Choosen file: " + path,Toast.LENGTH_LONG).show(); // Alternatively, use FileUtils.getFile(Context, Uri) if (path != null && FileUtils.isLocal(path)) { File file = new File(path); } // Create the intent to start video activity Intent i = new Intent(MainActivity.this, LocalVideoActivity.class); i.putExtra(Constants.<API key>,path); startActivity(i); } break; } } public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.<API key>); NetworkInfo netInfo = cm.<API key>(); return netInfo != null && netInfo.<API key>(); } public static void <API key>(Context ctx1) { final Context ctx = ctx1; final SweetAlertDialog builder = new SweetAlertDialog(ctx, SweetAlertDialog.SUCCESS_TYPE); builder.setCancelable(true); builder.setContentText("Open internet connection"); builder.setTitle("No connection error!"); builder.setConfirmText("Open wirless."); builder.<API key>(new SweetAlertDialog.<API key>() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { ctx.startActivity(new Intent(Settings.<API key>)); builder.<API key>(); } }); builder.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean <API key>(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection <API key> if (id == R.id.action_settings) { return true; }else if (id == R.id.action_search){ openSearch(); return true; } return super.<API key>(item); } private void openSearch() { Toast.makeText(this,"Clicked Search button", Toast.LENGTH_SHORT).show(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Marionette Components</title> </head> <body> Marionette View Test <script src='../build/view.js'></script> </body> </html>
<?php namespace Oro\Bundle\ApiBundle\Processor\Shared\Rest; use Oro\Bundle\ApiBundle\Metadata\RouteLinkMetadata; use Oro\Bundle\ApiBundle\Processor\Context; use Oro\Bundle\ApiBundle\Provider\ResourcesProvider; use Oro\Bundle\ApiBundle\Request\<API key> as ApiDoc; use Oro\Bundle\ApiBundle\Request\ApiAction; use Oro\Bundle\ApiBundle\Request\RequestType; use Oro\Bundle\ApiBundle\Request\Rest\RestRoutesRegistry; use Oro\Component\ChainProcessor\ContextInterface; use Oro\Component\ChainProcessor\ProcessorInterface; use Symfony\Component\Routing\Generator\<API key>; class AddHateoasLinks implements ProcessorInterface { /** @var RestRoutesRegistry */ private $routesRegistry; /** @var <API key> */ private $urlGenerator; /** @var ResourcesProvider */ private $resourcesProvider; /** * @param RestRoutesRegistry $routesRegistry * @param <API key> $urlGenerator * @param ResourcesProvider $resourcesProvider */ public function __construct( RestRoutesRegistry $routesRegistry, <API key> $urlGenerator, ResourcesProvider $resourcesProvider ) { $this->routesRegistry = $routesRegistry; $this->urlGenerator = $urlGenerator; $this->resourcesProvider = $resourcesProvider; } /** * {@inheritdoc} */ public function process(ContextInterface $context) { /** @var Context $context */ $documentBuilder = $context-><API key>(); if (null === $documentBuilder || !$context->isSuccessResponse()) { return; } $requestType = $context->getRequestType(); $entityClass = $context->getClassName(); if (ApiAction::GET_LIST !== $context->getAction() && $this-><API key>($entityClass, $context->getVersion(), $requestType) ) { return; } $documentBuilder->addLinkMetadata(ApiDoc::LINK_SELF, new RouteLinkMetadata( $this->urlGenerator, $this->routesRegistry->getRoutes($requestType)->getListRouteName(), [], ['entity' => $documentBuilder->getEntityAlias($entityClass, $requestType)] )); } /** * @param string $entityClass * @param string $version * @param RequestType $requestType * * @return bool */ private function <API key>(string $entityClass, string $version, RequestType $requestType): bool { return \in_array( ApiAction::GET_LIST, $this->resourcesProvider-><API key>($entityClass, $version, $requestType), true ); } }
const path = require('path'), fs = require('fs'), glob = require('glob'), pug = require('pug'), stylus = require('stylus'), nib = require('nib'), autoprefixer = require('autoprefixer-stylus'), {rollup} = require('rollup'), rollupPluginPug = require('rollup-plugin-pug'), rollupPluginResolve = require('<API key>'), rollupPluginReplace = require('<API key>'), <API key> = require('<API key>'), <API key> = require('<API key>'), rollupPluginAlias = require('rollup-plugin-alias'), rollupPluginBabel = require('rollup-plugin-babel'), sgUtil = require('./util'); class AppBuilder { constructor(conf, CollectorStore) { this.conf = conf; this.CollectorStore = CollectorStore; this.name = this.conf.get('package.name'); this.viewerDest = this.conf.get('viewerDest'); this.source = path.resolve(__dirname, '..', 'app'); this.sections = []; this.generateViewerPages = this.generateViewerPages.bind(this); this.<API key> = this.<API key>.bind(this); this.rollupViewerScripts = this.rollupViewerScripts.bind(this); this.<API key> = this.<API key>.bind(this); this.onEnd = this.onEnd.bind(this); } renderCollected() { if (!this.watcher) { this.CollectorStore.getFiles() .forEach(async (file) => { if (!file.exclude) { await file.render; } }); } return this; } saveCollectedData() { if (!this.watcher) { const {viewerDest, CollectorStore: {getCollectedData}} = this; sgUtil.writeJsonFile(path.join(viewerDest, 'structure.json'), getCollectedData()); } } <API key>() { return { description: this.conf.get('package.description', 'No description'), version: this.conf.get('version', this.conf.get('package.version') || 'dev') }; } onEnd(message) { return (error) => { if (error) { throw error; } sgUtil.log(`[] ${this.name} ${message}`, 'info'); }; } async generateViewerPages() { const {source, viewerDest, <API key>} = this, onEnd = this.onEnd('viewer html generated.'), templateFile = path.join(source, 'templates', 'viewer', 'index.pug'), renderOptions = Object.assign({ pretty: true, cache: false }, <API key>()); sgUtil.writeFile(path.join(viewerDest, 'index.html'), pug.renderFile(templateFile, renderOptions), onEnd); } async <API key>() { const {source, viewerDest} = this, onEnd = this.onEnd('viewer css generated.'), stylusStr = glob.sync(`${source}/style!(_)*.styl`) .map((file) => fs.readFileSync(file, 'utf8')) .join('\n'); stylus(stylusStr) .set('include css', true) .set('prefix', 'dsc-') .use(nib()) .use(autoprefixer({ browsers: ['> 5%', 'last 1 versions'], cascade: false })) .include(path.join(source, 'style')) .import('_reset') .import('_mixins') .import('_variables') .render((err, css) => { if (err) { onEnd(err); } else { sgUtil.writeFile(path.join(viewerDest, 'css', 'app.css'), css, onEnd); } }); } async rollupViewerScripts() { const {source, viewerDest} = this, destFile = path.join(viewerDest, 'scripts', 'app.js'); sgUtil.createPath(destFile); try { const bundle = await rollup({ input: path.join(source, 'scripts', 'index.js'), plugins: [ <API key>({ rename(name, id) { if (path.basename(id) !== 'index.js') { return null; } return path.basename(path.dirname(id)); } }), rollupPluginAlias({ vue: 'node_modules/vue/dist/vue.esm.js' }), rollupPluginResolve({ jsnext: true, main: true, module: true }), rollupPluginPug(), rollupPluginReplace({ 'process.env.NODE_ENV': JSON.stringify('development') }), <API key>(), rollupPluginBabel() ] }); await bundle.write({ file: destFile, format: 'iife', sourcemap: false }); } catch (error) { throw error; } this.onEnd('viewer js bundle generated.'); } } module.exports = AppBuilder;
package org.xcolab.client.contest.pojo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.xcolab.client.contest.pojo.tables.pojos.<API key>; @JsonDeserialize(as = <API key>.class) public interface <API key> { Long getId(); void setId(Long id); Long getParent(); void setParent(Long parent); Long getBigOntologyTerm(); void setBigOntologyTerm(Long bigOntologyTerm); Long <API key>(); void <API key>(Long smallOntologyTerm); String getDescription(); void setDescription(String description); String getShortName(); void setShortName(String shortName); Boolean isVisible(); void setVisible(Boolean visible); Integer getSortOrder(); void setSortOrder(Integer sortOrder); Long <API key>(); void <API key>(Long ontologyTermToLoad); Boolean isOnlyFeatured(); void setOnlyFeatured(Boolean onlyFeatured); }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Text Editor</title> <link href="favicon.ico" rel="shortcut icon"> </head> <body spellcheck="false"> <p style=" background: #ffa; border: 1px dashed; margin-top: 0; padding: .75em 1em; ">Like this project? Please support my <a href="https://github.com/mecha-cms">Mecha CMS</a> project too. Thank you!</p> <h1>Text Editor</h1> <p><textarea style="display:block;width:100%;height:6em;box-sizing:border-box;">Lorem ipsum dolor sit amet.</textarea></p> <p> <button onclick="editor.wrap('<b>', '</b>');"><b>B</b></button> <button onclick="editor.wrap('<i>', '</i>');"><i>I</i></button> <button onclick="editor.insert('', -1, true);">&#x263A;</button> </p> <h2>Features</h2> <ul> <li>Light-weight library. No dependencies. <strong>Text Editor</strong> uses plain JavaScript language.</li> <li>Simple <abbr title="Application Programming Interface">API</abbr>. Easy to learn.</li> <li>Extensible &rarr; <a href="#examples">check it out</a></li> <li>No hack. No feature detection. Optimized for modern browsers with their built-in JavaScript features.</li> <li>Make your own. The core functionality is enough to help you making your own text editor.</li> </ul> <h2>Start</h2> <pre><code>&lt;!DOCTYPE html&gt; &lt;html dir="ltr"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;&lt;textarea&gt;&lt;/textarea&gt;&lt;/p&gt; &lt;script src="<a href="text-editor.min.js" target="_blank">text-editor.min.js</a>"&gt;&lt;/script&gt; &lt;script&gt; var editor = new TE(document.querySelector('textarea')); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <h2>Configure</h2> <pre><code>var editor = new TE(<var>self</var>, <var>tab</var> = '\t');</code></pre> <pre><code>var editor = new TE(<var>self</var>, <var>state</var> = { tab: '\t' });</code></pre> <ul> <li><var>self</var> &rarr; The text area element.</li> <li><var>tab</var> &rarr; The default indent character for <code>editor.pull()</code> and <code>editor.push()</code> method.</li> <li><var>state</var> &rarr; The configuration data.</li> <li><var>state.tab</var> &rarr; The default indent character for <code>editor.pull()</code> and <code>editor.push()</code> method.</li> </ul> <h2>Instance</h2> <p>All editor instances will be stored in <code>TE.__instance__</code>. To iterate the instances is possible with <code>TE.each()</code>:</p> <pre><code>TE.each(function(key) { console.log(key); console.log(this.self); });</code></pre> <ul> <li><var>this</var> &rarr; Refers to the text editor instance.</li> <li><var>key</var> &rarr; Refers to the text editor target&rsquo;s <code>id</code> or <code>name</code> attribute value, or its current order.</li> </ul> <h2>Methods and Properties</h2> <h3>TE.version</h3> <p>Return the text editor version.</p> <h3>TE.x</h3> <p>List of regular expression characters to be escaped.</p> <h3>TE.esc(input)</h3> <p>Escape regular expression characters listed in <code>TE.x</code> from a string or array input.</p> <h3>TE._</h3> <p>Return the text editor prototypes.</p> <h3>editor.state</h3> <p>Return the text editor states if any.</p> <h3>editor.self</h3> <p>Return the <code>&lt;textarea&gt;</code> element.</p> <h3>editor.source</h3> <p>Alias for <code>editor.self</code> property.</p> <h3>editor.value</h3> <p>Return the initial value of the <code>&lt;textarea&gt;</code> element.</p> <h3>editor.set(value)</h3> <p>Set value to the <code>&lt;textarea&gt;</code> element.</p> <h3>editor.let()</h3> <p>Reset value to the initial value of the <code>&lt;textarea&gt;</code> element.</p> <h3>editor.get()</h3> <p>Get current value of the <code>&lt;textarea&gt;</code> element if not empty, otherwise, return <code>null</code>.</p> <h3>editor.$()</h3> <p>Get current text selection data.</p> <pre><code>// `a|b|c` console.log(editor.$()); // `{"start":1,"end":2,"value":"b","before":"a","after":"c","length":1}`</code></pre> <h3>editor.focus(mode = 0)</h3> <p>Focus to the <code>&lt;textarea&gt;</code>.</p> <pre><code>editor.focus(); // Focus to the last selection editor.focus(-1); // Focus to the start of text area value editor.focus(1); // Focus to the end of text area value editor.focus(true); // Select all</code></pre> <h3>editor.blur()</h3> <p>Blur from the <code>&lt;textarea&gt;</code>.</p> <h3>editor.select(...args)</h3> <p>Set selection range.</p> <pre><code>editor.select(); // Is the same as `editor.focus()` editor.select(2); // Move caret to the index `2` editor.select(0, 2); // Select from range `0` to `2` editor.select(true); // Select all</code></pre> <h3>editor.match(pattern, fn)</h3> <p>Match current selection with the pattern provided.</p> <pre><code>if (editor.match(/^\s*:\w+:\s*$/)) { alert('Selection is detected as emoji!'); // &rarr; <a href="text-editor.match.html" target="_blank">demo</a> }</code></pre> <p>Do something with the current matched selection.</p> <pre><code>var maps = { ':happy:': '', ':sad:': '', ':wonder:': '' } editor.match(/^\s*:\w+:\s*$/, function(m) { var exists = maps[m[0] = m[0] ? m[0].trim() : ""]; exists && this.insert(exists); // &rarr; <a href="text-editor.alter.html" target="_blank">demo</a> });</code></pre> <p>Match to the characters before selection, current selection and characters after selection.</p> <pre><code>var test = editor.match([/:$/, /^\w+$/, /^:/]); console.log(test[0] && test[1] && test[2]);</code></pre> <pre><code>editor.match([/:$/, /^\w+$/, /^:/], function(before, value, after) { console.log([before, value, after]); // &rarr; <a href="text-editor.toggle.html" target="_blank">demo</a> });</code></pre> <h3>editor.replace(from, to, mode = 0)</h3> <p>Replace current, before or after selection from <var>from</var> to <var>to</var>.</p> <pre><code>editor.replace(/<.*?>/g, ""); // Strip HTML tags in selection editor.replace(/<.*?>/g, "", -1); // Strip HTML tags before selection editor.replace(/<.*?>/g, "", 1); // Strip HTML tags after selection</code></pre> <h3>editor.insert(string, mode = 0, clear = false)</h3> <p>Insert <var>string</var> to (replace) the current selection.</p> <pre><code>editor.insert(':)'); // Insert at selection (replace selection) editor.insert('&lt;b&gt;', -1); // Insert before selection editor.insert('&lt;/b&gt;', 1); // Insert after selection editor.insert(':)', -1, true); // Insert before selection and delete selection editor.insert(':)', 1, true); // Insert after selection and delete selection</code></pre> <h3>editor.wrap(open, close, wrap = false)</h3> <p>Wrap current selection with <var>open</var> and <var>close</var>.</p> <pre><code>editor.wrap('&lt;', '&gt;'); // Wrap with `&lt;` and `&gt;` editor.wrap('&lt;', '&gt;', true); // Wrap with `&lt;` and `&gt;` then select</code></pre> <h3>editor.peel(open, close, wrap = false)</h3> <p>Unwrap current selection from <var>open</var> and <var>close</var>.</p> <pre><code>editor.peel('&lt;', '&gt;'); // Remove `&lt;` before selection and `&gt;` after selection editor.peel('&lt;', '&gt;', true); // Remove `&lt;` at selection start and `&gt;` at selection end editor.peel(/&lt;+/, /&gt;+/); // Remove any `&lt;` before selection and any `&gt;` after selection editor.peel(/&lt;+/, /&gt;+/, true); // Remove any `&lt;` at selection start and any `&gt;` at selection end</code></pre> <h3>editor.push(by = '\t', includeEmptyLines = false)</h3> <p>Indent current selection with <var>by</var>.</p> <pre><code>editor.push(); // Indent with `\t` editor.push('****'); <h3>editor.pull(by = '\t', includeEmptyLines = true)</h3> <p>Outdent current selection from <var>by</var>.</p> <pre><code>editor.pull(); // Outdent from `\t` editor.pull('****'); editor.pull(/[\t ]+/); // Outdent from any length of white-space</code></pre> <h3>editor.trim(open = "", close = "", start = "", end = "", tidy = true)</h3> <p>Trim current selection from white-spaces, and optionally insert characters at the specified points.</p> <pre><code>// `a&lt;open&gt;<mark>&lt;start&gt;b&lt;end&gt;</mark>&lt;close&gt;c` editor.trim(); // Remove any white-spaces before and after selection, start and end of selection editor.trim(false, false); // Remove any white-spaces at the start and end of selection editor.trim("", "", false, false); // Remove any white-spaces before and after selection editor.trim(' ', ' '); // Force a space before and after selection editor.trim('\n\n', '\n\n'); // Force line-break before and after selection editor.trim('\n\n', '\n\n', "", "", false); // Ignore empty value before and after selection, just insert that `\n\n` away</code></pre> <h2 id="examples">Examples</h2> <ul> <li><a href="text-editor.html" target="_blank">No Idea?</a></li> <li><a href="text-editor.self.html" target="_blank">Multiple Instances</a></li> <li><a href="text-editor.disabled.html" target="_blank">Disabled Input</a></li> <li><a href="text-editor.read-only.html" target="_blank">Read-Only Input</a></li> <li><a href="text-editor.get,let,set.html" target="_blank">Set, Get and Let Value</a></li> <li><a href="text-editor.$.html" target="_blank">Get Selection Data</a></li> <li><a href="text-editor.blur,focus.html" target="_blank">Focus, Blur Events</a></li> <li><a href="text-editor.select.html" target="_blank">Set Selection Range</a></li> <li><a href="text-editor.match.html" target="_blank">Match Selection</a></li> <li><a href="text-editor.alter.html" target="_blank">Alter Selection</a></li> <li><a href="text-editor.toggle.html" target="_blank">Toggle Replace Selection</a></li> <li><a href="text-editor.replace.html" target="_blank">Replace Selection</a></li> <li><a href="text-editor.insert.html" target="_blank">Insert Selection</a></li> <li><a href="text-editor.peel,wrap.html" target="_blank">Wrap, Peel Selection</a></li> <li><a href="text-editor.pull,push.html" target="_blank">Indent, Outdent Selection</a></li> <li><a href="text-editor.pull,push.type.html" target="_blank">Indent, Outdent by Custom Character</a></li> <li><a href="text-editor.pull,push.key.html" target="_blank">Indent, Outdent with Keyboard Key</a></li> <li><a href="text-editor.trim.html" target="_blank">Trim Selection</a></li> <li><a href="text-editor/rect.html" target="_blank">Get Selection Offset</a> (<a href="text-editor/rect.min.js" target="_blank">+rect.min.js</a>)</li> <li><a href="text-editor/rect.caret.html" target="_blank">Custom Caret Example</a></li> <li><a href="text-editor/history.html" target="_blank">Undo and Redo Feature</a> (<a href="text-editor/history.min.js" target="_blank">+history.min.js</a>)</li> <li><a href="text-editor/source.html" target="_blank">Source Code Editor</a> (<a href="text-editor/source.min.js" target="_blank">+source.min.js</a>)</li> </ul> <script src="text-editor.js"></script> <script> var editor = new TE(document.querySelector('textarea')); </script> </body> </html>
module ActiveWarehouse #:nodoc: # Class that supports prejoining a fact table with dimensions. This is useful if you need # to list facts along with some or all of their detail information. class PrejoinFact # The fact class that this engine instance is connected to attr_accessor :fact_class delegate :<API key>, :connection, :prejoined_fields, :<API key>, :dimension_class, :table_name, :columns, :to => :fact_class # Initialize the engine instance def initialize(fact_class) @fact_class = fact_class end # Populate the prejoined fact table. def populate(options={}) <API key>(options) end protected # Drop the storage table def <API key> connection.drop_table(<API key>) if connection.tables.include?(<API key>) end # Get foreign key names that are excluded. def <API key> <API key> = prejoined_fields.keys.collect {|k| <API key>[k]} <API key>.collect {|r| r.foreign_key} end # Construct the prejoined fact table. def <API key>(options={}) connection.transaction { <API key> connection.create_table(<API key>, :id => false) do |t| # get all columns except the foreign_key columns for prejoined dimensions columns.each do |c| t.column(c.name, c.type) unless <API key>.include?(c.name) end #prejoined_columns prejoined_fields.each_pair do |key, value| dclass = dimension_class(key) dclass.columns.each do |c| t.column(c.name, c.type) if value.include?(c.name.to_sym) end end end } end # Populate the prejoined fact table. def <API key>(options={}) fact_columns_string = columns.collect {|c| "#{table_name}." + c.name unless <API key>.include?(c.name) }.compact.join(",\n") prejoined_columns = [] tables_and_joins = "#{table_name}" prejoined_fields.each_pair do |key, value| dimension = dimension_class(key) tables_and_joins += "\nJOIN #{dimension.table_name} as #{key}" tables_and_joins += "\n ON #{table_name}.#{<API key>[key].foreign_key} = " tables_and_joins += "#{key}.#{dimension.primary_key}" prejoined_columns << value.collect {|v| "#{key}." + v.to_s} end if connection.<API key>? <API key> sql = <<-SQL SELECT #{fact_columns_string}, #{prejoined_columns.join(",\n")} FROM #{tables_and_joins} SQL sql = connection.<API key>(<API key>, sql) else <API key>(options) sql = <<-SQL INSERT INTO #{<API key>} SELECT #{fact_columns_string}, #{prejoined_columns.join(",\n")} FROM #{tables_and_joins} SQL end connection.transaction { connection.execute(sql) } end end end
from array import array import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import <API key> from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import <API key>, roc_auc_score, roc_curve from sklearn import tree import cPickle data = np.load('/Users/musthero/Documents/Yura/Applications/tmva_local/<API key>.npz') # Train on the first 2000, test on the rest X_train, y_train = data['data_training'], data['isprompt_training'].ravel() X_test, y_test = data['data_testing'][0:1000], data['isprompt_testing'][0:1000].ravel() # sklearn dt = <API key>(max_depth=3, min_samples_leaf=100) #min_samples_leaf=0.05*len(X_train)) doFit = False if doFit: print "Performing DecisionTree fit..." dt.fit(X_train, y_train) import cPickle with open('electrons_toTMVA.pkl', 'wb') as fid: cPickle.dump(dt, fid) else: print "Loading DecisionTree..." # load it again with open('electrons_toTMVA.pkl', 'rb') as fid: dt = cPickle.load(fid) #sk_y_predicted = dt.predict(X_test) #sk_y_predicted = dt.predict_proba(X_test)[:, 1] sk_y_predicted = dt.predict_proba(X_test)[:, 1] predictions = dt.predict(X_test) print predictions print y_test # Draw ROC curve fpr, tpr, _ = roc_curve(y_test, sk_y_predicted) plt.figure() plt.plot(fpr, tpr, label='ROC curve of class') plt.plot([0, 1], [0, 1], 'k plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Some extension of Receiver operating characteristic to multi-class') plt.legend(loc="lower right") plt.savefig("<API key>.png", dpi=144) tree.export_graphviz(dt, out_file='dt_viz.dot') # Save to file fpr, tpr #np.savez('<API key>.npz', # fpr=fpr, tpr=tpr)
layout: default og_type: article <article class="post grid u-pad-both pjax-animate"> <section class="grid__row"> <span class="post__date typography__mono">{{ page.date | date: "%-d %B %Y" }}</span> {{ content }} </section> </article> {% if page.comments != Nil %} {% assign showComments = page.comments %} {% else %} {% assign showComments = site.comments %} {% endif %} {% if showComments %} {% include blog-comments.html %} {% endif %} {% include blog-newsletter.html %} {% if page.next_in_category != nil %} {% assign nextpage = page.next_in_category %} {% else %} {% assign nextpage = page.first_in_category %} {% endif %} <section class="related-posts"> <a class="related-posts__link grid u-default-v-padding u-bg-natt-dark" href="{{ site.baseurl }}{{ nextpage.url }}"> <div class="grid__row"> <p class="<API key> typography__mono">Read Next</p> <h2 class="<API key>">{{ nextpage.title }}</h2> </div> </a> </section> {% include footer.html %}
package utils; import java.io.*; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ueb01.StringBufferImpl; public class Utils { private static long currentTime; public static boolean available(int port) { ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; } public static void stopwatchStart() { currentTime = java.lang.System.nanoTime(); } static ExecutorService pool = null; public static class SyncTcpResponse { public final Socket socket; public final String message; public boolean isValid() { return this.socket != null; } public SyncTcpResponse(Socket s, String m) { this.socket = s; this.message = m; } } public static String getTCPSync(final Socket socket) { StringBuilder sb = new StringBuilder(); try { Scanner s = new Scanner(socket.getInputStream()); while (s.hasNext()) { sb.append(s.next()); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public static SyncTcpResponse getTCPSync(final int port) { ServerSocket server = null; Socket client = null; StringBuilder sb = new StringBuilder(); try { server = new ServerSocket(port); client = server.accept(); Scanner s = new Scanner(client.getInputStream()); while (s.hasNext()) { sb.append(s.next()); } } catch (IOException e) { e.printStackTrace(); } finally { if (server != null) try { server.close(); } catch (IOException e) { e.printStackTrace(); } } return new SyncTcpResponse(client, sb.toString()); } public static Future<String> getTCP(final int port) { if (pool == null) { pool = Executors.newCachedThreadPool(); } return pool.submit(new Callable<String>() { @Override public String call() throws Exception { ServerSocket server = null; /*try(ServerSocket socket = new ServerSocket(port)){ Socket client = socket.accept(); Scanner s = new Scanner(client.getInputStream()); StringBuilder sb = new StringBuilder(); while (s.hasNext()){ sb.append(s.next()); } return sb.toString(); } */ return null; } }); } public static Socket sendTCP(InetAddress address, int port, String message) { try { Socket s = new Socket(address, port); return sendTCP(s, message); } catch (IOException e) { e.printStackTrace(); } return null; } public static Socket sendTCP(Socket socket, String message) { PrintWriter out = null; try { out = new PrintWriter(socket.getOutputStream()); out.println(message); out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } try { Thread.sleep(1000); } catch (<API key> e) { e.printStackTrace(); } } return socket; } public static void close() { if (pool != null) { pool.shutdown(); } } public static String wordFromScanner(Scanner scanner) { StringBuilder result = new StringBuilder(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); result.append(line); result.append("\n"); } return result.toString(); } public static String[] wordsFromScanner(Scanner scanner) { List<String> result = new ArrayList<String>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] words = line.split(" "); for (String word : words) { if (word.length() > 0) result.add(wordify(word)); } } return Utils.<String>listToArrayStr(result); } public static String wordify(String word) { return word.replace(",", "").replace(".", "").replace("'", "").replace("\"", "") .replace("...", "").replace("!", "").replace(";", "").replace(":", "").toLowerCase(); } public static <T> T[] listToArray(List<T> list) { T[] result = (T[]) new Object[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); } return result; } public static String[] listToArrayStr(List<String> list) { String[] result = new String[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); } return result; } public static void stopwatchEnd() { long current = java.lang.System.nanoTime(); long dif = current - currentTime; long millis = dif / 1000000; System.out.println("Millis: {" + millis + "} Nanos: {" + dif + "}"); } /** * Method to send a command to a Process * * @param p * @param command */ public static void send(Process p, String command) { OutputStream os = p.getOutputStream(); try { os.write(command.getBytes()); } catch (IOException e) { System.out.println("something went wrong... [Utils.send(..) -> " + e.getMessage()); } finally { try { os.close(); } catch (IOException e) { System.out.println("something went wrong while closing... [Utils.send(..) -> " + e.getMessage()); } } } public static void close(Process p) { try { p.getOutputStream().close(); p.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } /** * easy exceptionless sleep * * @param millis */ public static void sleep(long millis) { try { Thread.sleep(millis); } catch (<API key> e) { e.printStackTrace(); System.out.println("ALP5: Utils::sleep crashed.."); } } public static int <API key>(String fileName) { BufferedReader br = null; try { StringBuilder sb = new StringBuilder(); br = new BufferedReader(new FileReader(fileName)); String line = br.readLine(); while (line != null) { sb.append(line); line = br.readLine(); } return sb.length(); } catch (<API key> e) { e.printStackTrace(); System.out.println("shit happens... @Utils.<API key>"); return -1; } catch (IOException e) { e.printStackTrace(); System.out.println("shit happens while reading... @Utils.<API key>"); } finally { if (br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); return -2; } } return -3; } public static String join(String[] l, String connector) { StringBuilder sb = new StringBuilder(); for (String s : l) { if (sb.length() > 0) { sb.append(connector); } sb.append(s); } return sb.toString(); } public static String readFromStream(InputStream is){ java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } /** * Method to receive the output of a Process * * @param p * @return */ public static String read(Process p) { StringBuilder sb = new StringBuilder(); InputStream is = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String s = null; try { while ((s = reader.readLine()) != null) { if (s.equals("") || s.equals(" ")) break; sb.append(s); } } catch (IOException e) { System.out.println("something went wrong... [Utils.read(..) -> " + e.getMessage()); } return sb.toString(); } public static void main(String[] args) throws IOException, <API key> { System.out.println("yyy"); System.out.println('a' > 'b'); } /** * If you want to use your ssh-key-login, you need to generate a pem-File from * the ssh-private-key and put it into the main folder ( ALP5/ ); You also need * to define the user with @ (like: jutanke@peking.imp.fu-berlin.de:...) * * @param commandId * @return */ public static Process fork(String commandId) { String username = null; // HARDCODE ME! String password = null; // HARDCODE ME! String host = null; String command = commandId; if (commandId.contains(":")) { String[] temp = commandId.split(":"); if (temp[0].length() > 2) { // if the host is shorter its probably just a windows drive ('d:// ...') host = temp[0]; if (host.contains("@")) { String[] t = host.split("@"); username = t[0]; host = t[1]; } if (temp.length == 3) { command = temp[1] + ":" + temp[2]; // to "repair" windows drives... } else { command = temp[1]; } } } if (host != null) { Process remoteP = null; try { final Connection conn = new Connection(host); conn.connect(); boolean isAuth = false; if (password != null) { isAuth = conn.<API key>(username, password); } if (!isAuth) { File f = new File("private.pem"); isAuth = conn.<API key>(username, f, ""); if (!isAuth) return null; } final Session sess = conn.openSession(); sess.execCommand(command); remoteP = new Process() { @Override public OutputStream getOutputStream() { return sess.getStdin(); } @Override public InputStream getInputStream() { return sess.getStdout(); } @Override public InputStream getErrorStream() { return sess.getStderr(); } @Override public int waitFor() throws <API key> { sess.wait(); return 0; } @Override public int exitValue() { return 0; } @Override public void destroy() { sess.close(); conn.close(); } }; } catch (IOException e) { System.out.println("shit happens with the ssh connection: @Utils.fork .. " + e.getMessage()); return null; } return remoteP; } ProcessBuilder b = new ProcessBuilder(command.split(" ")); try { return b.start(); } catch (IOException e) { System.out.println("shit happens: @Utils.fork .. " + e.getMessage()); } return null; } }
import { onUnexpectedError } from 'vs/base/common/errors'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI, UriComponents } from 'vs/base/common/uri'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { <API key> } from 'vs/editor/common/services/editorWorkerService'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { <API key> } from 'vs/workbench/api/electron-browser/extHostCustomers'; import { ExtHostContext, <API key>, IExtHostContext, MainContext, <API key> } from '../node/extHost.protocol'; import { <API key> } from 'vs/base/common/cancellation'; @<API key>(MainContext.<API key>) export class <API key> implements <API key> { private readonly <API key> = new Map<number, IDisposable>(); private readonly _pendingUpdate = new Map<string, <API key>>(); private readonly _proxy: <API key>; constructor( extHostContext: IExtHostContext, @ITextModelService private readonly <API key>: ITextModelService, @IModeService private readonly _modeService: IModeService, @IModelService private readonly _modelService: IModelService, @<API key> private readonly <API key>: <API key> ) { this._proxy = extHostContext.getProxy(ExtHostContext.<API key>); } dispose(): void { this.<API key>.forEach(p => p.dispose()); this._pendingUpdate.forEach(source => source.dispose()); } $<API key>(handle: number, scheme: string): void { const registration = this.<API key>.<API key>(scheme, { provideTextContent: (uri: URI): Thenable<ITextModel> => { return this._proxy.$<API key>(handle, uri).then(value => { if (typeof value === 'string') { const firstLineText = value.substr(0, 1 + value.search(/\r?\n/)); const languageSelection = this._modeService.<API key>(uri.fsPath, firstLineText); return this._modelService.createModel(value, languageSelection, uri); } return undefined; }); } }); this.<API key>.set(handle, registration); } $<API key>(handle: number): void { const registration = this.<API key>.get(handle); if (registration) { registration.dispose(); this.<API key>.delete(handle); } } $<API key>(uri: UriComponents, value: string): void { const model = this._modelService.getModel(URI.revive(uri)); if (!model) { return; } // cancel and dispose an existing update if (this._pendingUpdate.has(model.id)) { this._pendingUpdate.get(model.id).cancel(); } // create and keep update token const myToken = new <API key>(); this._pendingUpdate.set(model.id, myToken); this.<API key>.<API key>(model.uri, [{ text: value, range: model.getFullModelRange() }]).then(edits => { // remove token this._pendingUpdate.delete(model.id); if (myToken.token.<API key>) { // ignore this return; } if (edits.length > 0) { // use the evil-edit as these models show in readonly-editor only model.applyEdits(edits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text))); } }).catch(onUnexpectedError); } }
// This file was generated, please do not edit it directly. using MS.Internal; using MS.Internal.KnownBoxes; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; namespace System.Windows.Media.Animation { <summary> This class is used to animate a Byte property value along a set of key frames. </summary> [ContentProperty("KeyFrames")] public class <API key> : ByteAnimationBase, IKeyFrameAnimation, IAddChild { #region Data private <API key> _keyFrames; private <API key>[] <API key>; private bool _areKeyTimesValid; #endregion #region Constructors <Summary> Creates a new <API key>. </Summary> public <API key>() : base() { _areKeyTimesValid = true; } #endregion #region Freezable <summary> Creates a copy of this <API key>. </summary> <returns>The copy</returns> public new <API key> Clone() { return (<API key>)base.Clone(); } <summary> Returns a version of this class with all its base property values set to the current animated values and removes the animations. </summary> <returns> Since this class isn't animated, this method will always just return this instance of the class. </returns> public new <API key> CloneCurrentValue() { return (<API key>)base.CloneCurrentValue(); } <summary> Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); canFreeze &= Freezable.Freeze(_keyFrames, isChecking); if (canFreeze & !_areKeyTimesValid) { ResolveKeyTimes(); } return canFreeze; } <summary> Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>. </summary> protected override void OnChanged() { _areKeyTimesValid = false; base.OnChanged(); } <summary> Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. </summary> <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new <API key>(); } <summary> Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. </summary> protected override void CloneCore(Freezable sourceFreezable) { <API key> sourceAnimation = (<API key>) sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } <summary> Implementation of <see cref="System.Windows.Freezable.<API key>(Freezable)">Freezable.<API key></see>. </summary> protected override void <API key>(Freezable sourceFreezable) { <API key> sourceAnimation = (<API key>) sourceFreezable; base.<API key>(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } <summary> Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. </summary> protected override void GetAsFrozenCore(Freezable source) { <API key> sourceAnimation = (<API key>) source; base.GetAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } <summary> Implementation of <see cref="System.Windows.Freezable.<API key>(Freezable)">Freezable.<API key></see>. </summary> protected override void <API key>(Freezable source) { <API key> sourceAnimation = (<API key>) source; base.<API key>(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } <summary> Helper used by the four Freezable clone methods to copy the resolved key times and key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here. </summary> <param name="sourceAnimation"></param> <param name="isCurrentValueClone"></param> private void CopyCommon(<API key> sourceAnimation, bool isCurrentValueClone) { _areKeyTimesValid = sourceAnimation._areKeyTimesValid; if ( _areKeyTimesValid && sourceAnimation.<API key> != null) { // <API key> is an array of <API key> so the notion of CurrentValueClone doesn't apply <API key> = (<API key>[])sourceAnimation.<API key>.Clone(); } if (sourceAnimation._keyFrames != null) { if (isCurrentValueClone) { _keyFrames = (<API key>)sourceAnimation._keyFrames.CloneCurrentValue(); } else { _keyFrames = (<API key>)sourceAnimation._keyFrames.Clone(); } <API key>(null, _keyFrames); } } #endregion // Freezable #region IAddChild interface <summary> Adds a child object to this KeyFrameAnimation. </summary> <param name="child"> The child object to add. </param> <remarks> A KeyFrameAnimation only accepts a KeyFrame of the proper type as a child. </remarks> void IAddChild.AddChild(object child) { WritePreamble(); if (child == null) { throw new <API key>("child"); } AddChild(child); WritePostscript(); } <summary> Implemented to allow KeyFrames to be direct children of KeyFrameAnimations in markup. </summary> [EditorBrowsable(<API key>.Advanced)] protected virtual void AddChild(object child) { ByteKeyFrame keyFrame = child as ByteKeyFrame; if (keyFrame != null) { KeyFrames.Add(keyFrame); } else { throw new ArgumentException(SR.Get(SRID.<API key>), "child"); } } <summary> Adds a text string as a child of this KeyFrameAnimation. </summary> <param name="childText"> The text to add. </param> <remarks> A KeyFrameAnimation does not accept text as a child, so this method will raise an <API key> unless a derived class has overridden the behavior to add text. </remarks> <exception cref="<API key>">The childText parameter is null.</exception> void IAddChild.AddText(string childText) { if (childText == null) { throw new <API key>("childText"); } AddText(childText); } <summary> This method performs the core functionality of the AddText() method on the IAddChild interface. For a KeyFrameAnimation this means throwing and <API key> because it doesn't support adding text. </summary> <remarks> This method is the only core implementation. It does not call WritePreamble() or WritePostscript(). It also doesn't throw an <API key> if the childText parameter is null. These tasks are performed by the interface implementation. Therefore, it's OK for a derived class to override this method and call the base class implementation only if they determine that it's the right course of action. The derived class can rely on KeyFrameAnimation's implementation of IAddChild.AddChild or implement their own following the Freezable pattern since that would be a public method. </remarks> <param name="childText">A string representing the child text that should be added. If this is a KeyFrameAnimation an exception will be thrown.</param> <exception cref="<API key>">Timelines have no way of adding text.</exception> [EditorBrowsable(<API key>.Advanced)] protected virtual void AddText(string childText) { throw new <API key>(SR.Get(SRID.<API key>)); } #endregion #region ByteAnimationBase <summary> Calculates the value this animation believes should be the current value for the property. </summary> <param name="defaultOriginValue"> This value is the suggested origin value provided to the animation to be used if the animation does not have its own concept of a start value. If this animation is the first in a composition chain this value will be the snapshot value if one is available or the base property value if it is not; otherise this value will be the value returned by the previous animation in the chain with an animationClock that is not Stopped. </param> <param name="<API key>"> This value is the suggested destination value provided to the animation to be used if the animation does not have its own concept of an end value. This value will be the base value if the animation is in the first composition layer of animations on a property; otherwise this value will be the output value from the previous composition layer of animations for the property. </param> <param name="animationClock"> This is the animationClock which can generate the CurrentTime or CurrentProgress value to be used by the animation to generate its output value. </param> <returns> The value this animation believes should be the current value for the property. </returns> protected sealed override Byte GetCurrentValueCore( Byte defaultOriginValue, Byte <API key>, AnimationClock animationClock) { Debug.Assert(animationClock.CurrentState != ClockState.Stopped); if (_keyFrames == null) { return <API key>; } // We resolved our KeyTimes when we froze, but also got notified // of the frozen state and therefore invalidated ourselves. if (!_areKeyTimesValid) { ResolveKeyTimes(); } if (<API key> == null) { return <API key>; } TimeSpan currentTime = animationClock.CurrentTime.Value; Int32 keyFrameCount = <API key>.Length; Int32 maxKeyFrameIndex = keyFrameCount - 1; Byte <API key>; Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames."); Int32 <API key> = 0; // Skip all the key frames with key times lower than the current time. // <API key> will be greater than maxKeyFrameIndex // if we are past the last key frame. while ( <API key> < keyFrameCount && currentTime > <API key>[<API key>]._resolvedKeyTime) { <API key>++; } // If there are multiple key frames at the same key time, be sure to go to the last one. while ( <API key> < maxKeyFrameIndex && currentTime == <API key>[<API key> + 1]._resolvedKeyTime) { <API key>++; } if (<API key> == keyFrameCount) { // Past the last key frame. <API key> = <API key>(maxKeyFrameIndex); } else if (currentTime == <API key>[<API key>]._resolvedKeyTime) { // Exactly on a key frame. <API key> = <API key>(<API key>); } else { // Between two key frames. Double <API key> = 0.0; Byte fromValue; if (<API key> == 0) { // The current key frame is the first key frame so we have // some special rules for determining the fromValue and an // optimized method of calculating the <API key>. // If we're additive we want the base value to be a zero value // so that if there isn't a key frame at time 0.0, we'll use // the zero value for the time 0.0 value and then add that // later to the base value. if (IsAdditive) { fromValue = AnimatedTypeHelpers.GetZeroValueByte(defaultOriginValue); } else { fromValue = defaultOriginValue; } // Current segment time divided by the segment duration. // Note: the reason this works is that we know that we're in // the first segment, so we can assume: // currentTime.TotalMilliseconds = current segment time // <API key>[0]._resolvedKeyTime.TotalMilliseconds = current segment duration <API key> = currentTime.TotalMilliseconds / <API key>[0]._resolvedKeyTime.TotalMilliseconds; } else { Int32 <API key> = <API key> - 1; TimeSpan <API key> = <API key>[<API key>]._resolvedKeyTime; fromValue = <API key>(<API key>); TimeSpan segmentCurrentTime = currentTime - <API key>; TimeSpan segmentDuration = <API key>[<API key>]._resolvedKeyTime - <API key>; <API key> = segmentCurrentTime.TotalMilliseconds / segmentDuration.TotalMilliseconds; } <API key> = GetResolvedKeyFrame(<API key>).InterpolateValue(fromValue, <API key>); } // If we're cumulative, we need to multiply the final key frame // value by the current repeat count and add this to the return // value. if (IsCumulative) { Double currentRepeat = (Double)(animationClock.CurrentIteration - 1); if (currentRepeat > 0.0) { <API key> = AnimatedTypeHelpers.AddByte( <API key>, AnimatedTypeHelpers.ScaleByte(<API key>(maxKeyFrameIndex), currentRepeat)); } } // If we're additive we need to add the base value to the return value. if (IsAdditive) { return AnimatedTypeHelpers.AddByte(defaultOriginValue, <API key>); } return <API key>; } <summary> Provide a custom natural Duration when the Duration property is set to Automatic. </summary> <param name="clock"> The Clock whose natural duration is desired. </param> <returns> If the last KeyFrame of this animation is a KeyTime, then this will be used as the NaturalDuration; otherwise it will be one second. </returns> protected override sealed Duration <API key>(Clock clock) { return new Duration(<API key>); } #endregion #region IKeyFrameAnimation <summary> Returns the <API key> used by this <API key>. </summary> IList IKeyFrameAnimation.KeyFrames { get { return KeyFrames; } set { KeyFrames = (<API key>)value; } } <summary> Returns the <API key> used by this <API key>. </summary> public <API key> KeyFrames { get { ReadPreamble(); // The reason we don't just set _keyFrames to the empty collection // in the first place is that null tells us that the user has not // asked for the collection yet. The first time they ask for the // collection and we're unfrozen, policy dictates that we give // them a new unfrozen collection. All subsequent times they will // get whatever collection is present, whether frozen or unfrozen. if (_keyFrames == null) { if (this.IsFrozen) { _keyFrames = <API key>.Empty; } else { WritePreamble(); _keyFrames = new <API key>(); <API key>(null, _keyFrames); WritePostscript(); } } return _keyFrames; } set { if (value == null) { throw new <API key>("value"); } WritePreamble(); if (value != _keyFrames) { <API key>(_keyFrames, value); _keyFrames = value; WritePostscript(); } } } <summary> Returns true if we should serialize the KeyFrames, property for this Animation. </summary> <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns> [EditorBrowsable(<API key>.Never)] public bool <API key>() { ReadPreamble(); return _keyFrames != null && _keyFrames.Count > 0; } #endregion #region Public Properties <summary> If this property is set to true, this animation will add its value to the base value or the value of the previous animation in the composition chain. Another way of saying this is that the units specified in the animation are relative to the base value rather than absolute units. </summary> <remarks> In the case where the first key frame's resolved key time is not 0.0 there is slightly different behavior between <API key> with IsAdditive set and without. Animations with the property set to false will behave as if there is a key frame at time 0.0 with the value of the base value. Animations with the property set to true will behave as if there is a key frame at time 0.0 with a zero value appropriate to the type of the animation. These behaviors provide the results most commonly expected and can be overridden by simply adding a key frame at time 0.0 with the preferred value. </remarks> public bool IsAdditive { get { return (bool)GetValue(IsAdditiveProperty); } set { SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value)); } } <summary> If this property is set to true, the value of this animation will accumulate over repeat cycles. For example, if this is a point animation and your key frames describe something approximating and arc, setting this property to true will result in an animation that would appear to bounce the point across the screen. </summary> <remarks> This property works along with the IsAdditive property. Setting this value to true has no effect unless IsAdditive is also set to true. </remarks> public bool IsCumulative { get { return (bool)GetValue(<API key>); } set { SetValueInternal(<API key>, BooleanBoxes.Box(value)); } } #endregion #region Private Methods private struct KeyTimeBlock { public int BeginIndex; public int EndIndex; } private Byte <API key>(Int32 <API key>) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling <API key>"); return GetResolvedKeyFrame(<API key>).Value; } private ByteKeyFrame GetResolvedKeyFrame(Int32 <API key>) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame"); return _keyFrames[<API key>[<API key>].<API key>]; } <summary> Returns the largest time span specified key time from all of the key frames. If there are not time span key times a time span of one second is returned to match the default natural duration of the From/To/By animations. </summary> private TimeSpan <API key> { get { bool hasTimeSpanKeyTime = false; TimeSpan <API key> = TimeSpan.Zero; if (_keyFrames != null) { Int32 keyFrameCount = _keyFrames.Count; for (int index = 0; index < keyFrameCount; index++) { KeyTime keyTime = _keyFrames[index].KeyTime; if (keyTime.Type == KeyTimeType.TimeSpan) { hasTimeSpanKeyTime = true; if (keyTime.TimeSpan > <API key>) { <API key> = keyTime.TimeSpan; } } } } if (hasTimeSpanKeyTime) { return <API key>; } else { return TimeSpan.FromSeconds(1.0); } } } private void ResolveKeyTimes() { Debug.Assert(!_areKeyTimesValid, "<API key>.ResolveKeyTimes() shouldn't be called if the key times are already valid."); int keyFrameCount = 0; if (_keyFrames != null) { keyFrameCount = _keyFrames.Count; } if (keyFrameCount == 0) { <API key> = null; _areKeyTimesValid = true; return; } <API key> = new <API key>[keyFrameCount]; int index = 0; // Initialize the <API key>. for ( ; index < keyFrameCount; index++) { <API key>[index].<API key> = index; } // calculationDuration represents the time span we will use to resolve // percent key times. This is defined as the value in the following // precedence order: // 1. The animation's duration, but only if it is a time span, not auto or forever. // 2. The largest time span specified key time of all the key frames. // 3. 1 second, to match the From/To/By animations. TimeSpan calculationDuration = TimeSpan.Zero; Duration duration = Duration; if (duration.HasTimeSpan) { calculationDuration = duration.TimeSpan; } else { calculationDuration = <API key>; } int maxKeyFrameIndex = keyFrameCount - 1; ArrayList unspecifiedBlocks = new ArrayList(); bool hasPacedKeyTimes = false; // Pass 1: Resolve Percent and Time key times. index = 0; while (index < keyFrameCount) { KeyTime keyTime = _keyFrames[index].KeyTime; switch (keyTime.Type) { case KeyTimeType.Percent: <API key>[index]._resolvedKeyTime = TimeSpan.FromMilliseconds( keyTime.Percent * calculationDuration.TotalMilliseconds); index++; break; case KeyTimeType.TimeSpan: <API key>[index]._resolvedKeyTime = keyTime.TimeSpan; index++; break; case KeyTimeType.Paced: case KeyTimeType.Uniform: if (index == maxKeyFrameIndex) { // If the last key frame doesn't have a specific time // associated with it its resolved key time will be // set to the calculationDuration, which is the // defined in the comments above where it is set. // Reason: We only want extra time at the end of the // key frames if the user specifically states that // the last key frame ends before the animation ends. <API key>[index]._resolvedKeyTime = calculationDuration; index++; } else if ( index == 0 && keyTime.Type == KeyTimeType.Paced) { // Note: It's important that this block come after // the previous if block because of rule precendence. // If the first key frame in a multi-frame key frame // collection is paced, we set its resolved key time // to 0.0 for performance reasons. If we didn't, the // resolved key time list would be dependent on the // base value which can change every animation frame // in many cases. <API key>[index]._resolvedKeyTime = TimeSpan.Zero; index++; } else { if (keyTime.Type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } KeyTimeBlock block = new KeyTimeBlock(); block.BeginIndex = index; // NOTE: We don't want to go all the way up to the // last frame because if it is Uniform or Paced its // resolved key time will be set to the calculation // duration using the logic above. // This is why the logic is: // ((++index) < maxKeyFrameIndex) // instead of: // ((++index) < keyFrameCount) while ((++index) < maxKeyFrameIndex) { KeyTimeType type = _keyFrames[index].KeyTime.Type; if ( type == KeyTimeType.Percent || type == KeyTimeType.TimeSpan) { break; } else if (type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } } Debug.Assert(index < keyFrameCount, "The end index for a block of unspecified key frames is out of bounds."); block.EndIndex = index; unspecifiedBlocks.Add(block); } break; } } // Pass 2: Resolve Uniform key times. for (int j = 0; j < unspecifiedBlocks.Count; j++) { KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j]; TimeSpan blockBeginTime = TimeSpan.Zero; if (block.BeginIndex > 0) { blockBeginTime = <API key>[block.BeginIndex - 1]._resolvedKeyTime; } // The number of segments is equal to the number of key // frames we're working on plus 1. Think about the case // where we're working on a single key frame. There's a // segment before it and a segment after it. // Time known Uniform Time known // | (segment 1) | (segment 2) | Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1; TimeSpan uniformTimeStep = TimeSpan.FromTicks((<API key>[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount); index = block.BeginIndex; TimeSpan resolvedTime = blockBeginTime + uniformTimeStep; while (index < block.EndIndex) { <API key>[index]._resolvedKeyTime = resolvedTime; resolvedTime += uniformTimeStep; index++; } } // Pass 3: Resolve Paced key times. if (hasPacedKeyTimes) { <API key>(); } // Sort resolved key frame entries. Array.Sort(<API key>); _areKeyTimesValid = true; return; } <summary> This should only be called from ResolveKeyTimes and only at the appropriate time. </summary> private void <API key>() { Debug.Assert(_keyFrames != null && _keyFrames.Count > 2, "Caller must guard against calling this method when there are insufficient keyframes."); // If the first key frame is paced its key time has already // been resolved, so we start at index 1. int index = 1; int maxKeyFrameIndex = <API key>.Length - 1; do { if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced) { // We've found a paced key frame so this is the // beginning of a paced block. // The first paced key frame in this block. int <API key> = index; // List of segment lengths for this paced block. List<Double> segmentLengths = new List<Double>(); // The resolved key time for the key frame before this // block which we'll use as our starting point. TimeSpan <API key> = <API key>[index - 1]._resolvedKeyTime; // The total of the segment lengths of the paced key // frames in this block. Double totalLength = 0.0; // The key value of the previous key frame which will be // used to determine the segment length of this key frame. Byte prevKeyValue = _keyFrames[index - 1].Value; do { Byte currentKeyValue = _keyFrames[index].Value; // Determine the segment length for this key frame and // add to the total length. totalLength += AnimatedTypeHelpers.<API key>(prevKeyValue, currentKeyValue); // Temporarily store the distance into the total length // that this key frame represents in the resolved // key times array to be converted to a resolved key // time outside of this loop. segmentLengths.Add(totalLength); // Prepare for the next iteration. prevKeyValue = currentKeyValue; index++; } while ( index < maxKeyFrameIndex && _keyFrames[index].KeyTime.Type == KeyTimeType.Paced); // index is currently set to the index of the key frame // after the last paced key frame. This will always // be a valid index because we limit ourselves with // maxKeyFrameIndex. // We need to add the distance between the last paced key // frame and the next key frame to get the total distance // inside the key frame block. totalLength += AnimatedTypeHelpers.<API key>(prevKeyValue, _keyFrames[index].Value); // Calculate the time available in the resolved key time space. TimeSpan pacedBlockDuration = <API key>[index]._resolvedKeyTime - <API key>; // Convert lengths in segmentLengths list to resolved // key times for the paced key frames in this block. for (int i = 0, <API key> = <API key>; i < segmentLengths.Count; i++, <API key>++) { // The resolved key time for each key frame is: // The key time of the key frame before this paced block // + ((the percentage of the way through the total length) // * the resolved key time space available for the block) <API key>[<API key>]._resolvedKeyTime = <API key> + TimeSpan.FromMilliseconds( (segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds); } } else { index++; } } while (index < maxKeyFrameIndex); } #endregion } }
'use strict'; const Hoek = require('hoek'); exports.plugin = { register: async (plugin, options) => { plugin.ext('onPreResponse', (request, h) => { try { var internals = { devEnv: (process.env.NODE_ENV === 'development'), meta: options.meta, credentials: request.auth.isAuthenticated ? request.auth.credentials : null }; var response = request.response; if (response.variety && response.variety === 'view') { response.source.context = Hoek.merge(internals, request.response.source.context); } return h.continue; } catch (error) { throw error; } }); }, pkg: require('../package.json'), name: 'context' };
'use strict'; //Customers service used to communicate Customers REST endpoints angular.module('customers') .factory('Customers', ['$resource', function($resource) { return $resource('customers/:customerId', { customerId: '@_id' }, { update: { method: 'PUT' } }); } ]) .factory('Notify', ['$rootScope', function($rootScope) { var notify = {}; notify.sendMsg = function(msg, data) { data = data || {}; $rootScope.$emit(msg, data); console.log('message sent!'); }; notify.getMsg = function(msg, func, scope) { var unbind = $rootScope.$on(msg, func); if (scope) { scope.$on('destroy', unbind); } }; return notify; } ]);
#pragma once char separator; #ifdef _WIN32 #define DIR_SEPARATOR '\\' #else #define DIR_SEPARATOR '/' #endif #include <string> #include <algorithm> using namespace std; class PathUtil{ public: /*A small function to extract FileName from File Path C:/File.exe -> File.exe */ string static extractFileName(string FilePath){ int separatorlast = FilePath.find_last_of(DIR_SEPARATOR); return FilePath.substr(separatorlast + 1, FilePath.length() - separatorlast); } string static extractFileExt(string FilePath){ int separatorlast = FilePath.find_last_of('.'); string FileExt = FilePath.substr(separatorlast + 1, FilePath.length() - separatorlast); std::transform(FileExt.begin(), FileExt.end(), FileExt.begin(), ::tolower); return FileExt; } string static <API key>(string FilePath){ string FileName = extractFileName(FilePath); int separatorlast = FilePath.find_last_of(DIR_SEPARATOR); int dotlast = FilePath.find_last_of('.'); return FilePath.substr(separatorlast + 1, dotlast); } string static extractDirPath(string FilePath){ string FileName = extractFileName(FilePath); int separatorlast = FilePath.find_last_of(DIR_SEPARATOR); int dotlast = FilePath.find_first_of('.'); return FilePath.substr(separatorlast + 1, dotlast - separatorlast -1); } };
/* some devices call home before accepting a wifi access point. Spoof those responses. */ var path = require('path'); exports.load = function(server, boatData, settings) { var endpointMap = [ {'route': '/kindle-wifi/wifiredirect.html', 'responseFile': 'kindle.html'} , {'route': '/kindle-wifi/wifistub.html', 'responseFile': 'kindle.html'} ]; _.each(endpointMap, function(endpoint) { server.get(endpoint.route, function(req, res) { res.sendFile(path.join(__dirname + endpoint.responseFile)); }); }); };
# <TwitterConsumerkey> To start the project git clone https://github.com/klosorio10/ExamenFinalWebDev.git cd ExamenFinalWebdev cd ExamenFinal A simple boilerplate for a Meteor 1.4 Twitter streamer application with React. Uses the twitter [npm](https: export <TwitterConsumerkey>="yourCredentialsHere" export <TwitterConsumerkey>="yourCredentialsHere" export <TwitterConsumerkey>="yourCredentialsHere" export <TwitterConsumerkey>="yourCredentialsHere" meteor npm install meteor This is a very basic implementation that handles a global search shared by all users and doesn't implement any security or restriction. It's intended as a starting point, so add your own requirements.
USE [VipunenTK] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[<API key>]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].[<API key>]( [id] [int] NOT NULL, [alkaa] [date] NOT NULL, [paattyy] [date] NOT NULL, [<API key>] [nvarchar](2) NOT NULL, [<API key>] [nvarchar](200) NULL, [<API key>] [nvarchar](200) NULL, [<API key>] [nvarchar](200) NULL, [jarjestys] [nvarchar](50) NULL, [tietolahde] [nvarchar](50) NULL ) ON [PRIMARY] END GO INSERT [dbo].[<API key>] ([id], [alkaa], [paattyy], [<API key>], [<API key>], [<API key>], [<API key>], [jarjestys], [tietolahde]) VALUES (-2, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'-2', N'Virhetilanne', N'Feltillstånd', N'Error occurred', N'99999', N'Manuaalinen') GO INSERT [dbo].[<API key>] ([id], [alkaa], [paattyy], [<API key>], [<API key>], [<API key>], [<API key>], [jarjestys], [tietolahde]) VALUES (-1, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'-1', N'Tuntematon', N'Information saknas', N'Missing data', N'99998', N'Manuaalinen') GO INSERT [dbo].[<API key>] ([id], [alkaa], [paattyy], [<API key>], [<API key>], [<API key>], [<API key>], [jarjestys], [tietolahde]) VALUES (1, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'1', N'Erikoislääkärit', N'*SV*Erikoislääkärit', N'*EN*Erikoislääkärit', N'1', N'Tilastokeskus') GO INSERT [dbo].[<API key>] ([id], [alkaa], [paattyy], [<API key>], [<API key>], [<API key>], [<API key>], [jarjestys], [tietolahde]) VALUES (2, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'2', N'Erikoishammaslääkärit', N'*SV*Erikoishammaslääkärit', N'*EN*Erikoishammaslääkärit', N'2', N'Tilastokeskus') GO USE [ANTERO]
# <API key> www.<API key>.hu
# Basics Toast is a Rack application that hooks into Ruby on Rails providing a REST interface for ActiveRecord models. For each model a HTTP interface can be configured. Using Toast's configuration DSL one declares which of its attributes are exposed, which are readable and/or writable using white lists. Web Service Provider Web Service Consumer | Toast | <--HTTP/REST--> | AJAX app, | | | \ | Java app, etc.| | Model A | | Model B | | Model C | Toast dispatches any request to the right model class by using naming conventions. That way a model can be exposed on the web by a simple configuration file under `config/toast-api/coconut.rb`: {% highlight ruby %} expose(Coconut) { readables :color, :weight via_get { # for GET /coconut/ID allow do |user, coconut, uri_params| user.is_admin? end } collection(:all) { via_get { # for GET /coconuts allow do |user, coconut, uri_params| user.is_admin? end } } } {% endhighlight %} This exposes the model Coconut. Toast would respond like this: GET /coconuts --> 200 OK --> [{"self":"https: {"self":"https: {"self":"https: given there are 3 rows in the table _coconuts_. Note that this request translates to the ActiveRecord call `Coconut.all`, hence the exposition of the `all` collection. Each of the URIs in the response will fetch the respective Coconut instances: GET /coconut/2 --> 200 OK --> {"self": "https: "color": "brown", "weight": 2.1} `color` and `weight` were declared in the `readables` list. That means these attributes are exposed via GET requests, but not updatable by PATCH requests. To allow that attributes must be declared writable: {% highlight ruby %} expose(Coconut) { readables :color writables :weight } {% endhighlight %} POST and DELETE operations must be allowed explicitly: {% highlight ruby %} expose(Coconut) { readables :color, :weight via_get { # for GET /coconut/ID allow do |user, coconut, uri_params| user.is_admin? end } via_delete { # for DELETE /coconut/ID allow do |user, coconut, uri_params| user.is_admin? end } collection(:all) { via_get { # for GET /coconuts allow do |user, coconut, uri_params| user.is_admin? end } via_post { # for POST /coconuts allow do |user, coconut, uri_params| user.is_admin? end } } } {% endhighlight %} The above permits to POST a new record (== `Coconut.create(...)` and to DELETE single instances (== `Coconnut.find(id).destroy`): POST /coconuts <-- {"color": "yellow", "weight": 42.0} --> 201 Created --> {"self": "https: "color": "yellow", "weight": 42.0} DELETE /coconut/3 --> 200 OK Nonetheless exposing associations will render your entire data model (or parts of it) a complete web-service. Associations will be represented as URIs via which the associated resource(s) can be fetched: {% highlight ruby %} class Coconut < ActiveRecord::Base belongs_to :tree has_many :consumers end {% endhighlight %} together with `config/toast-api/coconut.rb`: {% highlight ruby %} expose(Coconut) { readables :color, :weight association(:tree) { via_get { allow do |*args| true end } } association(:consumers) { via_get { allow do |user, coconut, uri_params| user.role == 'admin' end } via_post { allow do |user, coconut, uri_params| user.role == 'admin' end } } } {% endhighlight %} GET /coconut/2 --> 200 OK --> {"self": "https: "tree": "https: "consumers": "https: "color": "brown", "weight": 2.1} ## Representation Toast's JSON representation is very minimal. As you can see above it does not have any qualification of the properties. Data and links and even structured property value are possible. There are other standards like [HAL](http: Toast's key ideas and distinguishing features are: Simplicity and Opaque URIs. The JSON representation was guided by the idea that any client(/-programmer) must know the representation of each resource by documentation anyway, so there is no need to nest links in a 'links' sub structure like JSON API does. The only rules for Toast's JSON representation are: * The `self` property is the canonical URI (see below) of the model/resource * Link properties are named like ActiveRecord associations in the model and are not in non-canonical form * Data properties are named as the corresponding attributes of the model. They can contain any type and also structured data (serialized by AR or self constructed). ## URIs Toast treats URIs generally as opaque strings, meaning that it only uses complete URLs and has no concept of "URL templates" for processing. Such templates may only appear in the documentation. The canonical form of a URI for a model/resource is: `https://<HOST>/<PATH>/<RESOURCE>/<ID>?<PARAMS>`, where * `https://<HOST>` is FQDN. * `<PATH>` is an optional path segment, * `<RESOURCE>` is name of the resource/model * `<ID>` is a string of digits: `[0-9]+`, * `<PARAMS>` is an optional list of query parameters Association URIs composed like: `<CANONICAL>/<ASSOCIATION>?<PARAMS>`, where * `<CANONICAL>` is as defined above * `<ASSOCIATION>` is the name a models association (`has_many`, `belongs_to`, ...) Root collection URIs are also provided: `https://<HOST>/<PATH>/<RESOURCES>?<PARAMS>`. The string `<RESOURCES>` is named after a class method of a model that returns a relation to a collection of instances of the same model. ## Association Treatment Model instances link each other and construct a web of model instances/resources. The web is conveyed by URIs that can be traversed by GET request. All model association that are exposed appear in the JSON response as a URL, nothing else (embedding can be achieved through regular data properties). Association properties never change when associations change, because they don't use the canonical URI form. They can be used to issue a * a POST request to create a new resource + linking to the base resource, * a DELETE request to delete a model instance/resource, * a LINK request in order to link existing model instances/resources using a second canonical URI or * a UNLINK request in order to remove a association/link between model instances/resources without deleting a model instance/resource. All these actions are directly mapped to the corresponding ActiveRecord calls on associations.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using TestProjectFromCsv.ValidationSteps; namespace TestProjectFromCsv { public class Program { public static void Main(string[] args) { try { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { var validation = new Validation( new ValidationStep[] { new CsvFileExists(options), new TemplateFilesExist(options) }); if (!validation.IsValid()) { foreach (string issue in validation.Issues) { Console.WriteLine(issue); } } else { Directory.CreateDirectory(Path.Combine(options.ProjectPath, options.ProjectName)); CsvFile csvFile = new CsvFile(options.CsvFile); IList<CsvRecord> testRecords = csvFile.Parse(); StringBuilder allTestProjects = new StringBuilder(100 + testRecords.Count * 100); <API key> testTemplateGen = new <API key>(Path.Combine(options.TemplatePath, "Test.tmp")); foreach (CsvRecord record in testRecords) { string filename = Path.Combine( options.ProjectPath, options.ProjectName, string.Format("{0}.GenericTest", record.TestName)); try { allTestProjects.AppendLine(string.Format("\t<None Include=\"{0}.GenericTest\">", record.TestName)); allTestProjects.AppendLine("\t\t<<API key>>Always</<API key>>"); allTestProjects.AppendLine("\t</None>"); testTemplateGen.GenerateFile(filename, new Dictionary<string, string>() { { "[[TestName]]" , record.TestName } , { "[[FullFilePath]]", filename } , { "[[TestGuid]]", Guid.NewGuid().ToString("D") } , { "[[CommandFullFilePath]]", Path.Combine(options.CommandPath, record.BatchFile)} }); } catch (Exception ex) { Console.WriteLine(string.Format("Error building file '{0}' : {1}", filename, ex.Message)); } } string <API key> = Path.Combine(options.ProjectPath, options.ProjectName, "Properties", "AssemblyInfo.cs"); try { Directory.CreateDirectory(Path.Combine(options.ProjectPath, options.ProjectName, "Properties")); <API key> assemblyInfoGen = new <API key>(Path.Combine(options.TemplatePath, "AssemblyInfo.cs.tmp")); assemblyInfoGen.GenerateFile(<API key>, new Dictionary<string, string>() { { "[[ProjectName]]" , options.ProjectName } , { "[[AssemblyGuid]]", Guid.NewGuid().ToString("D") } }); } catch (Exception ex) { Console.WriteLine(string.Format("Error building file '{0}' : {1}", <API key>, ex.Message)); } string projectFileName = Path.Combine(options.ProjectPath, options.ProjectName, string.Format("{0}.csproj", options.ProjectName)); try { <API key> projectFileGen = new <API key>(Path.Combine(options.TemplatePath, "ProjectTemplate.proj.tmp")); projectFileGen.GenerateFile(projectFileName, new Dictionary<string, string>() { { "[[ProjectGuid]]", Guid.NewGuid().ToString("B") } , { "[[ProjectName]]" , options.ProjectName } , { "[[Tests]]" , allTestProjects.ToString() } }); } catch (Exception ex) { Console.WriteLine(string.Format("Error building file '{0}' : {1}", projectFileName, ex.Message)); } Console.WriteLine("Done."); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } }
class AlbumsController < <API key> respond_to :html, :xml, :json attr_reader :current_album_type, :author_name <API key> def index @albums = Album.by_type params[:album_type] respond_with(@albums) end def show <API key> get_author_name if @current_album_type.name.singularize == 'Picture' @album_pictures = @album.pictures.paginate(:page => params[:page], :per_page => 12) elsif @current_album_type.name.singularize == 'Video' @album_videos = @album.videos.paginate(:page => params[:page], :per_page => 12) end respond_with(@album) end def new @album.album_type_id = params[:album_type] <API key> respond_with(@album) end def edit <API key> respond_with(@album) end def create @album.user_id = user_signed_in? ? current_user.id : 0 flash[:notice] = 'Album was successfully created.' if @album.save <API key> respond_with(@album) end def update @album.update_attributes(params[:album]) respond_with(@album) end def destroy @album.destroy flash[:notice] = 'Successfully destroyed album.' redirect_to albums_path(:album_type => @album.album_type_id) end private def <API key> @current_album_type = AlbumType.all.find { |album_type| album_type.id == @album.album_type_id } end def get_author_name @author_name = (@album.user_id > 0) \ ? User.find { |user| user.id == @album.user_id }.name \ : 'Anonymous' end end
var koyomi = require('../..').create(); var format = koyomi.format.bind(koyomi); var eq = require('assert').equal; koyomi.startMonth = 1; eq(format(20150101, 'CC'), '1'); eq(format(20150101, 'CC>0'), '1st'); eq(format(20150102, 'CC>0'), '2nd'); eq(format(20150103, 'CC>0'), '3rd'); eq(format(20150104, 'CC>0'), '4th'); eq(format(20150105, 'CC>0'), '5th'); eq(format(20150106, 'CC>0'), '6th'); eq(format(20150107, 'CC>0'), '7th'); eq(format(20150108, 'CC>0'), '8th'); eq(format(20150109, 'CC>0'), '9th'); eq(format(20150110, 'CC>0'), '10th'); eq(format(20150111, 'CC>0'), '11th'); eq(format(20150112, 'CC>0'), '12th'); eq(format(20150113, 'CC>0'), '13th'); eq(format(20150114, 'CC>0'), '14th'); eq(format(20150115, 'CC>0'), '15th'); eq(format(20150116, 'CC>0'), '16th'); eq(format(20150117, 'CC>0'), '17th'); eq(format(20150118, 'CC>0'), '18th'); eq(format(20150119, 'CC>0'), '19th'); eq(format(20150120, 'CC>0'), '20th'); eq(format(20150121, 'CC>0'), '21st'); eq(format(20150122, 'CC>0'), '22nd'); eq(format(20150123, 'CC>0'), '23rd'); eq(format(20150124, 'CC>0'), '24th'); eq(format(20150125, 'CC>0'), '25th'); eq(format(20150126, 'CC>0'), '26th'); eq(format(20150127, 'CC>0'), '27th'); eq(format(20150128, 'CC>0'), '28th'); eq(format(20150129, 'CC>0'), '29th'); eq(format(20150130, 'CC>0'), '30th'); eq(format(20150131, 'CC>0'), '31st'); eq(format(20150201, 'CC>0'), '32nd'); eq(format(20150202, 'CC>0'), '33rd'); eq(format(20150203, 'CC>0'), '34th'); eq(format(20150204, 'CC>0'), '35th'); eq(format(20150205, 'CC>0'), '36th'); eq(format(20150206, 'CC>0'), '37th'); eq(format(20150207, 'CC>0'), '38th'); eq(format(20150208, 'CC>0'), '39th'); eq(format(20150209, 'CC>0'), '40th'); eq(format(20150210, 'CC>0'), '41st'); eq(format(20150211, 'CC>0'), '42nd'); eq(format(20150212, 'CC>0'), '43rd'); eq(format(20150213, 'CC>0'), '44th'); eq(format(20150214, 'CC>0'), '45th'); eq(format(20150215, 'CC>0'), '46th'); eq(format(20150216, 'CC>0'), '47th'); eq(format(20150217, 'CC>0'), '48th'); eq(format(20150218, 'CC>0'), '49th'); eq(format(20150219, 'CC>0'), '50th'); eq(format(20150220, 'CC>0'), '51st'); eq(format(20150221, 'CC>0'), '52nd'); eq(format(20150222, 'CC>0'), '53rd'); eq(format(20150223, 'CC>0'), '54th'); eq(format(20150224, 'CC>0'), '55th'); eq(format(20150225, 'CC>0'), '56th'); eq(format(20150226, 'CC>0'), '57th'); eq(format(20150227, 'CC>0'), '58th'); eq(format(20150228, 'CC>0'), '59th'); eq(format(20150301, 'CC>0'), '60th'); eq(format(20150302, 'CC>0'), '61st'); eq(format(20150303, 'CC>0'), '62nd'); eq(format(20150304, 'CC>0'), '63rd'); eq(format(20150305, 'CC>0'), '64th'); eq(format(20150306, 'CC>0'), '65th'); eq(format(20150307, 'CC>0'), '66th'); eq(format(20150308, 'CC>0'), '67th'); eq(format(20150309, 'CC>0'), '68th'); eq(format(20150310, 'CC>0'), '69th'); eq(format(20150311, 'CC>0'), '70th'); eq(format(20150312, 'CC>0'), '71st'); eq(format(20150313, 'CC>0'), '72nd'); eq(format(20150314, 'CC>0'), '73rd'); eq(format(20150315, 'CC>0'), '74th'); eq(format(20150316, 'CC>0'), '75th'); eq(format(20150317, 'CC>0'), '76th'); eq(format(20150318, 'CC>0'), '77th'); eq(format(20150319, 'CC>0'), '78th'); eq(format(20150320, 'CC>0'), '79th'); eq(format(20150321, 'CC>0'), '80th'); eq(format(20150322, 'CC>0'), '81st'); eq(format(20150323, 'CC>0'), '82nd'); eq(format(20150324, 'CC>0'), '83rd'); eq(format(20150325, 'CC>0'), '84th'); eq(format(20150326, 'CC>0'), '85th'); eq(format(20150327, 'CC>0'), '86th'); eq(format(20150328, 'CC>0'), '87th'); eq(format(20150329, 'CC>0'), '88th'); eq(format(20150330, 'CC>0'), '89th'); eq(format(20150331, 'CC>0'), '90th'); eq(format(20150401, 'CC>0'), '91st'); eq(format(20150402, 'CC>0'), '92nd'); eq(format(20150403, 'CC>0'), '93rd'); eq(format(20150404, 'CC>0'), '94th'); eq(format(20150405, 'CC>0'), '95th'); eq(format(20150406, 'CC>0'), '96th'); eq(format(20150407, 'CC>0'), '97th'); eq(format(20150408, 'CC>0'), '98th'); eq(format(20150409, 'CC>0'), '99th'); eq(format(20150410, 'CC>0'), '100th'); eq(format(20150411, 'CC>0'), '101st'); eq(format(20150412, 'CC>0'), '102nd'); eq(format(20150413, 'CC>0'), '103rd'); eq(format(20150414, 'CC>0'), '104th'); eq(format(20150415, 'CC>0'), '105th'); eq(format(20150416, 'CC>0'), '106th'); eq(format(20150417, 'CC>0'), '107th'); eq(format(20150418, 'CC>0'), '108th'); eq(format(20150419, 'CC>0'), '109th'); eq(format(20150420, 'CC>0'), '110th'); eq(format(20150421, 'CC>0'), '111th'); eq(format(20150422, 'CC>0'), '112th'); eq(format(20150423, 'CC>0'), '113th'); eq(format(20150424, 'CC>0'), '114th'); eq(format(20150425, 'CC>0'), '115th'); eq(format(20150426, 'CC>0'), '116th'); eq(format(20150427, 'CC>0'), '117th'); eq(format(20150428, 'CC>0'), '118th'); eq(format(20150429, 'CC>0'), '119th'); eq(format(20150430, 'CC>0'), '120th'); eq(format(20150501, 'CC>0'), '121st'); eq(format(20150502, 'CC>0'), '122nd'); eq(format(20150503, 'CC>0'), '123rd'); eq(format(20150504, 'CC>0'), '124th'); eq(format(20150505, 'CC>0'), '125th'); eq(format(20150506, 'CC>0'), '126th'); eq(format(20150507, 'CC>0'), '127th'); eq(format(20150508, 'CC>0'), '128th'); eq(format(20150509, 'CC>0'), '129th'); eq(format(20150510, 'CC>0'), '130th'); eq(format(20150511, 'CC>0'), '131st'); eq(format(20150512, 'CC>0'), '132nd'); eq(format(20150513, 'CC>0'), '133rd'); eq(format(20150514, 'CC>0'), '134th'); eq(format(20150515, 'CC>0'), '135th'); eq(format(20150516, 'CC>0'), '136th'); eq(format(20150517, 'CC>0'), '137th'); eq(format(20150518, 'CC>0'), '138th'); eq(format(20150519, 'CC>0'), '139th'); eq(format(20150520, 'CC>0'), '140th'); eq(format(20150521, 'CC>0'), '141st'); eq(format(20150522, 'CC>0'), '142nd'); eq(format(20150523, 'CC>0'), '143rd'); eq(format(20150524, 'CC>0'), '144th'); eq(format(20150525, 'CC>0'), '145th'); eq(format(20150526, 'CC>0'), '146th'); eq(format(20150527, 'CC>0'), '147th'); eq(format(20150528, 'CC>0'), '148th'); eq(format(20150529, 'CC>0'), '149th'); eq(format(20150530, 'CC>0'), '150th'); eq(format(20150531, 'CC>0'), '151st'); eq(format(20150601, 'CC>0'), '152nd'); eq(format(20150602, 'CC>0'), '153rd'); eq(format(20150603, 'CC>0'), '154th'); eq(format(20150604, 'CC>0'), '155th'); eq(format(20150605, 'CC>0'), '156th'); eq(format(20150606, 'CC>0'), '157th'); eq(format(20150607, 'CC>0'), '158th'); eq(format(20150608, 'CC>0'), '159th'); eq(format(20150609, 'CC>0'), '160th'); eq(format(20150610, 'CC>0'), '161st'); eq(format(20150611, 'CC>0'), '162nd'); eq(format(20150612, 'CC>0'), '163rd'); eq(format(20150613, 'CC>0'), '164th'); eq(format(20150614, 'CC>0'), '165th'); eq(format(20150615, 'CC>0'), '166th'); eq(format(20150616, 'CC>0'), '167th'); eq(format(20150617, 'CC>0'), '168th'); eq(format(20150618, 'CC>0'), '169th'); eq(format(20150619, 'CC>0'), '170th'); eq(format(20150620, 'CC>0'), '171st'); eq(format(20150621, 'CC>0'), '172nd'); eq(format(20150622, 'CC>0'), '173rd'); eq(format(20150623, 'CC>0'), '174th'); eq(format(20150624, 'CC>0'), '175th'); eq(format(20150625, 'CC>0'), '176th'); eq(format(20150626, 'CC>0'), '177th'); eq(format(20150627, 'CC>0'), '178th'); eq(format(20150628, 'CC>0'), '179th'); eq(format(20150629, 'CC>0'), '180th'); eq(format(20150630, 'CC>0'), '181st'); eq(format(20150701, 'CC>0'), '182nd'); eq(format(20150702, 'CC>0'), '183rd'); eq(format(20150703, 'CC>0'), '184th'); eq(format(20150704, 'CC>0'), '185th'); eq(format(20150705, 'CC>0'), '186th'); eq(format(20150706, 'CC>0'), '187th'); eq(format(20150707, 'CC>0'), '188th'); eq(format(20150708, 'CC>0'), '189th'); eq(format(20150709, 'CC>0'), '190th'); eq(format(20150710, 'CC>0'), '191st'); eq(format(20150711, 'CC>0'), '192nd'); eq(format(20150712, 'CC>0'), '193rd'); eq(format(20150713, 'CC>0'), '194th'); eq(format(20150714, 'CC>0'), '195th'); eq(format(20150715, 'CC>0'), '196th'); eq(format(20150716, 'CC>0'), '197th'); eq(format(20150717, 'CC>0'), '198th'); eq(format(20150718, 'CC>0'), '199th'); eq(format(20150719, 'CC>0'), '200th'); eq(format(20150720, 'CC>0'), '201st'); eq(format(20150721, 'CC>0'), '202nd'); eq(format(20150722, 'CC>0'), '203rd'); eq(format(20150723, 'CC>0'), '204th'); eq(format(20150724, 'CC>0'), '205th'); eq(format(20150725, 'CC>0'), '206th'); eq(format(20150726, 'CC>0'), '207th'); eq(format(20150727, 'CC>0'), '208th'); eq(format(20150728, 'CC>0'), '209th'); eq(format(20150729, 'CC>0'), '210th'); eq(format(20150730, 'CC>0'), '211th'); eq(format(20150731, 'CC>0'), '212th'); eq(format(20150801, 'CC>0'), '213th'); eq(format(20150802, 'CC>0'), '214th'); eq(format(20150803, 'CC>0'), '215th'); eq(format(20150804, 'CC>0'), '216th'); eq(format(20150805, 'CC>0'), '217th'); eq(format(20150806, 'CC>0'), '218th'); eq(format(20150807, 'CC>0'), '219th'); eq(format(20150808, 'CC>0'), '220th'); eq(format(20150809, 'CC>0'), '221st'); eq(format(20150810, 'CC>0'), '222nd'); eq(format(20150811, 'CC>0'), '223rd'); eq(format(20150812, 'CC>0'), '224th'); eq(format(20150813, 'CC>0'), '225th'); eq(format(20150814, 'CC>0'), '226th'); eq(format(20150815, 'CC>0'), '227th'); eq(format(20150816, 'CC>0'), '228th'); eq(format(20150817, 'CC>0'), '229th'); eq(format(20150818, 'CC>0'), '230th'); eq(format(20150819, 'CC>0'), '231st'); eq(format(20150820, 'CC>0'), '232nd'); eq(format(20150821, 'CC>0'), '233rd'); eq(format(20150822, 'CC>0'), '234th'); eq(format(20150823, 'CC>0'), '235th'); eq(format(20150824, 'CC>0'), '236th'); eq(format(20150825, 'CC>0'), '237th'); eq(format(20150826, 'CC>0'), '238th'); eq(format(20150827, 'CC>0'), '239th'); eq(format(20150828, 'CC>0'), '240th'); eq(format(20150829, 'CC>0'), '241st'); eq(format(20150830, 'CC>0'), '242nd'); eq(format(20150831, 'CC>0'), '243rd'); eq(format(20150901, 'CC>0'), '244th'); eq(format(20150902, 'CC>0'), '245th'); eq(format(20150903, 'CC>0'), '246th'); eq(format(20150904, 'CC>0'), '247th'); eq(format(20150905, 'CC>0'), '248th'); eq(format(20150906, 'CC>0'), '249th'); eq(format(20150907, 'CC>0'), '250th'); eq(format(20150908, 'CC>0'), '251st'); eq(format(20150909, 'CC>0'), '252nd'); eq(format(20150910, 'CC>0'), '253rd'); eq(format(20150911, 'CC>0'), '254th'); eq(format(20150912, 'CC>0'), '255th'); eq(format(20150913, 'CC>0'), '256th'); eq(format(20150914, 'CC>0'), '257th'); eq(format(20150915, 'CC>0'), '258th'); eq(format(20150916, 'CC>0'), '259th'); eq(format(20150917, 'CC>0'), '260th'); eq(format(20150918, 'CC>0'), '261st'); eq(format(20150919, 'CC>0'), '262nd'); eq(format(20150920, 'CC>0'), '263rd'); eq(format(20150921, 'CC>0'), '264th'); eq(format(20150922, 'CC>0'), '265th'); eq(format(20150923, 'CC>0'), '266th'); eq(format(20150924, 'CC>0'), '267th'); eq(format(20150925, 'CC>0'), '268th'); eq(format(20150926, 'CC>0'), '269th'); eq(format(20150927, 'CC>0'), '270th'); eq(format(20150928, 'CC>0'), '271st'); eq(format(20150929, 'CC>0'), '272nd'); eq(format(20150930, 'CC>0'), '273rd'); eq(format(20151001, 'CC>0'), '274th'); eq(format(20151002, 'CC>0'), '275th'); eq(format(20151003, 'CC>0'), '276th'); eq(format(20151004, 'CC>0'), '277th'); eq(format(20151005, 'CC>0'), '278th'); eq(format(20151006, 'CC>0'), '279th'); eq(format(20151007, 'CC>0'), '280th'); eq(format(20151008, 'CC>0'), '281st'); eq(format(20151009, 'CC>0'), '282nd'); eq(format(20151010, 'CC>0'), '283rd'); eq(format(20151011, 'CC>0'), '284th'); eq(format(20151012, 'CC>0'), '285th'); eq(format(20151013, 'CC>0'), '286th'); eq(format(20151014, 'CC>0'), '287th'); eq(format(20151015, 'CC>0'), '288th'); eq(format(20151016, 'CC>0'), '289th'); eq(format(20151017, 'CC>0'), '290th'); eq(format(20151018, 'CC>0'), '291st'); eq(format(20151019, 'CC>0'), '292nd'); eq(format(20151020, 'CC>0'), '293rd'); eq(format(20151021, 'CC>0'), '294th'); eq(format(20151022, 'CC>0'), '295th'); eq(format(20151023, 'CC>0'), '296th'); eq(format(20151024, 'CC>0'), '297th'); eq(format(20151025, 'CC>0'), '298th'); eq(format(20151026, 'CC>0'), '299th'); eq(format(20151027, 'CC>0'), '300th'); eq(format(20151028, 'CC>0'), '301st'); eq(format(20151029, 'CC>0'), '302nd'); eq(format(20151030, 'CC>0'), '303rd'); eq(format(20151031, 'CC>0'), '304th'); eq(format(20151101, 'CC>0'), '305th'); eq(format(20151102, 'CC>0'), '306th'); eq(format(20151103, 'CC>0'), '307th'); eq(format(20151104, 'CC>0'), '308th'); eq(format(20151105, 'CC>0'), '309th'); eq(format(20151106, 'CC>0'), '310th'); eq(format(20151107, 'CC>0'), '311th'); eq(format(20151108, 'CC>0'), '312th'); eq(format(20151109, 'CC>0'), '313th'); eq(format(20151110, 'CC>0'), '314th'); eq(format(20151111, 'CC>0'), '315th'); eq(format(20151112, 'CC>0'), '316th'); eq(format(20151113, 'CC>0'), '317th'); eq(format(20151114, 'CC>0'), '318th'); eq(format(20151115, 'CC>0'), '319th'); eq(format(20151116, 'CC>0'), '320th'); eq(format(20151117, 'CC>0'), '321st'); eq(format(20151118, 'CC>0'), '322nd'); eq(format(20151119, 'CC>0'), '323rd'); eq(format(20151120, 'CC>0'), '324th'); eq(format(20151121, 'CC>0'), '325th'); eq(format(20151122, 'CC>0'), '326th'); eq(format(20151123, 'CC>0'), '327th'); eq(format(20151124, 'CC>0'), '328th'); eq(format(20151125, 'CC>0'), '329th'); eq(format(20151126, 'CC>0'), '330th'); eq(format(20151127, 'CC>0'), '331st'); eq(format(20151128, 'CC>0'), '332nd'); eq(format(20151129, 'CC>0'), '333rd'); eq(format(20151130, 'CC>0'), '334th'); eq(format(20151201, 'CC>0'), '335th'); eq(format(20151202, 'CC>0'), '336th'); eq(format(20151203, 'CC>0'), '337th'); eq(format(20151204, 'CC>0'), '338th'); eq(format(20151205, 'CC>0'), '339th'); eq(format(20151206, 'CC>0'), '340th'); eq(format(20151207, 'CC>0'), '341st'); eq(format(20151208, 'CC>0'), '342nd'); eq(format(20151209, 'CC>0'), '343rd'); eq(format(20151210, 'CC>0'), '344th'); eq(format(20151211, 'CC>0'), '345th'); eq(format(20151212, 'CC>0'), '346th'); eq(format(20151213, 'CC>0'), '347th'); eq(format(20151214, 'CC>0'), '348th'); eq(format(20151215, 'CC>0'), '349th'); eq(format(20151216, 'CC>0'), '350th'); eq(format(20151217, 'CC>0'), '351st'); eq(format(20151218, 'CC>0'), '352nd'); eq(format(20151219, 'CC>0'), '353rd'); eq(format(20151220, 'CC>0'), '354th'); eq(format(20151221, 'CC>0'), '355th'); eq(format(20151222, 'CC>0'), '356th'); eq(format(20151223, 'CC>0'), '357th'); eq(format(20151224, 'CC>0'), '358th'); eq(format(20151225, 'CC>0'), '359th'); eq(format(20151226, 'CC>0'), '360th'); eq(format(20151227, 'CC>0'), '361st'); eq(format(20151228, 'CC>0'), '362nd'); eq(format(20151229, 'CC>0'), '363rd'); eq(format(20151230, 'CC>0'), '364th'); eq(format(20151231, 'CC>0'), '365th'); eq(format(20150101, 'GG>0'), ''); eq(format(20000101, 'y>0'), '00th'); eq(format(20010101, 'y>0'), '01st');
# ImageHelper [![Version](https: [![License](https: [![Platform](https: [![Carthage compatible](https: Image Extensions for Swift 3.0 ![Sample Project Screenshot](https://raw.githubusercontent.com/melvitax/AFImageHelper/master/Screenshot.png?raw=true "Sample Project Screenshot") ## Usage To run the example project, clone or download the repo, and run. ## UIImageView Extension Image from a URL Swift // Fetches an image from a URL. If caching is set, it will be cached by NSCache for future queries. The cached image is returned if available, otherise the placeholder is set. When the image is returned, the closure gets called. func imageFromURL(url: String, placeholder: UIImage, fadeIn: Bool = true, closure: ((image: UIImage?) ## UIImage Extension Colors Swift // Creates an image from a solid color UIImage(color:UIColor, size:CGSize) // Creates an image from a gradient color UIImage(gradientColors:[UIColor], size:CGSize) // Applies a gradient overlay to an image func applyGradientColors(gradientColors: [UIColor], blendMode: CGBlendMode) -> UIImage // Creates an image from a radial gradient UIImage(startColor: UIColor, endColor: UIColor, <API key>: CGPoint, radius:Float, size:CGSize) Text Swift // Creates an image with a string of text UIImage(text: String, font: UIFont, color: UIColor, backgroundColor: UIColor, size:CGSize, offset: CGPoint) Screenshot Swift // Creates an image from a UIView UIImage(fromView view: UIView) Alpha and Padding Swift // Returns true if the image has an alpha layer func hasAlpha() -> Bool // Returns a copy(if needed) of the image with alpha layer func applyAlpha() -> UIImage? // Returns a copy of the image with a transparent border of the given size added around its edges func applyPadding(padding: CGFloat) -> UIImage? Crop and Resize Swift // Crops an image to a new rect func crop(bounds: CGRect) -> UIImage? // Crops an image to a centered square func cropToSquare() -> UIImage? { // Resizes an image func resize(size:CGSize, contentMode: UIImageContentMode = .ScaleToFill) -> UIImage? Circle and Rounded Corners Swift // Rounds corners of an image func roundCorners(cornerRadius:CGFloat) -> UIImage? // Rounds corners of an image with border func roundCorners(cornerRadius:CGFloat, border:CGFloat, color:UIColor) -> UIImage? // Rounds corners to a circle func <API key>() -> UIImage? // Rounds corners to a circle with border func <API key>(border border:CGFloat, color:UIColor) -> UIImage? Border Swift // Adds a border func applyBorder(border:CGFloat, color:UIColor) -> UIImage? Image Effects Swift // Applies a light blur effect to the image func applyLightEffect() -> UIImage? // Applies a extra light blur effect to the image func <API key>() -> UIImage? // Applies a dark blur effect to the image func applyDarkEffect() -> UIImage? // Applies a color tint to an image func applyTintEffect(tintColor: UIColor) -> UIImage? // Applies a blur to an image based on the specified radius, tint color saturation and mask image func applyBlur(blurRadius:CGFloat, tintColor:UIColor?, <API key>:CGFloat, maskImage:UIImage? = nil) -> UIImage? Screen Density Swift // To create an image that is Retina aware, use the screen scale as a multiplier for your size. You should also use this technique for padding or borders. let width = 140 * UIScreen.mainScreen().scale let height = 140 * UIScreen.mainScreen().scale let image = UIImage(named: "myImage")?.resize(CGSize(width: width, height: height))
import { apiGet, apiPut, apiDelete } from 'utils/api' import { flashError, flashSuccess } from 'utils/flash' import { takeLatest, takeEvery, call, put, select } from 'redux-saga/effects' import { filter, find, without, omit } from 'lodash' import { filesUrlSelector } from 'ducks/app' import { makeUploadsSelector } from 'ducks/uploads' import { <API key> } from 'ducks/filters' import { <API key> } from 'ducks/filePlacements' // Constants const GET_FILES = 'files/GET_FILES' const GET_FILES_SUCCESS = 'files/GET_FILES_SUCCESS' const UPLOADED_FILE = 'files/UPLOADED_FILE' const THUMBNAIL_GENERATED = 'files/THUMBNAIL_GENERATED' const DELETE_FILE = 'files/DELETE_FILE' const DELETE_FILE_FAILURE = 'files/DELETE_FILE_FAILURE' const UPDATE_FILE = 'files/UPDATE_FILE' export const UPDATE_FILE_SUCCESS = 'files/UPDATE_FILE_SUCCESS' export const UPDATE_FILE_FAILURE = 'files/UPDATE_FILE_FAILURE' const UPDATED_FILES = 'files/UPDATED_FILES' const REMOVED_FILES = 'files/REMOVED_FILES' const CHANGE_FILES_PAGE = 'files/CHANGE_FILES_PAGE' const MASS_SELECT = 'files/MASS_SELECT' const MASS_DELETE = 'files/MASS_DELETE' const MASS_CANCEL = 'files/MASS_CANCEL' // Actions export function getFiles (fileType, filesUrl, query = '') { return { type: GET_FILES, fileType, filesUrl, query } } export function getFilesSuccess (fileType, records, meta) { return { type: GET_FILES_SUCCESS, fileType, records, meta } } export function uploadedFile (fileType, file) { return { type: UPLOADED_FILE, fileType, file } } export function thumbnailGenerated (fileType, temporaryUrl, url) { return { type: THUMBNAIL_GENERATED, fileType, temporaryUrl, url } } export function updatedFiles (fileType, files) { return { type: UPDATED_FILES, fileType, files } } export function updateFile (fileType, filesUrl, file, attributes) { return { type: UPDATE_FILE, fileType, filesUrl, file, attributes } } export function deleteFile (fileType, filesUrl, file) { return { type: DELETE_FILE, fileType, filesUrl, file } } export function deleteFileFailure (fileType, file) { return { type: DELETE_FILE_FAILURE, fileType, file } } export function removedFiles (fileType, ids) { return { type: REMOVED_FILES, fileType, ids } } export function updateFileSuccess (fileType, file, response) { return { type: UPDATE_FILE_SUCCESS, fileType, file, response } } export function updateFileFailure (fileType, file) { return { type: UPDATE_FILE_FAILURE, fileType, file } } export function changeFilesPage (fileType, filesUrl, page) { return { type: CHANGE_FILES_PAGE, fileType, filesUrl, page } } export function massSelect (fileType, file, select) { return { type: MASS_SELECT, fileType, file, select } } export function massDelete (fileType) { return { type: MASS_DELETE, fileType } } export function massCancel (fileType) { return { type: MASS_CANCEL, fileType } } // Sagas function * getFilesPerform (action) { try { const filesUrl = `${action.filesUrl}?${action.query}` const response = yield call(apiGet, filesUrl) yield put(getFilesSuccess(action.fileType, response.data, response.meta)) } catch (e) { flashError(e.message) } } function * getFilesSaga () { // takeLatest automatically cancels any saga task started previously if it's still running yield takeLatest(GET_FILES, getFilesPerform) } function * updateFilePerform (action) { try { const { file, filesUrl, attributes } = action const fullUrl = `${filesUrl}/${file.id}` const data = { file: { id: file.id, attributes } } const response = yield call(apiPut, fullUrl, data) yield put(updateFileSuccess(action.fileType, action.file, response.data)) } catch (e) { flashError(e.message) yield put(updateFileFailure(action.fileType, action.file)) } } function * updateFileSaga () { yield takeEvery(UPDATE_FILE, updateFilePerform) } function * <API key> (action) { try { const filtersQuery = yield select(<API key>(action.fileType)) let query = `page=${action.page}` if (filtersQuery) { query = `${query}&${filtersQuery}` } yield put(getFiles(action.fileType, action.filesUrl, query)) } catch (e) { flashError(e.message) } } function * changeFilesPageSaga () { yield takeLatest(CHANGE_FILES_PAGE, <API key>) } function * massDeletePerform (action) { try { const { massSelectedIds } = yield select(<API key>(action.fileType)) const filesUrl = yield select(filesUrlSelector) const fullUrl = `${filesUrl}/mass_destroy?ids=${massSelectedIds.join(',')}` const res = yield call(apiDelete, fullUrl) if (res.error) { flashError(res.error) } else { flashSuccess(res.data.message) yield put(removedFiles(action.fileType, massSelectedIds)) yield put(massCancel(action.fileType)) } } catch (e) { flashError(e.message) } } function * massDeleteSaga () { yield takeLatest(MASS_DELETE, massDeletePerform) } function * deleteFilePerform (action) { try { const res = yield call(apiDelete, `${action.filesUrl}/${action.file.id}`) if (res.error) { flashError(res.error) } else { yield put(removedFiles(action.fileType, [action.file.id])) } } catch (e) { flashError(e.message) } } function * deleteFileSaga () { yield takeLatest(DELETE_FILE, deleteFilePerform) } export const filesSagas = [ getFilesSaga, updateFileSaga, changeFilesPageSaga, massDeleteSaga, deleteFileSaga ] // Selectors export const <API key> = (fileType) => (state) => { return { loading: state.files[fileType] && state.files[fileType].loading, loaded: state.files[fileType] && state.files[fileType].loaded, massSelecting: state.files[fileType].massSelectedIds.length > 0 } } export const <API key> = (fileType) => (state) => { return state.files[fileType] && state.files[fileType].loaded } export const <API key> = (fileType) => (state) => { const base = state.files[fileType] || <API key> return { massSelectedIds: base.massSelectedIds, <API key>: base.<API key> } } export const makeFilesSelector = (fileType) => (state) => { const base = state.files[fileType] || <API key> const selected = base.massSelectedIds return base.records.map((file) => { if (file.id && selected.indexOf(file.id) !== -1) { return { ...file, massSelected: true } } else { return file } }) } export const <API key> = (fileType) => (state) => { const uploads = makeUploadsSelector(fileType)(state) let files if (uploads.uploadedIds.length) { files = makeFilesSelector(fileType)(state).map((file) => { if (uploads.uploadedIds.indexOf(file.id) === -1) { return file } else { return { ...file, attributes: { ...file.attributes, freshlyUploaded: true } } } }) } else { files = makeFilesSelector(fileType)(state) } return [ Object.values(uploads.records).map((upload) => ({ ...upload, attributes: { ...upload.attributes, uploading: true } })), files ] } export const <API key> = (fileType, selectedIds) => (state) => { const all = <API key>(fileType)(state) return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1) } export const <API key> = (fileType) => (state) => { const all = <API key>(fileType)(state) const selectedIds = <API key>(fileType)(state) return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1) } export const <API key> = (fileType) => (state) => { const base = state.files[fileType] || <API key> return base.pagination } export const <API key> = (fileType) => (state) => { const base = state.files[fileType] || <API key> return base.reactType } export const <API key> = (fileType) => (state) => { return <API key>(fileType)(state) === 'image' } // State const <API key> = { loading: false, loaded: false, records: [], massSelectedIds: [], <API key>: [], reactType: 'document', pagination: { page: null, pages: null } } const initialState = {} // Reducer function filesReducer (rawState = initialState, action) { const state = rawState if (action.fileType && !state[action.fileType]) { state[action.fileType] = { ...<API key> } } switch (action.type) { case GET_FILES: return { state, [action.fileType]: { state[action.fileType], loading: true } } case GET_FILES_SUCCESS: return { state, [action.fileType]: { state[action.fileType], records: action.records, loading: false, loaded: true, pagination: omit(action.meta, ['react_type']), reactType: action.meta.react_type } } case UPLOADED_FILE: return { state, [action.fileType]: { state[action.fileType], records: [action.file, ...state[action.fileType].records] } } case THUMBNAIL_GENERATED: { return { state, [action.fileType]: { state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.attributes.thumb !== action.temporaryUrl) return record return { record, attributes: { record.attributes, thumb: action.url } } }) } } } case UPDATE_FILE: return { state, [action.fileType]: { state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { record, attributes: { record.attributes, action.attributes, updating: true } } } else { return record } }) } } case UPDATE_FILE_SUCCESS: return { state, [action.fileType]: { state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.response.id) { return action.response } else { return record } }) } } case UPDATE_FILE_FAILURE: return { state, [action.fileType]: { state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { ...action.file } } else { return record } }) } } case UPDATED_FILES: return { state, [action.fileType]: { state[action.fileType], records: state[action.fileType].records.map((record) => { const found = find(action.files, { id: record.id }) return found || record }) } } case MASS_SELECT: { if (!action.file.id) return state let massSelectedIds = state[action.fileType].massSelectedIds let <API key> = state[action.fileType].<API key> if (action.select) { massSelectedIds = [...massSelectedIds, action.file.id] if (action.file.attributes.<API key>) { <API key> = [...<API key>, action.file.id] } } else { massSelectedIds = without(massSelectedIds, action.file.id) if (action.file.attributes.<API key>) { <API key> = without(<API key>, action.file.id) } } return { state, [action.fileType]: { state[action.fileType], massSelectedIds, <API key> } } } case MASS_CANCEL: return { state, [action.fileType]: { state[action.fileType], massSelectedIds: [] } } case REMOVED_FILES: { const originalLength = state[action.fileType].records.length const records = state[action.fileType].records.filter((record) => action.ids.indexOf(record.id) === -1) return { state, [action.fileType]: { state[action.fileType], records, pagination: { state[action.fileType].pagination, to: records.length, count: state[action.fileType].pagination.count - (originalLength - records.length) } } } } case DELETE_FILE: return { state, [action.fileType]: { state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { record, _destroying: true } } else { return record } }) } } case DELETE_FILE_FAILURE: return { state, [action.fileType]: { state[action.fileType], records: state[action.fileType].records.map((record) => { if (record.id === action.file.id) { return { ...action.file } } else { return record } }) } } default: return state } } export default filesReducer
using ShiftCaptain.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Security.Principal; using System.Web; using System.Web.Security; namespace ShiftCaptain.Infrastructure { public static class Authentication { public static Boolean Login(EmailNPass user, ref String errorMessage) { errorMessage = ""; var db = new <API key>(); var validUser = db.Users.FirstOrDefault(u => u.EmailAddress == user.EmailAddress); if (validUser != null) { if (validUser.Locked && validUser.LastLogin.HasValue && (validUser.LastLogin.Value <= DateTime.Now.AddMinutes(-30))) { validUser.Locked = false; validUser.NumTries = 0; } int numTries = 4; Int32.TryParse(<API key>.AppSettings["NumTries"], out numTries); if (validUser.NumTries++ > numTries) { validUser.Locked = true; } if (!validUser.Locked && validUser.Pass == user.Pass) { validUser.NumTries = 0; if (validUser.IsActive) { var ticket = new Forms<API key>(String.Format("{0}|{1}", validUser.Id, validUser.EmailAddress), true, 30); var encr = FormsAuthentication.Encrypt(ticket); //FormsAuthentication.SetAuthCookie("authCk", false); SessionManager.UserId = validUser.Id; SessionManager.token = encr; SessionManager.GetVersion(); return true; } } validUser.LastLogin = DateTime.Now; db.Entry(validUser).State = EntityState.Modified; db.SaveChanges(); if (validUser.Locked) { errorMessage = "Your account is locked. Please wait 30 minutes or contact the system administrator."; return false; } } errorMessage = "Email Address or Password is invalid."; return false; } public static void LogOff() { SessionManager.Clear(); } public static bool Authenticate(HttpContextBase ctx) { if (SessionManager.token != null) { var ticket = FormsAuthentication.Decrypt(SessionManager.token); if (ticket != null && !ticket.Expired) { ctx.User = new GenericPrincipal(new FormsIdentity(ticket), new string[] { }); var nTicket = new Forms<API key>(ticket.Name, true, 30);//Everytime you click a new page, clock restarts SessionManager.<API key>.Encrypt(nTicket); } } return ctx.User.Identity.IsAuthenticated; } } }
# Angular.js Enterprise Edition Lazy Load Boilerplate > **TODO:** review and update This boilerplate (seed project, starting project) helps you build large scale [Angular.js](https: <!-- toc --> * [Overview](#overview) * [Installation Guide](#installation-guide) * [Prerequisites](#prerequisites) * [Use Guide](#use-guide) * [Tools for Development Workflow](#<API key>) * [Build](#build) * [Code Generation](#code-generation) * [Development](#development) * [Distribuction Preview](#<API key>) * [Tests](#tests) * [Tools Configuration](#tools-configuration) * [Tips](#tips) * [Known Issues](#known-issues) * [Publishing tool for GitHub gh-pages](#<API key>) * [Directories Structure](#<API key>) * [Development](#development) * [Publishing](#publishing) * [Project](#project) <!-- toc stop --> ## Overview FrontEnd Boilerplate project with development and publishing tools (for GitHub gh-pages) * **Important**: to define a better communication between frontend and backend (server), please consider follow the given proposal [REST URL Design](rest_url_design.md) ## Installation Guide Enter the following commands in the terminal bash $ git clone https://github.com/erkobridee/<API key>.git $ cd <API key> $ cd tools $ npm run setup $ cd .. $ cd publisher $ npm install Prerequisites * Must have [Git](http://git-scm.com/) installed * Must have [node.js (at least v0.10.0)](http://nodejs.org/) installed with npm (Node Package Manager) * Must have [Grunt](https://github.com/gruntjs/grunt) node package installed globally ## Use Guide > `./` means root directoy Tools for Development Workflow > Inside `./tools` directory, available grunt.js commands * `grunt` >> (default task) that will execute lintspaces, jshint to verify and ensure js code quality and cleanup build and dist directories > **Attention:** the following task **lintspaces** will verify the patterns insides files according rules inside `.editorconfig` in the root directory # Build * `grunt build:dev` >> prepare files for development, inside `./tools/.temp` directory * `grunt build:prod` >> cleanup build directories, execute test's and then prepare files for distribution / production, inside `./dist` directory # Code Generation * `grunt generate` >> ask for which code generate option you want, values for the chosen and finally output destination # Development * `grunt dev:livereload` >> first will execute `build:dev` task, after that start web server with livereload support and watch changes on files *.html, .css and .js*, that will update all browsers and devices connect to server * `grunt dev:livereload:proxy` >> beyond the `dev:livereload` tasks, this task create a proxy to route requests to other server based on given context, for example `/rest` * `grunt dev:sync` >> first will execute `build:dev` task, after that start web server with browser-sync support and watch changes on files *.html, .css and .js*, that will update all browsers and devices connect to server and sync data and navigation * `grunt dev:sync:proxy` >> beyond the `dev:sync` tasks, this task create a proxy to route requests to other server based on given context, for example `/rest` ## alias * `grunt dev` >> alias to `grunt dev:livereload` * `grunt dev:proxy` >> alias to `grunt dev:livereload:proxy` # Distribuction Preview * `grunt dist` >> first will execute `build:prod` task, after that start web server with generated files * `grunt dist:proxy` >> first will execute `build:prod` task, after that start web server with generated files + proxy to route requests to other server based on given context, for example `/rest` * `grunt dist:sync` >> first will execute `build:prod` task, after that start web server with generated files + browser-sync to synchronize data and navigation * `grunt dist:sync:proxy` >> first will execute `build:prod` task, after that start web server with generated files + browser-sync to synchronize data and navigation + proxy to route requests to other server based on given context, for example `/rest` # Tests ## Unit Tests * `grunt ci` - cleanup build directories and then execute `karma:ci` grunt task that run test's * `grunt reports` - cleanup build directories, execute `karma:reports` grunt task that generate coverage and jasmine html reports and then open reports output directory * `grunt specs` - first generate coverage and jasmine html reports, start karma with watch process and webserver with livereload watching reports html's > **Attention:** if you want to run with dev flow, run first dev task (ex.: `grunt dev`) in one terminal and in other terminal run `grunt specs` ## e2e (end-to-end) - Selenium Tests * `grunt e2e` - execute `build:prod`, start web server with proxy support and then run e2e test's with Protractor * `grunt protractor` - run only e2e test's > **Attention:** need to run with dev flow, run first (ex.: `grunt dev`) in one terminal and in other terminal run `grunt protractor` or specific test's suite `grunt protractor --suite bookmarks` (Protractor configs: `./tools/config.protractor.js`) # Tools Configuration * Tools global configs: `./tools/config.js` which is used on `./tools/helpers/grunt/config/project.js` * Proxy routing configuration ( see: `var backend = { ...` ) * Proxy Grunt.js Plugin : [grunt-connect-proxy](https: * To center and make more easy to manage Grunt.js tasks configurations was defined the file `./tools/helpers/grunt/config/project.js` # Tips * If you use Sublime Text, check this out: * [[GitHub] the-front / <API key>](https://github.com/the-front/<API key>) - Sublime Text 2 / 3 Snippets and Completions for Angular.js, Angular UI Router and Require.js (focused to the <API key> code) * [[GitHub] caiogondim / <API key>](https://github.com/caiogondim/<API key>) - Snippets for Jasmine, the BDD framework for testing JavaScript, in Sublime Text # Known Issues ## Mac OSX * [How do I fix the error EMFILE: Too many opened files? | grunt-contrib-watch - GitHub](https://github.com/gruntjs/grunt-contrib-watch#<API key>) * [[SuperUser] How to change default ulimit values in Mac OS X 10.6?](https://superuser.com/questions/261023/<API key>) This is because of your system's max opened file limit. For OSX the default is very low (256). Temporarily increase your limit with `ulimit -n 2048`, the number being the new max limit. In some versions of OSX the above solution doesn't work. In that case try `launchctl limit maxfiles 2048 2048` and restart your terminal. ## Windows * Behind a NTLM proxy * run `npm install` two times, to install all dependencies ## Protracto & Selenium - Firefox dos not work * When you uptade to last Firefox version and Selenium stop to work with * **Solution:** `keep selenium server jar always up to date` Publishing tool for GitHub gh-pages > Inside `./publisher` directory, available grunt.js commands * `grunt init` >> do project clone from GitHub inside `./publisher/local/gh-pages` directory and checkout `gh-pages` branch, which is used to update remote `gh-pages` branch on GitHub > Execute this command at once, before the following commands * `grunt publish` >> this task will invoke `grunt build:prod` command inside `./tools` directory, then copy generated files from `./dist` to `./publisher/local/gh-pages`, commit files and finally push to `gh-pages` branch on GitHub * `grunt publish:dev` - this task will copy files from `./src` to `./publisher/local/gh-pages`, commit files and finally push to `gh-pages` branch on GitHub ## Directories Structure ./ /src >> project source /tools >> development tools /publisher >> publisher tool Development /tools /helpers /lib >> auxiliary processing /scripts >> automation processing /<API key> jasmine.html >> jasmine html report template /grunt /config >> configuration files to grunt.js tasks /tasks >> custom grunt.js tasks /tests require.config.js >> load application files and test's specs for Karma Runner /templates >> templates files for grunt.js generate task config.js >> global configs for grunt.js tasks config.karma.js >> referenced on config.js config.protractor.js >> config for Protractor Gruntfile.js >> main grunt.js configuration file package.json >> node.js 'tools' project and dependencies configuration Publishing /publisher /helpers /grunt /config >> configuration files to grunt.js tasks /tasks >> custom grunt.js tasks Gruntfile.js >> main grunt.js configuration file package.json >> node.js 'publisher' project and dependencies configuration Project > The directories structure of the project is organized following the BDD (Behavior Driven Development [wikipedia](https://en.wikipedia.org/wiki/<API key>)) concept, where all one "use case" (behavior) is inside the same directory, which this allow code and behavior reuse /src /app /bookmarks >> CRUD example with mock >> package.js map all js files in the directory this file is referenced as a dependency on /app/main/module.js /mock >> package.js map all js files in the directory this file is referenced as a dependency on /require.mock.load.js /tests/unit >> package.js map all js files in the directory this file is referenced as a dependency on /require.unit.load.js /tests/e2e >> files loaded from Protractor config specs regexp /about >> module referenced as a dependency on /app/main/module.js /help >> module referenced as a dependency on /app/main/module.js /home >> module referenced as a dependency on /app/main/module.js /main >> main application module where other modules are charged on /module.js >> package.js map all js files in the directory this file is referenced as a dependency on /ng.app.js /shared /fallback >> scripts for Internet Explorer /fend >> set of commons and useful reusable modules across projects and other modules /mock >> module that enables emulate the backend /less /bootstrap default.less >> default theme and configuration for Bootstrap, which is imported in /less/app.less >> other configurations and components /less app.less >> map .less files that generate /styles/app.css /styles app.css /vendor >> third party libraries (ex.: twitter bootstrap, jquery, angular.js, ...) require.mock.load.js >> list and reference all mocks to be loaded this file is referenced as a dependency on /ng.app.js require.unit.load.js >> list and reference all tests unit to be loaded this file is referenced as dependency on ./tools/helpers/tests/require.config.js ng.app.js >> where start Angular.js application require.config.js >> main configuration file to load all needed JavaScripts files to execute /ng.app.js index.html
;;; keydown-counter.asm -- Count keydown form P3.2 and outputs in P1 using LED ;; Author: Zeno Zeng <zenoofzeng@gmail.com> ;; Time-stamp: <2014-12-25 21:56:36 Zeno Zeng> ;;; Commentary: ;; Count keydown from P3.2 then ouputs using 8bit P1 (in LED) ;;; Code: ORG 0000H AJMP INIT ORG 0003H AJMP ONKEYDOWN INIT: CLR A MOV TCON, #01H ; IT0 = 1 MOV IE, #81H ; EX0P3.2 EA = 1, EX0 = 1 LISTENING: SJMP LISTENING ONKEYDOWN: INC A MOV P1, A RETI EXIT: END
var self = module.exports; self = (function(){ self.debug = true; self.prefix = '/kaskade'; self.ssl = false; /*{ key: {PEM}, cert: {PEM} }*/ self.port = 80; self.host = '0.0.0.0'; self.onConnectionClose = new Function(); self.redis = false; /*{ host: {String}, port: {Number}, options: {Object} }*/ self.init = function(cfg){ for(var c in cfg){ if(c in this) this[c] = cfg[c]; } }; })();
# encoding: utf-8 require_relative "qipowl/version" require_relative "qipowl/constants" require_relative "qipowl/core/mapper" require_relative "qipowl/core/ruler" require_relative "qipowl/core/bowler" require_relative "qipowl/bowlers/html" require_relative "qipowl/bowlers/i_sp_ru" #require_relative "qipowl/bowlers/cmd" #require_relative "qipowl/bowlers/yaml" Encoding.default_external = Encoding::UTF_8 Encoding.default_internal = Encoding::UTF_8 module Qipowl extend self # A wrapper for the configuration block def configure &block instance_eval(&block) end def [](key) config[key.to_sym] end private def set(key, value) config[key.to_sym] = value end def add(key, value) config[key.to_sym] = [*config[key.to_sym]] << value end def config @config ||= Hash.new end def method_missing(sym, *args) if sym.to_s =~ /(.+)=$/ config[$1.to_sym] = args.first else config[sym.to_sym] end end end Qipowl::configure do set :bowlers, File.expand_path(File.join(__dir__, '..', 'config', 'bowlers')) end class Qipowl::Html attr_reader :bowler def self.parse s (@bowler ||= Qipowl::Ruler.new_bowler "html").execute s end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Retina</title> <link rel="stylesheet" href="http://pic.lvmama.com/min/index.php?f=/styles/v6/header_new.css"> <link rel="stylesheet" href="css/monokai-sublime.css"> <link rel="stylesheet" href="css/docs.css"> <link rel="stylesheet" href="css/retina.css"> </head> <body> <header id="header"> <div id="logo"> NOVA </div> </header> <menu id="nav"> <li><a href="./"></a></li> </menu> <div id="everything"> <h1>Retina</h1> <h2></h2> <blockquote> Ctrl + = 200% </blockquote> <h3></h3> <section> <div class="lvmama-logo"></div> </section> <h3></h3> <section> <div class="lvmama-logo lvmama-logo-retina"></div> </section> <pre> <code> .lvmama-logo { background-image: url(../img/logo-61.png); width: 330px; height: 70px; } @media only screen and (-<API key>: 1.5), only screen and (<API key>: 1.5), only screen and (<API key>: 1.5) { .lvmama-logo-retina { background-image: url(../img/logo-61@2x.png); background-size: 100%; } } </code> </pre> <h2></h2> <!-- start --> <div class="ds-thread" data-thread-key="retina" data-title="NOVA" data-url="http: <!-- end --> </div> <script src="js/jquery-1.12.1.js"></script> <script src="js/highlight.pack.js"></script> <script src="js/navigation.js"></script> </body> </html>
// AppDelegate.h // testspinner #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <<API key>> @property (strong, nonatomic) UIWindow *window; @end
<html><body> <h4>Windows 10 x64 (19041.264)</h4><br> <h2>_PPM_IDLE_STATES</h2> <font face="arial"> +0x000 InterfaceVersion : UChar<br> +0x001 IdleOverride : UChar<br> +0x002 <API key> : UChar<br> +0x003 <API key> : UChar<br> +0x004 <API key> : UChar<br> +0x005 <API key> : UChar<br> +0x006 IdleDurationLimited : UChar<br> +0x007 IdleCheckLimited : UChar<br> +0x008 StrictVetoBias : UChar<br> +0x00c <API key> : Uint4B<br> +0x010 TargetState : Uint4B<br> +0x014 ActualState : Uint4B<br> +0x018 OldState : Uint4B<br> +0x01c OverrideIndex : Uint4B<br> +0x020 ProcessorIdleCount : Uint4B<br> +0x024 Type : Uint4B<br> +0x028 LevelId : Uint8B<br> +0x030 ReasonFlags : Uint2B<br> +0x038 InitiateWakeStamp : Uint8B<br> +0x040 PreviousStatus : Int4B<br> +0x044 <API key> : Uint4B<br> +0x048 <API key> : <a href="./_KAFFINITY_EX.html">_KAFFINITY_EX</a><br> +0x0f0 <API key> : <a href="./_KAFFINITY_EX.html">_KAFFINITY_EX</a><br> +0x198 IdlePrepare : Ptr64 void <br> +0x1a0 IdlePreExecute : Ptr64 long <br> +0x1a8 IdleExecute : Ptr64 long <br> +0x1b0 IdlePreselect : Ptr64 unsigned long <br> +0x1b8 IdleTest : Ptr64 unsigned long <br> +0x1c0 <API key> : Ptr64 unsigned long <br> +0x1c8 IdleComplete : Ptr64 void <br> +0x1d0 IdleCancel : Ptr64 void <br> +0x1d8 IdleIsHalted : Ptr64 unsigned char <br> +0x1e0 IdleInitiateWake : Ptr64 unsigned char <br> +0x1e8 PrepareInfo : <a href="./<API key>.html"><API key></a><br> +0x240 DeepIdleSnapshot : <a href="./_KAFFINITY_EX.html">_KAFFINITY_EX</a><br> +0x2e8 Tracing : Ptr64 <a href="./<API key>.html"><API key></a><br> +0x2f0 CoordinatedTracing : Ptr64 <a href="./<API key>.html"><API key></a><br> +0x2f8 ProcessorMenu : <a href="./_PPM_SELECTION_MENU.html">_PPM_SELECTION_MENU</a><br> +0x308 CoordinatedMenu : <a href="./_PPM_SELECTION_MENU.html">_PPM_SELECTION_MENU</a><br> +0x318 <API key> : <a href="./<API key>.html"><API key></a><br> +0x330 State : [1] <a href="./_PPM_IDLE_STATE.html">_PPM_IDLE_STATE</a><br> </font></body></html>
# coding=utf-8 from setuptools import setup from Cython.Build import cythonize setup( name="cyfib", ext_modules=cythonize('cyfib.pyx', compiler_directives={'embedsignature': True}), )
package org.eggermont.hm.cluster; import cern.colt.matrix.DoubleFactory1D; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; public class ClusterFactory { private final DoubleMatrix2D x; private final DoubleMatrix1D blocks; private final DoubleMatrix1D vMin; private final DoubleMatrix1D vMax; private final int ndof; public ClusterFactory(int d, int nidx, int ndof) { this.ndof = ndof; this.blocks = DoubleFactory1D.dense.make(d * nidx); this.x = blocks.like2D(nidx, d); this.vMin = DoubleFactory1D.dense.make(d); this.vMax = DoubleFactory1D.dense.make(d); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using SharpDeflate; using vtortola.WebSockets; using vtortola.WebSockets.Rfc6455; namespace RohBot { public sealed class WebSocketServer<TClient> : IDisposable where TClient : WebSocketClient, new() { private class ClientHandle : IDisposable { private Action _dispose; public ClientHandle(Action dispose) { if (dispose == null) throw new <API key>(nameof(dispose)); _dispose = dispose; } public void Dispose() { _dispose?.Invoke(); _dispose = null; } } private <API key> _cts; private WebSocketListener _listener; private object _clientsSync; private List<TClient> _clients; private IReadOnlyList<TClient> _clientsCache; public WebSocketServer(IPEndPoint endpoint) { var options = new <API key> { PingTimeout = TimeSpan.FromSeconds(30) }; _cts = new <API key>(); _listener = new WebSocketListener(endpoint, options); _clientsSync = new object(); _clients = new List<TClient>(); var rfc6455 = new <API key>(_listener); rfc6455.MessageExtensions.RegisterExtension(new <API key>()); _listener.Standards.RegisterStandard(rfc6455); _listener.Start(); ListenAsync(); } public void Dispose() { _cts.Cancel(); _listener.Dispose(); } public IReadOnlyList<TClient> Clients { get { lock (_clientsSync) { return _clientsCache ?? (_clientsCache = _clients.ToList().AsReadOnly()); } } } private async void ListenAsync() { while (_listener.IsStarted) { WebSocket websocket; try { websocket = await _listener.<API key>(_cts.Token).ConfigureAwait(false); if (websocket == null) continue; } catch (Exception e) { Program.Logger.Error("Failed to accept websocket connection", e); continue; } var client = new TClient(); var clientHandle = new ClientHandle(() => { lock (_clientsSync) { _clients.Remove(client); _clientsCache = null; } }); client.Open(clientHandle, websocket, _cts.Token); lock (_clientsSync) { _clients.Add(client); _clientsCache = null; } } } } }
/* eslint-disable no-undef */ const cukeBtnSubmit = '//button[@data-cuke="save-item"]'; const cukeInpSize = '//input[@data-cuke="size"]'; const cukeInpTitle = '//input[@data-cuke="title"]'; const cukeInpContent = '//textarea[@data-cuke="content"]'; const cukeSize = '//x-cuke[@id="size"]'; const cukeTitle = '//x-cuke[@id="title"]'; const cukeContent = '//x-cuke[@id="content"]'; /* const cukeHrefEdit = '//a[@data-cuke="edit-ite"]'; const cukeHrefDelete = '//a[@data-cuke="delete-item"]'; */ const cukeInvalidSize = '//span[@class="help-block error-block"]'; let size = ''; let title = ''; let content = ''; module.exports = function () { // Scenario: Create a new widget this.Given(/^I have opened the 'add widgets' page : "([^"]*)"$/, function (_url) { browser.setViewportSize({ width: 1024, height: 480 }); browser.timeouts('implicit', 60000); browser.timeouts('page load', 60000); browser.url(_url); server.call('_widgets.wipe'); }); this.When(/^I create a "([^"]*)" millimetre "([^"]*)" item with text "([^"]*)",$/, function (_size, _title, _content) { size = _size; title = _title; content = _content; browser.waitForEnabled( cukeBtnSubmit ); browser.setValue(cukeInpTitle, title); browser.setValue(cukeInpSize, size); browser.setValue(cukeInpContent, content); browser.click(cukeBtnSubmit); }); this.Then(/^I see a new record with the same title, size and contents\.$/, function () { expect(browser.getText(cukeSize)).toEqual(size + ' millimetres.'); expect(browser.getText(cukeTitle)).toEqual(title); expect(browser.getText(cukeContent)).toEqual(content); }); // Scenario: Verify field validation this.Given(/^I have opened the widgets list page : "([^"]*)"$/, function (_url) { browser.setViewportSize({ width: 1024, height: 480 }); browser.<API key>(1000); browser.url(_url); }); /* let link = ''; this.Given(/^I choose to edit the "([^"]*)" item,$/, function (_widget) { link = '//a[@data-cuke="' + _widget + '"]'; browser.waitForExist( link ); browser.click(link); browser.waitForEnabled( cukeHrefEdit ); browser.click(cukeHrefEdit); }); */ this.When(/^I set 'Size' to "([^"]*)"$/, function (_size) { browser.setValue(cukeInpSize, _size); }); this.Then(/^I see the size validation hint "([^"]*)"\.$/, function (_message) { expect(browser.getText(cukeInvalidSize)).toEqual(_message); }); // Scenario: Fail to delete widget let widget = ''; this.Given(/^I choose to view the "([^"]*)" item,$/, function (_widget) { widget = _widget; const cukeHrefWidget = `//a[@data-cuke="${widget}"]`; browser.waitForEnabled( cukeHrefWidget ); browser.click( cukeHrefWidget ); }); /* let href = null; this.When(/^I decide to delete the item,$/, function () { href = cukeHrefDelete; browser.waitForExist( href ); }); this.Then(/^I see it is disabled\.$/, function () { expect(browser.isEnabled( href )).toBe(true); }); */ // Scenario: Unable to update widget /* this.When(/^I attempt to edit the item,$/, function () { href = cukeHrefEdit; browser.waitForExist( href ); }); */ // Scenario: Prohibited from add and from update this.Given(/^I have opened the widgets editor page : "([^"]*)"$/, function (_url) { browser.setViewportSize({ width: 1024, height: 480 }); browser.timeouts('implicit', 60000); browser.timeouts('page load', 60000); browser.url(_url); }); /* this.Then(/^I see the warning "([^"]*)"$/, function (_warning) { expect(_warning).toEqual(browser.getText(cukeWarning)); }); */ // Scenario: Hide widget /* this.Given(/^I have elected to "([^"]*)" the "([^"]*)" item\.$/, function (_cmd, _widget) { link = '//a[@data-cuke="' + _widget + '"]'; browser.waitForEnabled( link ); browser.click(link); let cukeHrefCmd = '//a[@data-cuke="' + _cmd + '-widget"]'; browser.waitForEnabled( cukeHrefCmd ); browser.click( cukeHrefCmd ); }); */ /* this.Then(/^I no longer see that widget record\.$/, function () { browser.waitForEnabled( cukeWidgetsList ); let item = browser.elements(link); expect(item.value.length).toEqual(0); }); */ };
<!DOCTYPE html> <?php include("initial-header.php"); include("config.php"); include('swift/lib/swift_required.php'); $error = ""; if($_SERVER["REQUEST_METHOD"] == "POST") { // username and password sent from form $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); $myusername = <API key>($db,$_POST['username']); $my<API key>($db,$_POST['password']); $sql = "SELECT email_id, Password, salt FROM login WHERE email_id='$myusername' "; $result = mysqli_query($db,$sql); $row = mysqli_fetch_array($result,MYSQLI_ASSOC); $count = mysqli_num_rows($result); // If email ID exists in the login table if($count == 1) { $salt = $row["salt"]; $password_hash = $row["Password"]; $myhash = hash('sha512', $mypassword . $salt); //If the password is correct if($password_hash == $myhash){ $_SESSION['login_user'] = $myusername; $random = rand(100000,999999); $sql2 = "UPDATE login SET otp=". $random ." WHERE User_id='". $myusername. "'"; $querry = mysqli_query($db,$sql2); $to = $myusername; $subject = 'Dual Authentication for Gamify'; $body = 'Greetings. Your one time password is: '.$random; $headers = 'From: Gamify <gamify101@gmail.com>' . "\r\n" . 'Reply-To: Gamify <gamify101@gmail.com>' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $result = mail($to, $subject, $body, $headers); header('Location: duo_auth.php'); } else{ $error = "Your Login Name or Password is invalid"; } }else { $error = "Your Login Name or Password is invalid"; } } ?> <div class="page-content container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="login-wrapper"> <div class="box"> <div class="content-wrap"> <h6>Sign In</h6> <form action = "" method = "post"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope"></i></span> <input class="form-control" type="text" name = "username" placeholder="User Name" autofocus required> </div> <br> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input class="form-control" type="password" name = "password" placeholder="Password" required> </div> <div class="already"> <span><?php if (isset($error)) echo $error ?></span> </div> <div class="action"> <input type = "submit" class="btn btn-primary btn-block signup" value = " Login "/> </div> </form> <br><br> <p><h4><a href="fg_pwd.php">Forgot Password?</a></h4></p><br> <h4><p>Don't have an account?<a href="<API key>.php"> Register now!</a></p></h4> </div> </div> </div> </div> <?php include('initial-footer.php'); ?> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://code.jquery.com/jquery.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="bootstrap/js/bootstrap.min.js"></script> <script src="js/custom.js"></script> </body> </html>
package net.spy.digg.parsers; import java.io.IOException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import net.spy.digg.Story; /** * Parse a stories response. */ public class StoriesParser extends TimePagedItemParser<Story> { @Override protected String getRootElementName() { return "stories"; } @Override protected void handleDocument(Document doc) throws SAXException, IOException { parseCommonFields(doc); final NodeList nl=doc.<API key>("story"); for(int i=0; i<nl.getLength(); i++) { addItem(new StoryImpl(nl.item(i))); } } }
require "../test_helper" require "rorschart/data/rorschart_data" module Rorschart class TestPivotSeries < Minitest::Unit::TestCase def test_pivot # Given data = [ {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "A", "count"=> 1}, {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "B", "count"=> 2}, {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "C", "count"=> 3}, {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "D", "count"=> 4}, {"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "A", "count"=> 5}, {"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "B", "count"=> 6}, {"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "D", "count"=> 7} ] # When pivot_series = PivotSeries.new(data) # assert expected_cols = [ {:type=>"date", :label=>"collector_tstamp"}, {:type=>"number", :label=>"A"}, {:type=>"number", :label=>"B"}, {:type=>"number", :label=>"C"}, {:type=>"number", :label=>"D"} ] expected_rows = [ [Date.parse("2013-11-02"), 1, 2, 3, 4], [Date.parse("2013-12-01"), 5, 6, nil, 7] ] assert_equal expected_cols, pivot_series.cols assert_equal expected_rows, pivot_series.rows end def <API key> # Given data = [ {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "A", "count"=> 1}, {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "B", "count"=> 2}, {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "C", "count"=> 3}, {"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "D", "count"=> 4}, {"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "A", "count"=> nil}, {"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "B", "count"=> 6}, {"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "D", "count"=> 7} ] # When pivot_series = PivotSeries.new(data, add_total_column: true) # assert expected_cols = [ {:type=>"date", :label=>"collector_tstamp"}, {:type=>"number", :label=>"Total"}, {:type=>"number", :label=>"A"}, {:type=>"number", :label=>"B"}, {:type=>"number", :label=>"C"}, {:type=>"number", :label=>"D"} ] expected_rows = [ [Date.parse("2013-11-02"), 10, 1, 2, 3, 4], [Date.parse("2013-12-01"), 13, nil, 6, nil, 7] ] assert_equal expected_cols, pivot_series.cols assert_equal expected_rows, pivot_series.rows end def <API key> # Given data = [] # When pivot_series = PivotSeries.new(data) # assert expected_cols = [] expected_rows = [] assert_equal expected_cols, pivot_series.cols assert_equal expected_rows, pivot_series.rows end end end
#define <API key> #include "core/filament.h" #include "locking/fil_lock.h" typedef struct _pyfil_lock { PyObject_HEAD int locked; FilWaiterList waiters; } PyFilLock; typedef struct _pyfil_rlock { PyFilLock lock; /* must remain first. */ uint64_t owner; uint64_t count; } PyFilRLock; static PyFilLock *_lock_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyFilLock *self = (PyFilLock *)type->tp_alloc(type, 0); if (self != NULL) { fil_waiterlist_init(self->waiters); } return self; } static int _lock_init(PyFilLock *self, PyObject *args, PyObject *kwargs) { return 0; } static void _lock_dealloc(PyFilLock *self) { assert(<API key>(self->waiters)); PyObject_Del(self); } static int __lock_acquire(PyFilLock *lock, int blocking, struct timespec *ts) { if (!lock->locked && <API key>(lock->waiters)) { lock->locked = 1; return 0; } if (!blocking) { return 1; } int err = fil_waiterlist_wait(lock->waiters, ts, NULL); if (err < 0) { return err; } assert(lock->locked == 1); return 0; } static int __lock_release(PyFilLock *lock) { if (!lock->locked) { PyErr_SetString(PyExc_RuntimeError, "release without acquire"); return -1; } if (<API key>(lock->waiters)) { lock->locked = 0; return 0; } /* leave 'locked' set because a different thread is just * going to grab it anyway. This prevents some races without * additional work to resolve them. */ <API key>(lock->waiters); return 0; } static int __rlock_acquire(PyFilRLock *lock, int blocking, struct timespec *ts) { uint64_t owner; owner = fil_get_ident(); if (!lock->lock.locked && <API key>(lock->lock.waiters)) { lock->lock.locked = 1; lock->owner = owner; lock->count = 1; return 0; } if (owner == lock->owner) { lock->count++; return 0; } if (!blocking) { return 1; } int err = fil_waiterlist_wait(lock->lock.waiters, ts, NULL); if (err) { return err; } assert(lock->lock.locked == 1); lock->owner = owner; lock->count = 1; return 0; } static int __rlock_release(PyFilRLock *lock) { if (!lock->lock.locked || (fil_get_ident() != lock->owner)) { PyErr_SetString(PyExc_RuntimeError, "cannot release un-acquired lock"); return -1; } if (--lock->count > 0) { return 0; } lock->owner = 0; if (<API key>(lock->lock.waiters)) { lock->lock.locked = 0; return 0; } /* leave 'locked' set because a different thread is just * going to grab it anyway. This prevents some races without * additional work to resolve them. */ <API key>(lock->lock.waiters); return 0; } PyDoc_STRVAR(_lock_acquire_doc, "Acquire the lock."); static PyObject *_lock_acquire(PyFilLock *self, PyObject *args, PyObject *kwargs) { static char *keywords[] = {"blocking", "timeout", NULL}; PyObject *blockingobj = NULL; PyObject *timeout = NULL; struct timespec tsbuf; struct timespec *ts; int blocking; int err; if (!<API key>(args, kwargs, "|O!O", keywords, &PyBool_Type, &blockingobj, &timeout)) { return NULL; } if (<API key>(timeout, &tsbuf, &ts) < 0) { return NULL; } blocking = (blockingobj == NULL || blockingobj == Py_True); err = __lock_acquire(self, blocking, ts); if (err < 0 && err != -ETIMEDOUT) { return NULL; } if (err == 0) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } PyDoc_STRVAR(_lock_locked_doc, "Is the lock locked?"); static PyObject *_lock_locked(PyFilLock *self) { PyObject *res = (self->locked || !<API key>(self->waiters)) ? Py_True : Py_False; Py_INCREF(res); return res; } PyDoc_STRVAR(_lock_release_doc, "Release the lock."); static PyObject *_lock_release(PyFilLock *self) { if (__lock_release(self) < 0) { return NULL; } Py_RETURN_NONE; } static PyObject *_lock_enter(PyFilLock *self) { int err = __lock_acquire(self, 1, NULL); if (err) { if (!PyErr_Occurred()) { PyErr_Format(PyExc_RuntimeError, "unexpected failure in Lock.__enter__: %d", err); } return NULL; } Py_INCREF(self); return (PyObject *)self; } static PyObject *_lock_exit(PyFilLock *self, PyObject *args) { return _lock_release(self); } PyDoc_STRVAR(_rlock_acquire_doc, "Acquire the lock."); static PyObject *_rlock_acquire(PyFilRLock *self, PyObject *args, PyObject *kwargs) { static char *keywords[] = {"blocking", "timeout", NULL}; PyObject *blockingobj = NULL; PyObject *timeout = NULL; struct timespec tsbuf; struct timespec *ts; int blocking; int err; if (!<API key>(args, kwargs, "|O!O", keywords, &PyBool_Type, &blockingobj, &timeout)) { return NULL; } if (<API key>(timeout, &tsbuf, &ts) < 0) { return NULL; } blocking = (blockingobj == NULL || blockingobj == Py_True); err = __rlock_acquire(self, blocking, ts); if (err < 0 && err != -ETIMEDOUT) { return NULL; } if (err == 0) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } PyDoc_STRVAR(_rlock_locked_doc, "Is the lock locked (by someone else)?"); static PyObject *_rlock_locked(PyFilRLock *self) { uint64_t owner = fil_get_ident(); PyObject *res = ((self->lock.locked && self->owner != owner) || !<API key>(self->lock.waiters)) ? Py_True : Py_False; Py_INCREF(res); return res; } PyDoc_STRVAR(_rlock_release_doc, "Release the lock."); static PyObject *_rlock_release(PyFilRLock *self) { if (__rlock_release(self) < 0) { return NULL; } Py_RETURN_NONE; } static PyObject *_rlock_enter(PyFilRLock *self) { int err = __rlock_acquire(self, 1, NULL); if (err) { if (!PyErr_Occurred()) { PyErr_Format(PyExc_RuntimeError, "unexpected failure in RLock.__enter__: %d", err); } return NULL; } Py_INCREF(self); return (PyObject *)self; } static PyObject *_rlock_exit(PyFilRLock *self, PyObject *args) { return _rlock_release(self); } static PyMethodDef _lock_methods[] = { { "acquire", (PyCFunction)_lock_acquire, METH_VARARGS|METH_KEYWORDS, _lock_acquire_doc }, { "release", (PyCFunction)_lock_release, METH_NOARGS, _lock_release_doc }, { "locked", (PyCFunction)_lock_locked, METH_NOARGS, _lock_locked_doc }, { "__enter__", (PyCFunction)_lock_enter, METH_NOARGS, NULL }, { "__exit__", (PyCFunction)_lock_exit, METH_VARARGS, NULL }, { NULL, NULL } }; static PyMethodDef _rlock_methods[] = { { "acquire", (PyCFunction)_rlock_acquire, METH_VARARGS|METH_KEYWORDS, _rlock_acquire_doc }, { "release", (PyCFunction)_rlock_release, METH_NOARGS, _rlock_release_doc }, { "locked", (PyCFunction)_rlock_locked, METH_NOARGS, _rlock_locked_doc }, { "__enter__", (PyCFunction)_rlock_enter, METH_NOARGS, NULL }, { "__exit__", (PyCFunction)_rlock_exit, METH_VARARGS, NULL }, { NULL, NULL } }; static PyTypeObject _lock_type = { <API key>(0, 0) "_filament.locking.Lock", /* tp_name */ sizeof(PyFilLock), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)_lock_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ <API key>, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ FIL_DEFAULT_TPFLAGS, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ _lock_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)_lock_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ (newfunc)_lock_new, /* tp_new */ PyObject_Del, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; /* Re-entrant lock. We can use the same calls here */ static PyTypeObject _rlock_type = { <API key>(0, 0) "_filament.locking.RLock", /* tp_name */ sizeof(PyFilRLock), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)_lock_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ <API key>, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ FIL_DEFAULT_TPFLAGS, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ _rlock_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)_lock_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ (newfunc)_lock_new, /* tp_new */ PyObject_Del, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; PyFilLock *fil_lock_alloc(void) { return _lock_new(&_lock_type, NULL, NULL); } PyFilRLock *fil_rlock_alloc(void) { return (PyFilRLock *)_lock_new(&_rlock_type, NULL, NULL); } int fil_lock_acquire(PyFilLock *lock, int blocking, struct timespec *ts) { return __lock_acquire(lock, blocking, ts); } int fil_rlock_acquire(PyFilRLock *rlock, int blocking, struct timespec *ts) { return __rlock_acquire(rlock, blocking, ts); } int fil_lock_release(PyFilLock *lock) { return __lock_release(lock); } int fil_rlock_release(PyFilRLock *rlock) { return __rlock_release(rlock); } int fil_lock_type_init(PyObject *module) { PyFilCore_Import(); if (PyType_Ready(&_lock_type) < 0) { return -1; } if (PyType_Ready(&_rlock_type) < 0) { return -1; } Py_INCREF((PyObject *)&_lock_type); if (PyModule_AddObject(module, "Lock", (PyObject *)&_lock_type) != 0) { Py_DECREF((PyObject *)&_lock_type); return -1; } Py_INCREF((PyObject *)&_rlock_type); if (PyModule_AddObject(module, "RLock", (PyObject *)&_rlock_type) != 0) { Py_DECREF((PyObject *)&_rlock_type); return -1; } return 0; }
package de.thomas.dreja.ec.musicquiz.gui.dialog; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import de.thomas.dreja.ec.musicquiz.R; import de.thomas.dreja.ec.musicquiz.ctrl.PlaylistResolver.SortOrder; public class <API key> extends DialogFragment { private <API key> listener; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String[] items = new String[SortOrder.values().length]; for(int i=0; i<items.length; i++) { items[i] = SortOrder.values()[i].getName(getResources()); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.sort_by) .setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { listener.onSortOrderSelected(SortOrder.values()[which]); } }); return builder.create(); } public interface <API key> { public void onSortOrderSelected(SortOrder order); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the <API key> so we can send events to the host listener = (<API key>) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement <API key>"); } } }
/* * Panel */ .panel { margin: 5rem auto; max-width: 64rem; background: $white; border: 0.4rem solid $black; box-shadow: 5px 5px 0px $black; &:first-child { margin-top: 0; } &:last-child { margin-bottom: 0; } } .panel-header { padding: 2rem; background: $secondary; border-bottom: 0.4rem solid $black; } .panel-title { color: $white; } .panel-content { padding: 3rem 2rem; }
<API key> ========================== A native Angular multi select tree. No JQuery. ![BrowserStack Status](https: # Demo Page: [Demo] (http: # Features: Very Easy to Use: - Plug and Play component - Tree List - Databind - Filter/NoFilter by search textbox - Checkbox - Select one only or Multiselect - NO JQuery # Design details: Custom element using Angular Directive and Templating # Callbacks: This is your onchange :) ## Usage: Get this awesome component to your project by: sh bower install <API key> --save # bower install long name ehhfsaduasdu lol . just kidding use the first one :) Make sure to load the scripts in your html. html <link rel="stylesheet" href="../dist/<API key>.min.css"> <script type="text/javascript" src="../dist/<API key>.min.js"></script> <script type="text/javascript" src="../dist/<API key>.tpl.js"></script> And Inject the module as dependency to your angular app. angular.module('[YOURAPPNAMEHERE!]', ['<API key>', '....']); ### Html Structure: html <<API key> multi-select="true" data-input-model="data" data-output-model="selectedItem2" data-callback="CustomCallback(item, selectedItems)" <API key>="true"> </<API key>> That's what all you have to do. MIT, see [LICENSE.md](./LICENSE.md).
// DNTag.h // DNTagView #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> <API key> @interface DNTag : NSObject @property (nonatomic, copy) NSString *text; @property (nonatomic, copy) NSAttributedString *attributedText; @property (nonatomic, strong) UIColor *textColor; @property (nonatomic, strong) UIColor *bgColor; @property (nonatomic, strong) UIColor *highlightedBgColor; @property (nonatomic, strong) UIColor *borderColor; @property (nonatomic, strong) UIImage *bgImg; @property (nonatomic, strong) UIFont *font; @property (nonatomic, assign) CGFloat cornerRadius; @property (nonatomic, assign) CGFloat borderWidth; like padding in css @property (nonatomic, assign) UIEdgeInsets padding; if no font is specified, system font with fontSize is used @property (nonatomic, assign) CGFloat fontSize; default:YES @property (nonatomic, assign) BOOL enable; - (nonnull instancetype)initWithText: (nonnull NSString *)text; + (nonnull instancetype)tagWithText: (nonnull NSString *)text; @end <API key>
#pragma once #include "FtInclude.h" #include <string> namespace ft { class Library { public: Library(); ~Library(); FT_Library library = nullptr; Library(const Library&) = delete; Library(Library&&) = delete; Library& operator = (const Library&) = delete; Library& operator=(Library&&) = delete; std::string getVersionString() const; private: static int initialized; }; }
package com.github.fhtw.swp.tutorium.guice; import com.github.fhtw.swp.tutorium.composite.Leaf; import com.github.fhtw.swp.tutorium.composite.LeafTypeProvider; import com.github.fhtw.swp.tutorium.reflection.AnnotatedTypeFinder; import org.reflections.Configuration; import javax.inject.Inject; import java.util.Set; public class <API key> implements LeafTypeProvider { private final Configuration configuration; @Inject public <API key>(Configuration configuration) { this.configuration = configuration; } @Override public Set<Class<?>> getLeafTypes() { return new AnnotatedTypeFinder(configuration, Leaf.class).getAnnotatedTypes(); } }
#!/bin/sh tokenizer() { STRNG="${1}" DELIM="${2}" while : do NEW="${STRNG%${DELIM}}" while case "$NEW" in *${DELIM}*);; *)break;; esac do NEW="${NEW%${DELIM}*}" done TOKEN="${NEW%${DELIM}*}" STRNG="${STRNG#${TOKEN}${DELIM}}" printf "%s\n" "$TOKEN" case "$STRNG" in *${DELIM}*) ;; *) [ -n "$d" ] && break || d="1" ;; esac done } which(){ for i in $(tokenizer $PATH ":" ) do #echo "${i}" # test directory walk [ -d "${i}/${1}" ] && break [ -x "${i}/${1}" ] && echo "${i}/${1}" && exit done } which $@
// <API key>.h // MH4U Dex #import <UIKit/UIKit.h> @class Region; @interface <API key> : UIViewController @property (nonatomic, strong) Region *region; @end
# cooper document with one key example class RevisionedObject include Cooper::Document revision_field :key, type: String end describe 'Updating documents' do let(:object) do RevisionedObject.new end it 'works like Mongoid::Document' do object.key = 'value0' object.save object.update_attributes(key: 'value1') expect(object.key).to eq 'value1' end end
<?php namespace BackendBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class <API key> extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/'); $this->assertContains('Hello World', $client->getResponse()->getContent()); } }
# AIT_MAIKON <br> wiki
using System; using System.Net; using Microsoft.Extensions.Logging; namespace CakesNoteProxy { public static class NoteProxyConfigure { public static ILoggerFactory LoggerFactory; public static class NoteApi { public static string SiteFqdn { get; private set; } public static string UserId { get; private set; } public static bool IsIntro { get; private set; } static NoteApi() { SiteFqdn = "https://note.mu"; UserId = "info"; IsIntro = true; } public static void SetGlobal(string noteSiteFqdn) { if ( noteSiteFqdn!=null) SiteFqdn = noteSiteFqdn; } public static void SetMyNote(string noteUserId, bool isIntro) { if (noteUserId != null) UserId = noteUserId; IsIntro = isIntro; } public static readonly string ApiRoot = "/api/v1"; } public static class NoteCache { public static int <API key> = 50; public static TimeSpan <API key> = TimeSpan.FromSeconds(12); public static TimeSpan <API key> = TimeSpan.FromSeconds(720); public static double <API key> = 0.8; } } }
module HealthSeven::V2_5 class Rq1 < ::HealthSeven::Segment # Anticipated Price attribute :anticipated_price, St, position: "RQ1.1" # Manufacturer Identifier attribute :<API key>, Ce, position: "RQ1.2" # Manufacturer's Catalog attribute :<API key>, St, position: "RQ1.3" # Vendor ID attribute :vendor_id, Ce, position: "RQ1.4" # Vendor Catalog attribute :vendor_catalog, St, position: "RQ1.5" # Taxable attribute :taxable, Id, position: "RQ1.6" # Substitute Allowed attribute :substitute_allowed, Id, position: "RQ1.7" end end
using System; using Lunt.IO; namespace Lunt { <summary> Represent a dependency to an asset. </summary> public sealed class AssetDependency { private readonly FilePath _path; private readonly long _fileSize; private readonly string _checksum; <summary> Gets the path of the dependency. </summary> <value>The path of the dependency.</value> public FilePath Path { get { return _path; } } <summary> Gets the file size of the dependency. </summary> <value>The file size of the dependency.</value> public long FileSize { get { return _fileSize; } } <summary> Gets the checksum of the dependency. </summary> <value>The checksum of the dependency.</value> public string Checksum { get { return _checksum; } } <summary> Initializes a new instance of the <see cref="AssetDependency" /> class. </summary> <param name="path">The path.</param> <param name="fileSize">The file size.</param> <param name="checksum">The checksum.</param> public AssetDependency(FilePath path, long fileSize, string checksum) { if (path == null) { throw new <API key>("path"); } if (checksum == null) { throw new <API key>("checksum"); } _path = path; _fileSize = fileSize; _checksum = checksum; } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "liste.h" #include "atl.h" #include "es.h" #define FILE_ATLETI "atleti.txt" #define FILE_ESERCIZI "esercizi.txt" #define MAX_NOME 25 #define LUNG_CODICE 5 #define non_strutturato ;; #ifdef _WIN32 #define F_CLEAR "cls" #else #define F_CLEAR "clear" #endif Atleta inputCercaAtleta(Lista); void makeDotTxt(char*, char*); FILE *inputStampaSuFile(); int main() { FILE *fp, *fEs; Atleta tmpAtl=newAtleta(); Lista atleti=newAtlCollection(); tabellaEs esercizi=newEsCollection(); char uInput[100], fileTxt[10]; char codice[LUNG_CODICE+1], nome[MAX_NOME+1], cognome[MAX_NOME+1]; char categoria[MAX_NOME+1], data[11]; int scelta=-1; int x,y; // file ESERCIZI if ((fp=fopen(FILE_ESERCIZI, "r"))==NULL){ printf("Errore! Impossibile aprire il file \"%s\"!\n", FILE_ESERCIZI); exit(1); } caricaEsercizi(esercizi, fp); fclose(fp); // file degli ATLETI (riciclo fp) if ((fp=fopen(FILE_ATLETI, "r"))==NULL){ printf("Errore! Impossibile aprire il file \"%s\"!\n", FILE_ATLETI); exit(1); } caricaAtleti(atleti, fp); fclose(fp); // menu' for(non_strutturato) { system(F_CLEAR); puts("01. Stampa contenuto anagrafica"); puts("02. Stampa gli atleti divisi per categoria"); puts("03. Aggiornamento monte ore settimanali"); puts("04. Ricerca atleta per codice o cognome parziale"); puts("05. Aggiungi un atleta"); puts("06. Cancella un atleta"); for (x=80; x-->0; printf("-")); puts(""); // linea orizzontale puts("07. Caricare / salvare esercizi di un atleta"); puts("08. Modificare set / ripetizioni di un esercizio di un atleta"); puts("09. Aggiungi un esercizio"); puts("10. Cancella un esercizio"); for (x=80; x-->0; printf("-")); puts(""); puts("0. Esci"); puts(""); printf("> "); scanf("%d", &scelta); switch (scelta) { case 0: return 0; case 1: // stampa contetnuto anagrafica fp=inputStampaSuFile(); stampaAnagrafica(atleti, fp); if (fp!=stdout) fclose(fp); break; case 2: // stamapa divisi per categoria stampaPerCategoria(atleti); break; case 3: // aggiornamento monte ore settimanli if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break; printf("Monte ore attuali: %d\n", getOreAtleta(tmpAtl)); printf("Nuovo monte ore: "); scanf("%d", &x); modificaOreAtl(tmpAtl, x); puts("Monte ore aggiornato correttamente!"); break; case 4: // ricerca atleta inputCercaAtleta(atleti); break; case 5: // aggiungi atleta printf("Codice: "); scanf("%s", codice); printf("Nome: "); scanf("%s", nome); printf("Cognome: "); scanf("%s", cognome); printf("Cateogria: "); scanf("%s", categoria); printf("Data : "); scanf("%s", data); printf("Monte ore: "); scanf("%d", &x); aggiungiAtletaByPar(atleti, codice, nome, cognome, categoria, data, x); puts("Atleta aggiunto correttamente!"); break; case 6: // cancellazione atleta if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break; printf("Rimuovere l'atleta trovato? [s/n] "); scanf("%s", uInput); if (tolower(uInput[0])=='s') { cancellaAtleta(atleti, tmpAtl); puts("Atleta cancellato con successo!"); } break; case 7: // caricare / salvare esericizi per un atleta if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break; if (eserciziCaricatiAtl(tmpAtl)) { fp=inputStampaSuFile(); stampaTuttiEs(getListaEsercizi(tmpAtl), fp); break; } //else: cerco di caricare il piano esercizi per l'altleta makeDotTxt(fileTxt, getCodiceAtleta(tmpAtl)); if ((fEs=fopen(fileTxt, "r"))!=NULL) { // se ho trovato un file con il codice dell'atleta... caricaPianoEsercizi(getListaEsercizi(tmpAtl), esercizi, fEs); puts("Piano degli esercizi caricato correttamente"); fclose(fEs); } else { printf("Non ho trovato un piano esercizi per %s\n", getCodiceAtleta(tmpAtl)); } break; case 8: // modificare il numero di set/ripetizioni if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break; if (!eserciziCaricatiAtl(tmpAtl)){ printf("Esercizi non caricati per \"%s\"", getCodiceAtleta(tmpAtl)); break; } printf("Nome dell'esercizio per modificare set/ripetizioni: "); scanf("%s", uInput); printf("Nuovo n* set: "); scanf("%d", &x); printf("Nuovo n* ripetizioni: "); scanf("%d", &y); if(<API key>(getListaEsercizi(tmpAtl), uInput, x, y)){ puts("Modifiche effettuate con successo!"); } else { puts("Errore! Esercizio non trovato."); } break; case 9: // aggiunta di un esercizio // ho bisogno sia dei set/ripetizioni da mettere nella lista, sia // dell'esercizio da far pountare quindi del nome, della // categoria e del tipo di esercizio if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break; printf("Nome dell'esercizio da aggiungere: "); scanf("%s", uInput); printf("Nuovo n* set: "); scanf("%d", &x); printf("Nuovo n* ripetizioni: "); scanf("%d", &y); if(aggiungiEs(getListaEsercizi(tmpAtl), esercizi, uInput, x, y)) { puts("Esercizio aggiunto con successo!"); } else { printf("Impossibile trovare l'esercizio \"%s\"!\n", uInput); } break; case 10: // cancellazione di un esercizio if ((tmpAtl=inputCercaAtleta(atleti))==NULL) break; if (!eserciziCaricatiAtl(tmpAtl)){ printf("Esercizi non caricati per \"%s\"", getCodiceAtleta(tmpAtl)); break; } printf("Nome dell'esercizio da cancellare: "); scanf("%s", uInput); // scorro tutti gli elementi della lista con p=head della lista if (<API key>(getListaEsercizi(tmpAtl), uInput)) puts("Esercizio cancellato con successo!"); else puts("Errore! Esercizio non trovato!"); break; default: puts("Comando non trovato."); } getc(stdin); // prendo il ritorno a capo della scanf printf("\nPremere invio per tornare al menu'... "); getc(stdin); // aspetto che l'utente prema invio } return 0; } Atleta inputCercaAtleta(Lista l) { char c[MAX_NOME+1]; Atleta atl; printf("Codice o cognome parziale dell'atleta: "); scanf("%s", c); if ((atl=cercaAtleta(l, c))!=NULL) { stampaAtleta(atl, stdout); return atl; } else { puts("Atleta non trovato"); return NULL; } } FILE *inputStampaSuFile() { FILE *fp; char c[3], f[100]; printf("Stampa su file? [s/n] "); scanf("%s", c); if (tolower(c[0])=='s') { printf("Inserisci il nome del file: "); scanf("%s", f); if ((fp=fopen(f, "w"))==NULL) { printf("Errore! Impossibile aprire il file \"%s\"", f); printf("Stampo a video...\n"); return stdout; } else { return fp; } } else { return stdout; } } void makeDotTxt(char *dst, char *src) { strcpy(dst, src); strcat(dst, ".txt"); }
#include "ofQuickTimeGrabber.h" #include "ofUtils.h" #if !defined(TARGET_LINUX) && !defined(<API key>) #ifdef <API key> static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon); static ComponentResult frameIsGrabbedProc(SGChannel sgChan, short nBufferNum, Boolean *pbDone, long lRefCon){ ComponentResult err = SGGrabFrameComplete( sgChan, nBufferNum, pbDone ); bool * havePixChanged = (bool *)lRefCon; *havePixChanged = true; return err; } #endif ofQuickTimeGrabber::ofQuickTimeGrabber(){ #ifdef <API key> initializeQuicktime(); bSgInited = false; gSeqGrabber = nullptr; <API key> = nullptr; #endif // common bIsFrameNew = false; bVerbose = false; bGrabberInited = false; bChooseDevice = false; deviceID = 0; //width = 320; // default setting //height = 240; // default setting //pixels = nullptr; attemptFramerate = -1; } ofQuickTimeGrabber::~ofQuickTimeGrabber(){ close(); #ifdef <API key> if (<API key> != nullptr){ delete[] <API key>; <API key> = nullptr; } #endif } void ofQuickTimeGrabber::setVerbose(bool bTalkToMe){ bVerbose = bTalkToMe; } void ofQuickTimeGrabber::setDeviceID(int _deviceID){ deviceID = _deviceID; bChooseDevice = true; } void ofQuickTimeGrabber::setDesiredFrameRate(int framerate){ attemptFramerate = framerate; } bool ofQuickTimeGrabber::setPixelFormat(ofPixelFormat pixelFormat){ //note as we only support RGB we are just confirming that this pixel format is supported if( pixelFormat == OF_PIXELS_RGB ){ return true; } ofLogWarning("ofQuickTimeGrabber") << "setPixelFormat(): requested pixel format " << pixelFormat << " not supported"; return false; } ofPixelFormat ofQuickTimeGrabber::getPixelFormat() const { //note if you support more than one pixel format you will need to return a ofPixelFormat variable. return OF_PIXELS_RGB; } bool ofQuickTimeGrabber::setup(int w, int h){ #ifdef <API key> if( !qtInitSeqGrabber() ){ ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to initialize the seq grabber"; return false; } //width = w; //height = h; MacSetRect(&videoRect, 0, 0, w, h); // Create a buffer big enough to hold the video data, // make sure the pointer is 32-byte aligned. // also the rgb image that people will grab <API key> = (unsigned char*)malloc(4 * w * h + 32); pixels.allocate(w, h, OF_IMAGE_COLOR); #if defined(TARGET_OSX) && defined(__BIG_ENDIAN__) QTNewGWorldFromPtr (&(videogworld), k32ARGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (<API key>), 4 * w); #else QTNewGWorldFromPtr (&(videogworld), k24RGBPixelFormat, &(videoRect), nullptr, nullptr, 0, (pixels.getPixels()), 3 * w); #endif LockPixels(GetGWorldPixMap(videogworld)); SetGWorld (videogworld, nullptr); SGSetGWorld(gSeqGrabber, videogworld, nil); bool didWeChooseADevice = bChooseDevice; bool deviceIsSelected = false; //if we have a device selected then try first to setup //that device if(didWeChooseADevice){ deviceIsSelected = qtSelectDevice(deviceID, true); if(!deviceIsSelected && bVerbose) ofLogError("ofQuickTimeGrabber") << "initGrabber(): unable to open device[" << deviceID << "], will attempt other devices"; } //if we couldn't select our required device //or we aren't specifiying a device to setup //then lets try to setup ANY device! if(deviceIsSelected == false){ //lets list available devices listDevices(); setDeviceID(0); deviceIsSelected = qtSelectDevice(deviceID, false); } //if we still haven't been able to setup a device //we should error and stop! if( deviceIsSelected == false){ goto bail; } OSStatus err; err = SGSetChannelUsage(gVideoChannel,seqGrabPreview); if ( err != noErr ) goto bail; err = SGSetChannelRefCon(gVideoChannel, (long)&bHavePixelsChanged ); if(!err) { VideoBottles vb; /* get the current bottlenecks */ vb.procCount = 9; err = <API key>(gVideoChannel, &vb); if (!err) { myGrabCompleteProc = <API key>(frameIsGrabbedProc); vb.grabCompleteProc = myGrabCompleteProc; /* add our GrabFrameComplete function */ err = <API key>(gVideoChannel, &vb); } } err = SGSetChannelBounds(gVideoChannel, &videoRect); if ( err != noErr ) goto bail; err = SGPrepare(gSeqGrabber, true, false); //theo swapped so preview is true and capture is false if ( err != noErr ) goto bail; err = SGStartPreview(gSeqGrabber); if ( err != noErr ) goto bail; bGrabberInited = true; loadSettings(); if( attemptFramerate >= 0 ){ err = SGSetFrameRate(gVideoChannel, IntToFixed(attemptFramerate) ); if ( err != noErr ){ ofLogError("ofQuickTimeGrabber") << "initGrabber: couldn't setting framerate to " << attemptFramerate << ": OSStatus " << err; } } ofLogNotice("ofQuickTimeGrabber") << " inited grabbed "; ofLogNotice("ofQuickTimeGrabber") << " // we are done return true; bail: ofLogError("ofQuickTimeGrabber") << "***** ofQuickTimeGrabber error *****"; ofLogError("ofQuickTimeGrabber") << " //if we don't close this - it messes up the next device! if(bSgInited) qtCloseSeqGrabber(); bGrabberInited = false; return false; #else return false; #endif } bool ofQuickTimeGrabber::isInitialized() const{ return bGrabberInited; } vector<ofVideoDevice> ofQuickTimeGrabber::listDevices() const{ vector <ofVideoDevice> devices; #ifdef <API key> bool <API key> = false; if (!bSgInited) <API key> = true; //if we need to initialize the grabbing component then do it if( <API key> ){ if( !qtInitSeqGrabber() ){ return devices; } } ofLogNotice("ofQuickTimeGrabber") << " SGDeviceList deviceList; <API key> (gVideoChannel, <API key>, &deviceList); unsigned char pascalName[64]; unsigned char pascalNameInput[64]; //this is our new way of enumerating devices //quicktime can have multiple capture 'inputs' on the same capture 'device' //ie the USB Video Class Video 'device' - can have multiple usb webcams attached on what QT calls 'inputs' //The isight for example will show up as: //USB Video Class Video - Built-in iSight ('input' 1 of the USB Video Class Video 'device') //Where as another webcam also plugged whill show up as //USB Video Class Video - Philips SPC 1000NC Webcam ('input' 2 of the USB Video Class Video 'device') //this means our the device ID we use for selection has to count both capture 'devices' and their 'inputs' //this needs to be the same in our init grabber method so that we select the device we ask for int deviceCount = 0; ofLogNotice("ofQuickTimeGrabber") << "listing available capture devices"; for(int i = 0 ; i < (*deviceList)->count ; ++i) { SGDeviceName nameRec; nameRec = (*deviceList)->entry[i]; SGDeviceInputList deviceInputList = nameRec.inputs; int numInputs = 0; if( deviceInputList ) numInputs = ((*deviceInputList)->count); memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64); //this means we can use the capture method if(nameRec.flags != <API key>){ //if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used //we go through its inputs to list all physical devices - as there could be more than one! for(int j = 0; j < numInputs; j++){ //if our 'device' has inputs we get their names here if( deviceInputList ){ SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j]; memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64); } ofLogNotice() << "device [" << deviceCount << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput); ofVideoDevice vd; vd.id = deviceCount; vd.deviceName = p2cstr(pascalName); vd.bAvailable = true; devices.push_back(vd); //we count this way as we need to be able to distinguish multiple inputs as devices deviceCount++; } }else{ ofLogNotice("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName); ofVideoDevice vd; vd.id = deviceCount; vd.deviceName = p2cstr(pascalName); vd.bAvailable = false; devices.push_back(vd); deviceCount++; } } ofLogNotice("ofQuickTimeGrabber") << " //if we initialized the grabbing component then close it if( <API key> ){ qtCloseSeqGrabber(); } #endif return devices; } void ofQuickTimeGrabber::update(){ #ifdef <API key> if (bGrabberInited == true){ SGIdle(gSeqGrabber); // set the top pixel alpha = 0, so we can know if it // was a new frame or not.. // or else we will process way more than necessary // (ie opengl is running at 60fps +, capture at 30fps) if (bHavePixelsChanged){ #if defined(TARGET_OSX) && defined(__BIG_ENDIAN__) convertPixels(<API key>, pixels.getPixels(), width, height); #endif } } // newness test for quicktime: if (bGrabberInited == true){ bIsFrameNew = false; if (bHavePixelsChanged == true){ bIsFrameNew = true; bHavePixelsChanged = false; } } #endif } ofPixels& ofQuickTimeGrabber::getPixels(){ return pixels; } const ofPixels& ofQuickTimeGrabber::getPixels() const { return pixels; } bool ofQuickTimeGrabber::isFrameNew() const { return bIsFrameNew; } float ofQuickTimeGrabber::getWidth() const { return pixels.getWidth(); } float ofQuickTimeGrabber::getHeight() const { return pixels.getHeight(); } void ofQuickTimeGrabber::clearMemory(){ pixels.clear(); } void ofQuickTimeGrabber::close(){ #ifdef <API key> qtCloseSeqGrabber(); <API key>(myGrabCompleteProc); #endif clearMemory(); } void ofQuickTimeGrabber::videoSettings(void){ #ifdef <API key> Rect curBounds, curVideoRect; ComponentResult err; // Get our current state err = SGGetChannelBounds (gVideoChannel, &curBounds); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get get channel bounds: ComponentResult " << err; return; } err = SGGetVideoRect (gVideoChannel, &curVideoRect); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't get video rect: ComponentResult " << err; return; } // Pause err = SGPause (gSeqGrabber, true); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): couldn't set pause: ComponentResult " << err; return; } #ifdef TARGET_OSX //load any saved camera settings from file loadSettings(); static SGModalFilterUPP <API key> = NewSGModalFilterUPP(<API key>); ComponentResult result = SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, 0, <API key>, nil); if (result != noErr){ ofLogError("ofQuickTimeGrabber") << "videoSettings(): settings dialog error: ComponentResult " << err; return; } //save any changed settings to file saveSettings(); #else SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, nil, <API key>, nullptr, 0); #endif SGSetChannelBounds(gVideoChannel, &videoRect); SGPause (gSeqGrabber, false); #endif } #ifdef TARGET_OSX bool ofQuickTimeGrabber::saveSettings(){ if (bGrabberInited != true) return false; ComponentResult err; UserData mySGVideoSettings = nullptr; // get the SGChannel settings cofigured by the user err = <API key>(gSeqGrabber, gVideoChannel, &mySGVideoSettings, 0); if ( err != noErr ){ ofLogError("ofQuickTimeGrabber") << "saveSettings(): couldn't get camera settings: ComponentResult " << err; return false; } string pref = "ofVideoSettings-"+deviceName; CFStringRef cameraString = <API key>(kCFAllocatorDefault,pref.c_str(),<API key>); //get the settings using the key "ofVideoSettings-the name of the device" <API key>( cameraString, mySGVideoSettings); DisposeUserData(mySGVideoSettings); return true; } bool ofQuickTimeGrabber::loadSettings(){ if (bGrabberInited != true || deviceName.length() == 0) return false; ComponentResult err; UserData mySGVideoSettings = nullptr; // get the settings using the key "ofVideoSettings-the name of the device" string pref = "ofVideoSettings-"+deviceName; CFStringRef cameraString = <API key>(kCFAllocatorDefault,pref.c_str(),<API key>); <API key>(cameraString, &mySGVideoSettings); if (mySGVideoSettings){ Rect curBounds, curVideoRect; //we need to make sure the dimensions don't get effected //by our preferences // Get our current state err = SGGetChannelBounds (gVideoChannel, &curBounds); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel bounds: ComponentResult " << err; } err = SGGetVideoRect (gVideoChannel, &curVideoRect); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set video rect: ComponentResult " << err; } // use the saved settings preference to configure the SGChannel err = <API key>(gSeqGrabber, gVideoChannel, mySGVideoSettings, 0); if ( err != noErr ) { ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set channel settings: ComponentResult " << err; return false; } DisposeUserData(mySGVideoSettings); // Pause err = SGPause (gSeqGrabber, true); if (err != noErr){ ofLogError("ofQuickTimeGrabber") << "loadSettings(): couldn't set pause: ComponentResult " << err; } SGSetChannelBounds(gVideoChannel, &videoRect); SGPause (gSeqGrabber, false); }else{ ofLogWarning("ofQuickTimeGrabber") << "loadSettings(): no camera settings to load"; return false; } return true; } bool ofQuickTimeGrabber::qtInitSeqGrabber(){ if (bSgInited != true){ OSErr err = noErr; <API key> theDesc; Component sgCompID; // this crashes when we get to // SGNewChannel // we get -9405 as error code for the channel // gSeqGrabber = <API key>(<API key>, 0); // this seems to work instead (got it from hackTV) theDesc.componentType = <API key>; theDesc.componentSubType = nullptr; theDesc.<API key> = 'appl'; theDesc.componentFlags = nullptr; theDesc.componentFlagsMask = nullptr; sgCompID = FindNextComponent (nullptr, &theDesc); if (sgCompID == nullptr){ ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): findNextComponent did not return a valid component"; return false; } gSeqGrabber = OpenComponent(sgCompID); err = GetMoviesError(); if (gSeqGrabber == nullptr || err) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't get default sequence grabber component: OSErr " << err; return false; } err = SGInitialize(gSeqGrabber); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't initialize sequence grabber component: OSErr " << err; return false; } err = SGSetDataRef(gSeqGrabber, 0, 0, <API key>); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): can't set the destination data reference: OSErr " << err; return false; } // windows crashes w/ out gworld, make a dummy for now... // this took a long time to figure out. err = SGSetGWorld(gSeqGrabber, 0, 0); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): setting up the gworld: OSErr " << err; return false; } err = SGNewChannel(gSeqGrabber, VideoMediaType, &(gVideoChannel)); if (err != noErr) { ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): couldn't create a new channel: OSErr " << err; ofLogError("ofQuickTimeGrabber") << "qtInitSeqGrabber(): check if you have any qt capable cameras attached"; return false; } bSgInited = true; return true; } return false; } bool ofQuickTimeGrabber::qtCloseSeqGrabber(){ if (gSeqGrabber != nullptr){ SGStop (gSeqGrabber); CloseComponent (gSeqGrabber); gSeqGrabber = nullptr; bSgInited = false; return true; } return false; } bool ofQuickTimeGrabber::qtSelectDevice(int deviceNumber, bool didWeChooseADevice){ //note - check for memory freeing possibly needed for the all <API key> mac stuff // also see notes in listDevices() regarding new enunemeration method. //Generate a device list and enumerate //all devices availble to the channel SGDeviceList deviceList; <API key>(gVideoChannel, <API key>, &deviceList); unsigned char pascalName[64]; unsigned char pascalNameInput[64]; int numDevices = (*deviceList)->count; if(numDevices == 0){ ofLogError("ofQuickTimeGrabber") << "no capture devices found"; return false; } int deviceCount = 0; for(int i = 0 ; i < numDevices; ++i) { SGDeviceName nameRec; nameRec = (*deviceList)->entry[i]; SGDeviceInputList deviceInputList = nameRec.inputs; int numInputs = 0; if( deviceInputList ) numInputs = ((*deviceInputList)->count); memcpy(pascalName, (*deviceList)->entry[i].name, sizeof(char) * 64); memset(pascalNameInput, 0, sizeof(char)*64); //this means we can use the capture method if(nameRec.flags != <API key>){ //if we have a capture 'device' (qt's word not mine - I would prefer 'system' ) that is ready to be used //we go through its inputs to list all physical devices - as there could be more than one! for(int j = 0; j < numInputs; j++){ //if our 'device' has inputs we get their names here if( deviceInputList ){ SGDeviceInputName inputNameRec = (*deviceInputList)->entry[j]; memcpy(pascalNameInput, inputNameRec.name, sizeof(char) * 64); } //if the device number matches we try and setup the device //if we didn't specifiy a device then we will try all devices till one works! if( deviceCount == deviceNumber || !didWeChooseADevice ){ ofLogNotice("ofQuickTimeGrabber") << "attempting to open device [" << deviceCount << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput); OSErr err1 = SGSetChannelDevice(gVideoChannel, pascalName); OSErr err2 = <API key>(gVideoChannel, j); int successLevel = 0; //if there were no errors then we have opened the device without issue if ( err1 == noErr && err2 == noErr){ successLevel = 2; } //parameter errors are not fatal so we will try and open but will caution the user else if ( (err1 == paramErr || err1 == noErr) && (err2 == noErr || err2 == paramErr) ){ successLevel = 1; } //the device is opened! if ( successLevel > 0 ){ deviceName = (char *)p2cstr(pascalName); deviceName += "-"; deviceName += (char *)p2cstr(pascalNameInput); if(successLevel == 2){ ofLogNotice("ofQuickTimeGrabber") << "device " << deviceName << " opened successfully"; } else{ ofLogWarning("ofQuickTimeGrabber") << "device " << deviceName << " opened with some paramater errors, should be fine though!"; } //no need to keep searching - return that we have opened a device! return true; }else{ //if we selected a device in particular but failed we want to go through the whole list again - starting from 0 and try any device. //so we return false - and try one more time without a preference if( didWeChooseADevice ){ ofLogWarning("ofQuickTimeGrabber") << "problems setting device [" << deviceNumber << "] " << p2cstr(pascalName) << " - " << p2cstr(pascalNameInput) << " *****"; return false; }else{ ofLogWarning("ofQuickTimeGrabber") << "unable to open device, trying next device"; } } } //we count this way as we need to be able to distinguish multiple inputs as devices deviceCount++; } }else{ //ofLogError("ofQuickTimeGrabber") << "(unavailable) device [" << deviceCount << "] " << p2cstr(pascalName); deviceCount++; } } return false; } #endif #endif
# <API key>: true require 'spec_helper' describe 'logging' do it "should have a logger" do expect(Dummy).to respond_to(:logger) end it "should be able to log debug methods" do expect(Dummy.logger).to respond_to(:debug) end it "should be settable" do expect(Dummy).to respond_to(:logger=) log = double Dummy.logger = log expect(Dummy.logger).to eq(log) end end
// RepeatExpression.h // iLogo #import "ScopedExpression.h" //#import "Expression.h" @interface RepeatExpression : ScopedExpression { Expression *variableExpression; NSMutableArray *commandExpression; } - (void)convert:(NSMutableArray*)commandList; - (NSMutableArray*)evaluate:(TurtleCommand*)lastTurtleCommand; @end
#include "ofp/tablestatus.h" #include "ofp/writable.h" using namespace ofp; bool TableStatus::validateInput(Validation *context) const { size_t length = context->length(); if (length < sizeof(TableStatus) + sizeof(TableDesc)) { log_debug("TableStatus too small", length); return false; } size_t remainingLength = length - sizeof(TableStatus); context->setLengthRemaining(remainingLength); // FIXME: make sure there is only one table? return table().validateInput(context); } UInt32 TableStatusBuilder::send(Writable *channel) { UInt8 version = channel->version(); UInt32 xid = channel->nextXid(); UInt16 msgLen = UInt16_narrow_cast(sizeof(msg_) + table_.writeSize(channel)); msg_.header_.setVersion(version); msg_.header_.setLength(msgLen); msg_.header_.setXid(xid); channel->write(&msg_, sizeof(msg_)); table_.write(channel); channel->flush(); return xid; }
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Post It App</title> <link rel="apple-touch-icon" sizes="57x57" href="/icon2015/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/icon2015/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/icon2015/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/icon2015/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/icon2015/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/icon2015/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/icon2015/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/icon2015/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/icon2015/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/icon2015/<API key>.png"> <link rel="icon" type="image/png" sizes="32x32" href="/icon2015/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/icon2015/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/icon2015/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="<API key>" content="#ffffff"> <meta name="<API key>" content="/icon2015/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="css/main.css"/> <link rel="stylesheet" type="text/css" href="bower_components/font-awesome/css/font-awesome.css"/> </head> <body> <div class="fullpage title imgbackground"> <div class="title-text"> Post IT app <p> Partner offer </p> </div> <a href="#content" class="arrow-down arrow-animation"><i class="fa fa-arrow-down"></i></a> </div> <div id="content"> <div class="container"> <div class="row"> <div class="text-center" style="padding-bottom:5vh;"> <h1>Hi!</h1> </div> <div class="col-md-offset-2 col-md-8 text-center"> <p> <b>Post IT app</b> has for aim to get youth interested in IT and to empower them in providing the basic IT concepts, <i>all without programming</i>. </p> <p>For the last two years, we have conducted a workshop for high school students, in which we teach them how to create business models and paper prototypes of applications. </p> <p>One of our main objectives is to train tomorrow’s decision makers in the digital world. </p> <p> Our second main objective is to question the stereotypical image of IT: we want to show that IT is a fun, challenging and creative field which can be explored regardless of gender, background, personality traits of skills! </p> <p style="padding-top:1em; padding-bottom:0.5em;"> A part of: </p> <a href="http://gbgtechweek.com" style="margin-left:3em"><img src="img/Gbgtechweek_solid.png"></a> </div> </div> </div> </div> <div class="onepage walker imgbackground" id="frågor"> <div class="container"> <div class="row"> <div class="col-md-offset-1 col-md-11" style="padding-bottom:4vh"> <h1 style="padding-bottom:3vh"> Packages </h1> </div> <div class="col-md-offset-1 col-md-5" style="padding-bottom:4vh"> <h4 class="gloria">Bronze Partnership <br> 1000kr</h4> <p>Small Logo in our video *</p> <p>Small Logo and explanatory text as a sponsor on social media</p> <p>Small Logo and name on our website *</p> <p>Small Logo in presentation</p> </div> <div class="col-md-5" style="padding-bottom:4vh"> <h4 class="gloria">Silver Partnership <br> 3000kr</h4> <p> <small>Everything in partnership bronze +</small> </p> <p>Silver sponsor on our website</p> <p>Logo and explanatory text as a sponsor on social media</p> <p>Logo in our presentation and an expressed thanks</p> </div> </div> <div class="row"> <div class="col-md-offset-1 col-md-5" style="padding-bottom:4vh"> <h4 class="gloria">Gold Partnership <br> 6000kr</h4> <p> <small>Everything in silver Partnership +</small> </p> <p>Big and clear thank you in the presentation</p> <p>2 seconds video time with a large logo *</p> <p>Slogans and medium sized logo on T-Shirts! *</p> </div> <div class="col-md-5" style="padding-bottom:4vh"> <h4 class="gloria">Platinum Partnership <br> 10000kr</h4> <p> <small>Everything in gold Partnership +</small> </p> <p> 4 second special video time with a large logo *</p> <p>Very clear communication that you are a co-organizer who made all that extra cool possible!</p> <p> The opportunity to pitch a whole minute!</p> </div> </div> <div class="row"> <div class=" col-md-10" style="padding-bottom:4vh"> <p>* Video and Tshirt requires that we reach our financial target of 20 000 SEK.</p> <p>PS: in the Silver, Gold and Platinum packages, we provide you with the possibility to distribute advertising goodies to our students.</p> </div> </div> </div> </div> </div> </div> </div> <script src="bower_components/jquery/dist/jquery.min.js"></script> <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <script src="js/main.js"></script> <script> (function (i, s, o, g, r, a, m) { i['<API key>'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.<API key>(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', ' ga('create', 'UA-61692156-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
#!/bin/sh # CYBERWATCH SAS - 2017 # Security fix for USN-2950-5 # Operating System: Ubuntu 14.04 LTS # Architecture: x86_64 # - samba:2:4.3.9+dfsg-0ubuntu0.14.04.3 # Last versions recommanded by security team: # - samba:2:4.3.11+dfsg-0ubuntu0.14.04.4 # CVE List: # - CVE-2015-5370 # - CVE-2016-2110 # - CVE-2016-2111 # - CVE-2016-2112 # - CVE-2016-2113 # - CVE-2016-2114 # - CVE-2016-2115 # - CVE-2016-2118 # More details: sudo apt-get install --only-upgrade samba=2:4.3.11+dfsg-0ubuntu0.14.04.4 -y
require 'delegate' module Bizflow module BusinessModel class SimpleWrapper < SimpleDelegator def self.wrap(item) new item end def self.wraps(items) res = items.map do |item| new item end res end end end end
class Solution { public int solution(int[] A) { int[] temArray = new int[A.length + 2]; for (int i = 0; i < A.length; i++) { temArray[A[i]] = 1; } for (int i = 1; i < temArray.length + 1; i++) { if(temArray[i] == 0){ return i; } } return A[A.length - 1] + 1; } }
function EditMovieCtrl(MovieService,$stateParams) { // ViewModel const edit = this; edit.title = 'Edit Movies' + $stateParams.id; edit.back = function(){ window.history.back() } edit.checker = function(bool){ if(bool=='true') return true; if(bool=='false') return false; } edit.click = function(bool,key){ edit.data[key] = !bool } MovieService.getID($stateParams.id).then(function(results){ if(results.status===404) edit.data.movies='not found' edit.data = results }) // MovieService.get().then(function(results){ // edit.movies = results edit.processForm = function(){ MovieService.put(edit.data).then(function(res){ console.log(res) }) } } EditMovieCtrl.$inject=['MovieService','$stateParams'] export default { name: 'EditMovieCtrl', fn: EditMovieCtrl };
# CGGameCircle Marmalade Lua Binding for Game Circle
/** * @fileoverview Rule to require or disallow line breaks inside braces. * @author Toru Nagashima */ "use strict"; // Requirements let astUtils = require("../ast-utils"); // Helpers // Schema objects. let OPTION_VALUE = { oneOf: [ { enum: ["always", "never"] }, { type: "object", properties: { multiline: { type: "boolean" }, minProperties: { type: "integer", minimum: 0 } }, <API key>: false, minProperties: 1 } ] }; /** * Normalizes a given option value. * * @param {string|Object|undefined} value - An option value to parse. * @returns {{multiline: boolean, minProperties: number}} Normalized option object. */ function <API key>(value) { let multiline = false; let minProperties = Number.POSITIVE_INFINITY; if (value) { if (value === "always") { minProperties = 0; } else if (value === "never") { minProperties = Number.POSITIVE_INFINITY; } else { multiline = Boolean(value.multiline); minProperties = value.minProperties || Number.POSITIVE_INFINITY; } } else { multiline = true; } return {multiline: multiline, minProperties: minProperties}; } /** * Normalizes a given option value. * * @param {string|Object|undefined} options - An option value to parse. * @returns {{ObjectExpression: {multiline: boolean, minProperties: number}, ObjectPattern: {multiline: boolean, minProperties: number}}} Normalized option object. */ function normalizeOptions(options) { if (options && (options.ObjectExpression || options.ObjectPattern)) { return { ObjectExpression: <API key>(options.ObjectExpression), ObjectPattern: <API key>(options.ObjectPattern) }; } let value = <API key>(options); return {ObjectExpression: value, ObjectPattern: value}; } // Rule Definition module.exports = { meta: { docs: { description: "enforce consistent line breaks inside braces", category: "Stylistic Issues", recommended: false }, fixable: "whitespace", schema: [ { oneOf: [ OPTION_VALUE, { type: "object", properties: { ObjectExpression: OPTION_VALUE, ObjectPattern: OPTION_VALUE }, <API key>: false, minProperties: 1 } ] } ] }, create: function(context) { let sourceCode = context.getSourceCode(); let normalizedOptions = normalizeOptions(context.options[0]); /** * Reports a given node if it violated this rule. * * @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node. * @param {{multiline: boolean, minProperties: number}} options - An option object. * @returns {void} */ function check(node) { let options = normalizedOptions[node.type]; let openBrace = sourceCode.getFirstToken(node); let closeBrace = sourceCode.getLastToken(node); let first = sourceCode.<API key>(openBrace); let last = sourceCode.<API key>(closeBrace); let needsLinebreaks = ( node.properties.length >= options.minProperties || ( options.multiline && node.properties.length > 0 && first.loc.start.line !== last.loc.end.line ) ); /* * Use tokens or comments to check multiline or not. * But use only tokens to check whether line breaks are needed. * This allows: * var obj = { // eslint-disable-line foo * a: 1 * } */ first = sourceCode.getTokenAfter(openBrace); last = sourceCode.getTokenBefore(closeBrace); if (needsLinebreaks) { if (astUtils.isTokenOnSameLine(openBrace, first)) { context.report({ message: "Expected a line break after this opening brace.", node: node, loc: openBrace.loc.start, fix: function(fixer) { return fixer.insertTextAfter(openBrace, "\n"); } }); } if (astUtils.isTokenOnSameLine(last, closeBrace)) { context.report({ message: "Expected a line break before this closing brace.", node: node, loc: closeBrace.loc.start, fix: function(fixer) { return fixer.insertTextBefore(closeBrace, "\n"); } }); } } else { if (!astUtils.isTokenOnSameLine(openBrace, first)) { context.report({ message: "Unexpected line break after this opening brace.", node: node, loc: openBrace.loc.start, fix: function(fixer) { return fixer.removeRange([ openBrace.range[1], first.range[0] ]); } }); } if (!astUtils.isTokenOnSameLine(last, closeBrace)) { context.report({ message: "Unexpected line break before this closing brace.", node: node, loc: closeBrace.loc.start, fix: function(fixer) { return fixer.removeRange([ last.range[1], closeBrace.range[0] ]); } }); } } } return { ObjectExpression: check, ObjectPattern: check }; } };
import random, math import gimp_be #from gimp_be.utils.quick import qL from gimp_be.image.layer import editLayerMask from effects import mirror import numpy as np import UndrawnTurtle as turtle def brushSize(size=-1): """" Set brush size """ image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if size < 1: size = random.randrange(2, ((image.height + image.width) / 8)) gimp_be.pdb.<API key>(size) # Set brush opacity def brushOpacity(op=-1): if op == -1: op = random.randrange(15, 100) gimp_be.pdb.<API key>(op) return op # Set random brush color no parameters set random def brushColor(r1=-1, g1=-1, b1=-1, r2=-1, g2=-1, b2=-1): if not r1 == -1: gimp_be.pdb.<API key>((r1, g1, b1)) if not r2 == -1: gimp_be.pdb.<API key>((r2, g2, b2)) elif r1 == -1: r1 = random.randrange(0, 255) g1 = random.randrange(0, 255) b1 = random.randrange(0, 255) r2 = random.randrange(0, 255) g2 = random.randrange(0, 255) b2 = random.randrange(0, 255) gimp_be.pdb.<API key>((r1, g1, b1)) gimp_be.pdb.<API key>((r2, g2, b2)) return (r1, g1, b1, r2, g2, b2) #set gray scale color def grayColor(gray_color): gimp_be.pdb.<API key>((gray_color, gray_color, gray_color)) # Set random brush def randomBrush(): num_brushes, brush_list = gimp_be.pdb.<API key>('') brush_pick = brush_list[random.randrange(0, len(brush_list))] gimp_be.pdb.<API key>(brush_pick) return brush_pick # Set random brush dynamics def randomDynamics(): dynamics_pick = random.choice(gimp_be.pdb.<API key>('')[1]) gimp_be.pdb.<API key>(dynamics_pick) return dynamics_pick def qL(): # quick new layer gimp_be.addNewLayer() image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) gimp_be.pdb.gimp_edit_fill(drawable, 1) def drawLine(points): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) gimp_be.pdb.<API key>(drawable, len(points), points) def drawSpiral(n=140, angle=61, step=10, center=[]): coord=[] nt=turtle.Turtle() if center == []: image = gimp_be.gimp.image_list()[0] center=[image.width/2,image.height/2] for step in range(n): coord.append(int(nt.position()[0]*10)+center[0]) coord.append(int(nt.position()[1]*10)+center[1]) nt.forward(step) nt.left(angle) coord.append(int(nt.position()[0]*10)+center[0]) coord.append(int(nt.position()[1]*10)+center[1]) drawLine(coord) def drawRays(rays=32, rayLength=100, centerX=0, centerY=0): """" draw N rays from center in active drawable with current brush """ image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if centerX == 0: centerX = image.width/2 if centerY == 0: centerY = image.height/2 ray_gap = int(360.0/rays) for ray in range(0,rays): ctrlPoints = centerX, centerY, centerX + rayLength * math.sin(math.radians(ray*ray_gap)), centerY + rayLength * math.cos(math.radians(ray*ray_gap)) drawLine(ctrlPoints) def drawRandomRays(rays=32, length=100, centerX=0, centerY=0,noise=0.3): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if centerX == 0: centerX = image.width/2 if centerY == 0: centerY = image.height/2 ray_gap = 360.0/rays for ray in range(0,rays): rayLength=random.choice(range(int(length-length*noise),int(length+length*noise))) random_angle=random.choice(np.arange(0.0,360.0,0.01)) ctrlPoints = [ centerX, centerY, centerX + int(rayLength * math.sin(math.radians(random_angle))), int(centerY + rayLength * math.cos(math.radians(random_angle)))] drawLine(ctrlPoints) def spikeBallStack(depth=20, layer_mode=6, flatten=0): for x in range(1,depth): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) qL() gimp_be.pdb.gimp_layer_set_mode(gimp_be.pdb.<API key>(image), layer_mode) drawRandomRays(rays=random.choice([32,64,128,4]), length=(image.height/2-image.height/12), centerX=image.width/2, centerY=image.height/2,noise=random.choice([0.3,0.1,0.8])) if flatten: if not x%flatten: gimp_be.pdb.gimp_image_flatten(image) def randomStrokes(num = 4, opt = 1): """ Draw random strokes of random size and random position """ image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) r = random.randrange for loopNum in range(0, num): if opt == 1: brushSize(35) drawLine(ctrlPoints) # draw random color bars, opt 3 uses random blend def drawBars(barNum=10, opt=3): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) barWidth =image.width/ barNum barLeft = 0 color = -1 for loopNum in range(0, barNum): gimp_be.pdb.<API key>(image, 2, barLeft, 0, barWidth, image.height) barLeft = barLeft + barWidth if opt == 3: randomBlend() elif opt == 2: color = brushColor() gimp_be.pdb.<API key>(drawable, 0, 0, 100, 0, 1, 0, gimp_be.<API key>, 0, 0) else: gimp_be.pdb.<API key>(drawable, 0, 0, 100, 0, 1, 0, gimp_be.<API key>, 0, 0) gimp_be.pdb.gimp_selection_none(image) return (barNum, opt, color) # draw carbon nano tube def drawCNT(): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) drawSinWave(1, 4, image.height * .42, 0, image.height / 2) gimp_be.pdb.gimp_paintbrush(drawable, 0, 4, (0, (image.height - 80),image.width, (image.height - 80)), 0, 0) gimp_be.pdb.gimp_paintbrush(drawable, 0, 4, (0, 80,image.width, 80), 0, 0) # draw sine wave def drawSinWave(bar_space=32, bar_length=-1, mag=70, x_offset=-1, y_offset=-1): image = gimp_be.gimp.image_list()[0] if y_offset == -1: y_offset = image.height/2 if x_offset == -1: x_offset = 0 if bar_length == -1: bar_length = image.height/6 steps = image.width / bar_space x = 0 for cStep in range(0, steps): x = cStep * bar_space + x_offset y = int(round(math.sin(x) * mag) + y_offset) ctrlPoints = x, int(y - round(bar_length / 2)), x, int(y + round(bar_length / 2)) drawLine(ctrlPoints) # draw sine wave def drawSinWaveDouble(barSpace, barLen, mag): image = gimp_be.gimp.image_list()[0] steps =image.width/ barSpace x = 0 for cStep in range(1, steps): x = cStep * barSpace y = int(abs(round(math.sin(x) * mag + image.height / 2))) ctrlPoints = x, int(y - round(barLen / 2)), x, int(y + round(barLen / 2)) drawLine(ctrlPoints) # draw a single brush point def drawBrush(x1, y1): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) ctrlPoints = (x1, y1, x1, y1) drawLine(ctrlPoints) # draw multiple brush points def drawMultiBrush(brush_strokes=24): image = gimp_be.gimp.image_list()[0] grid_width=image.width/int(math.sqrt(brush_strokes)) grid_height=image.height/int(math.sqrt(brush_strokes)) coord_x=0 coord_y = 0 for i in range(0, int(math.sqrt(brush_strokes))): coord_x = coord_x + grid_width for x in range(0, int(math.sqrt(brush_strokes))): coord_y = coord_y + grid_height drawBrush(coord_x, coord_y) coord_y = 0 def dotGrid(): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) for i in range(10,image.width-10,20): for x in range(10, image.height-10,20): grayColor(abs(i^3-x^3)%256) drawBrush(i+10,x+10) # draws random dots, opt does random color def randomCircleFill(num=20, size=100, opt=3, sq=1): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) for loopNum in range(0, num): cirPar = [random.randrange(0,image.width), random.randrange(0, image.height), random.randrange(10, size), random.randrange(10, size)] if opt % 2 == 0: brushColor() if sq: gimp_be.pdb.gimp_ellipse_select(image, cirPar[0], cirPar[1], cirPar[2], cirPar[2], 2, 1, 0, 0) else: gimp_be.pdb.gimp_ellipse_select(image, cirPar[0], cirPar[1], cirPar[2], cirPar[3], 2, 1, 0, 0) if opt % 3 == 3: randomBlend() else: gimp_be.pdb.<API key>(drawable, 0, 0, 100, 0, 1, 0, gimp_be.<API key>, 0, 0) gimp_be.pdb.gimp_selection_none(image) def randomRectFill(num=20, size=100, opt=3, sq=0): # draws square, opt does random color image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) selectMode = 2 if opt % 5 == 0: selectMode = 0 for loopNum in range(0, num): if opt % 2 == 0: brushColor() rectPar = [random.randrange(0,image.width), random.randrange(0, image.height), random.randrange(10, size), random.randrange(10, size)] if sq: gimp_be.pdb.<API key>(image, 2, rectPar[0], rectPar[1], rectPar[2], rectPar[2]) else: gimp_be.pdb.<API key>(image, 2, rectPar[0], rectPar[1], rectPar[2], rectPar[3]) if opt % 3 == 0: randomBlend() else: gimp_be.pdb.<API key>(drawable, 0, 0, 100, 0, 1, 0, gimp_be.<API key>, 0, 0) gimp_be.pdb.gimp_selection_none(image) def randomBlend(): # Random Blend tool test blend_mode = 0 paint_mode = 0 gradient_type = random.randrange(0, 10) opacity = random.randrange(20, 100) offset = 0 repeat = random.randrange(0, 2) reverse = 0 supersample = 0 max_depth = random.randrange(1, 9) threshold = 0 threshold = random.randrange(0, 1) dither = 0 image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) brushColor() x1 = random.randrange(0,image.width) y1 = random.randrange(0, image.height) x2 = random.randrange(0,image.width) y2 = random.randrange(0, image.height) gimp_be.pdb.gimp_blend(drawable, blend_mode, paint_mode, gradient_type, opacity, offset, repeat, reverse, supersample, max_depth, threshold, dither, x1, y1, x2, y2) def randomPoints(num=12): d = [] for x in range(num): d.append(choice(range(boarder,image.width-boarder))) d.append(choice(range(boarder,image.height-boarder))) return d def drawInkBlot(option=''): image=gimp_be.gimp.image_list()[0] layer=gimp_be.pdb.<API key>(image) if 'trippy' in option: layer_copy = gimp_be.pdb.gimp_layer_copy(layer, 0) gimp_be.pdb.<API key>(image, layer_copy,1) randomBlend() mask = gimp_be.pdb.<API key>(layer,5) gimp_be.pdb.<API key>(image, layer,mask) editLayerMask(1) randomCircleFill(num=15,size=800) brushColor(255,255,255) randomCircleFill(num=50,size=100) randomCircleFill(num=5,size=300) brushColor(0) randomCircleFill(num=20,size=600) randomCircleFill(num=50,size=400) randomCircleFill(num=100,size=100) brushColor(255,255,255) randomCircleFill(num=50,size=100) brushColor(0) drawable = gimp_be.pdb.<API key>(image) brushSize() strokes=[random.randrange(0,image.width/2),random.randrange(0,image.height),random.randrange(0,image.width/2),random.randrange(0,image.height)] gimp_be.pdb.gimp_smudge(drawable, random.choice([1,5,10,50,100]), len(strokes), strokes) brushSize() strokes=[random.randrange(0,image.width/2),random.randrange(0,image.height),random.randrange(0,image.width/2),random.randrange(0,image.height)] gimp_be.pdb.gimp_smudge(drawable, random.choice([1,5,10,50,100]), len(strokes), strokes) mirror('h') if 'trippy' in option and random.choice([0,1]): drawable = gimp_be.pdb.<API key>(image) gimp_be.pdb.gimp_invert(drawable) editLayerMask(0) def inkBlotStack(depth=16,layer_mode=6, flatten=0): for x in range(1,depth): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) qL() gimp_be.pdb.gimp_layer_set_mode(gimp_be.pdb.<API key>(image), layer_mode) drawInkBlot() if flatten: if not x%flatten: flatten() def gridCenters(grid=[]): if grid==[]: grid=[4,3] image = gimp_be.gimp.image_list()[0] row_width = image.width/(grid[0]) columb_height = image.height/(grid[1]) tile_centers = [] for row in range(0,grid[0]): for columb in range(0,grid[1]): tile_centers.append([row_width*row+row_width/2,columb_height*columb+columb_height/2]) return tile_centers def tile(grid=[],option="mibd",irregularity=0.3): image=gimp_be.gimp.image_list()[0] layer=gimp_be.pdb.<API key>(image) if grid==[]: if image.height == image.width: grid=[4,4] elif image.height < image.width: grid=[3,4] else: grid=[4,3] if "m" in option: mask = gimp_be.pdb.<API key>(layer,0) gimp_be.pdb.<API key>(image, layer,mask) editLayerMask(1) drawable = gimp_be.pdb.<API key>(image) grid_spacing = image.width/grid[0] tile_centers=gridCenters(grid) if irregularity > 0.0: i_tiles=[] for tile in tile_centers: tile[0]=tile[0]+random.randrange((-1*int(grid_spacing*irregularity)),int(grid_spacing*irregularity)) tile[1]=tile[1]+random.randrange((-1*int(grid_spacing*irregularity)),int(grid_spacing*irregularity)) i_tiles.append(tile) tile_centers=i_tiles if "b" in option: randomBrush() if "d" in option: randomDynamics() brushSize(grid_spacing) brushColor(0,0,0) for tile in tile_centers: if "m" in option: editLayerMask(1) if irregularity == 0: gimp_be.pdb.<API key>(drawable, len(tile), tile) elif random.randrange(50.0*irregularity)+random.randrange(50.0*irregularity)>50.0: randomDynamics() else: gimp_be.pdb.<API key>(drawable, len(tile), tile) if "g" in option: gimp_be.pdb.plug_in_gauss(image, drawable, 20.0, 20.0, 0) if "w" in option: gimp_be.pdb.plug_in_whirl_pinch(image, drawable, 90, 0.0, 1.0) if "i" in option: gimp_be.pdb.gimp_invert(drawable) if "m" in option: editLayerMask(0) def drawAkuTree(branches=6,tree_height=0, position=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if position==0: position=[] position.append(random.randrange(image.width)) position.append(random.randrange(4*tree_height/3, 3*image.height/4)) if tree_height == 0: tree_height=random.randrange(position[1]/3, position[1]-position[1]/25) print 'position:' + str(position) #draw trunk trunk=[position[0],position[1],position[0],position[1]-tree_height] trunk_size=tree_height/40+3 print str(trunk) print 'tree_height: ' + str(tree_height) print 'trunk size: ' + str(trunk_size) brushSize(trunk_size) drawLine(trunk) for node in range(branches): node_base=[position[0],position[1]-((node*tree_height+1)/branches+tree_height/25+random.randrange(-1*tree_height/12,tree_height/12))] base_length=tree_height/25 node_end=[] if node%2==0: node_end=[node_base[0]+base_length/2,node_base[1]-base_length/2] brushSize(2*trunk_size/3) drawLine([node_base[0],node_base[1],node_end[0],node_end[1]]) brushSize(trunk_size/3) drawLine([node_end[0],node_end[1],node_end[0],node_end[1]-tree_height/12-(tree_height/48)]) else: node_end=[node_base[0]-base_length/2,node_base[1]-base_length/2] brushSize(2*trunk_size/3) drawLine([node_base[0],node_base[1],node_end[0],node_end[1]]) brushSize(trunk_size/3) drawLine([node_end[0],node_end[1],node_end[0],node_end[1]-(tree_height/12)]) def drawAkuForest(num=25): for x in range(num): drawAkuTree() # draw a tree def drawTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if x1 == -1: x1 = image.width/2 if y1 == -1: y1 = image.height/2 x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0) ctrlPoints = (x1, y1, x2, y2) if recursiondepth <= 2: brushColor(87, 53, 12) elif depth == 1: brushColor(152, 90, 17) elif depth <= 3: brushColor(7, 145, 2) brushSize(depth * 4 + 5) gimp_be.pdb.<API key>(drawable, len(ctrlPoints), ctrlPoints) if depth > 0: drawTree(x2, y2, angle - 20, depth - 1, recursiondepth + 1) drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1) # draw a tree with 3 branches per node def drawTriTree(x1=-1, y1=-1, angle=270, depth=6, recursiondepth=0, size=10): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if x1 == -1: x1 = image.width/2 if y1 == -1: y1 = image.height/2 if depth: x2 = x1 + int(math.cos(math.radians(angle)) * depth * size) + random.randrange(-12, 12) y2 = y1 + int(math.sin(math.radians(angle)) * depth * size) + random.randrange(-12, 12) ctrlPoints = (x1, y1, x2, y2) brushSize(depth + int(size/10)) brushColor() gimp_be.pdb.<API key>(drawable, len(ctrlPoints), ctrlPoints) drawTriTree(x2, y2, angle - 30, depth - 1, recursiondepth + 1,size) drawTriTree(x2, y2, angle, depth - 1, recursiondepth + 1,size) drawTriTree(x2, y2, angle + 30, depth - 1, recursiondepth + 1,size) # draw random color tri-tree def drawColorTriTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if x1 == -1: x1 = image.width/2 if y1 == -1: y1 = image.height/2 brushSize(depth + 1) if depth: x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) + random.randrange(-12, 12) y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0) + random.randrange(-12, 12) ctrlPoints = (x1, y1, x2, y2) gimp_be.pdb.<API key>(drawable, len(ctrlPoints), ctrlPoints) drawColorTriTree(x2, y2, angle - 20 + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1) drawColorTriTree(x2, y2, angle + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1) drawColorTriTree(x2, y2, angle + 20 + random.choice(-10, -5, 0, 5, 10), depth - 1, recursiondepth + 1) # draw a tree def drawOddTree(x1=-1, y1=-1, angle=270, depth=9, recursiondepth=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if x1 == -1: x1 = image.width/2 if y1 == -1: y1 = image.height/2 brushSize((depth * 8 + 30)) if depth: x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0) ctrlPoints = (x1, y1, x2, y2) gimp_be.pdb.<API key>(drawable, len(ctrlPoints), ctrlPoints) if not random.randrange(0, 23) == 23: drawTree(x2, y2, angle - 20, depth - 1, recursiondepth + 1) if depth % 2 == 0: drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1) if (depth + 1) % 4 == 0: drawTree(x2, y2, angle + 20, depth - 1, recursiondepth + 1) if depth == 5: drawTree(x2, y2, angle - 45, depth - 1, recursiondepth + 1) drawTree(x2, y2, angle + 45, depth - 1, recursiondepth + 1) # draw a tree def drawForestTree(x1=-1, y1=-1, angle=270, depth=7, size=10, recursiondepth=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if x1 == -1: x1 = image.width/2 if y1 == -1: y1 = image.height/2 if depth: x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0) ctrlPoints = (x1, y1, x2, y2) brushSize(depth * depth * (int(size / ((image.height - y1)) / image.height)) + 4) gimp_be.pdb.<API key>(drawable, len(ctrlPoints), ctrlPoints) if not random.randrange(0, 23) == 23: drawForestTree(x2, y2, angle - 20, depth - 1, size, recursiondepth + 1) if random.randrange(0, 23) == 23: drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1) drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1) drawForestTree(x2, y2, angle - random.randrange(-30, 30), depth - 1, size, recursiondepth + 1) else: drawForestTree(x2, y2, angle - random.randrange(15, 50), depth - 1, size, recursiondepth + 1) if depth % 2 == 0: drawForestTree(x2, y2, angle + 20, depth - 1, size, recursiondepth + 1) if (depth + 1) % 4 == 0: drawForestTree(x2, y2, angle + 20, depth - 1, size, recursiondepth + 1) if depth == 5: drawForestTree(x2, y2, angle - 45, depth - 1, size, recursiondepth + 1) drawForestTree(x2, y2, angle + 45, depth - 1, size, recursiondepth + 1) # draw a series of trees with a y position based on depth def drawForest(trees, options): image = gimp_be.gimp.image_list()[0] for tree in range(0, trees): y1 = 2 * (image.height / 3) + random.randrange(-1 * (image.height / 5), image.height / 5) x1 = random.randrange(image.width / 20, 19 * (image.width / 20)) angle = random.randrange(250, 290) size = (y1 / (2.0 * (image.height / 3.0) + (image.height / 5.0))) + 4 depth = random.randrange(3, 7) drawForestTree(x1, y1, angle, depth, size) #draws polygon of N sides at a x-y location def drawPolygon(sides=5,size=300,x_pos=0,y_pos=0, angle_offset=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if y_pos==0: y_pos=image.height/2 if x_pos==0: x_pos=image.width/2 <API key>=360/sides points_list=[] for x in range(0,sides+1): point_degree=<API key>*x+angle_offset points_list.append(int(round(math.sin(math.radians(point_degree))*size))+x_pos) points_list.append(int(round(math.cos(math.radians(point_degree))*size))+y_pos) fade_out=0 method=0 gradient_length=0 gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length) #draw a grid of polygons of N sides def drawPolygonGrid(size=60,sides=3, angle_offset=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if sides%2 == 1 or sides>4: for y in range(0-image.height/10,image.height+image.height/10, size): x_loop=0 for x in range(0-image.width/10, image.width+image.width/10, size): if x_loop%2==1: drawPolygon(sides,size-size/2,x-(size/2),y,360/sides) else: drawPolygon(sides,size-size/2,x,y,0) x_loop=x_loop+1 else: for x in range(0-image.height/10,image.height+image.height/10, size): for y in range(0-image.width/10, image.width+image.width/10, size): drawPolygon(sides,size/3,x,y,0) <API key>=360/sides points_list=[] for x in range(0,sides+1): point_degree=math.radians(<API key>*x+angle_offset) points_list.append(int(round(math.sin(point_degree)*size))) points_list.append(int(round(math.cos(point_degree)*size))) fade_out=0 method=0 gradient_length=0 gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length) def drawFrygon(sides=5,size=300,x_pos=0,y_pos=0, angle_offset=0): image = gimp_be.gimp.image_list()[0] drawable = gimp_be.pdb.<API key>(image) if y_pos==0: y_pos=image.height/2 if x_pos==0: x_pos=image.width/2 <API key>=360/sides points_list=[] for x in range(0,sides+1): point_degree=<API key>*x+angle_offset points_list.append(int(round(math.sin(point_degree)*size))+y_pos) points_list.append(int(round(math.cos(point_degree)*size))+x_pos) fade_out=0 method=0 gradient_length=0 gimp_be.pdb.gimp_paintbrush(drawable, fade_out, len(points_list), points_list, method, gradient_length) def drawFrygonGrid(size=120,sides=13): global height, width if sides%2 == 1: for x in range(0,height,size): x_deep=0 for y in range(0, width,size): if x_deep%2==1: drawFrygon(sides,size,x,y-(size/2),0) else: drawFrygon(sides,size,x,y,0) x_deep=x_deep+1 else: for x in range(0,height, size): for y in range(0, width, size): drawFrygon(sides,size,x,y,0)
import {Option} from "./option"; export class HelpOption extends Option { constructor() { super(); this.shortName = 'h'; this.longName = 'help'; this.argument = ''; } }
import * as React from 'react'; import { createIcon } from '../Icon'; export const ShieldIcon = createIcon( <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />, 'ShieldIcon' );
"use strict"; var <API key> = Math.pow(2, 53); var util = { uuid: function(){ return Math.ceil(Math.random() * <API key>); } }; module.exports = util;
<?php namespace ToyLang\Core\Lexer; use ToyLang\Core\Lexer\Token\Token; use ToyLang\Core\Lexer\Token\TokenType; interface Lexer { /** * @param TokenType $tokenType * @return $this */ public function addTokenType(TokenType $tokenType); /** * @param TokenType[] $tokenTypes * @return $this */ public function addTokenTypes($tokenTypes); /** * @param $input * @return Token[] */ public function tokenize($input); }