repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
joshesp/ionic | src/navigation/nav-controller.ts | 24685 | import { EventEmitter } from '@angular/core';
import { Config } from '../config/config';
import { NavOptions } from './nav-util';
import { ViewController } from './view-controller';
/**
* @name NavController
* @description
*
* NavController is the base class for navigation controller components like
* [`Nav`](../../components/nav/Nav/) and [`Tab`](../../components/tabs/Tab/). You use navigation controllers
* to navigate to [pages](#view-creation) in your app. At a basic level, a
* navigation controller is an array of pages representing a particular history
* (of a Tab for example). This array can be manipulated to navigate throughout
* an app by pushing and popping pages or inserting and removing them at
* arbitrary locations in history.
*
* The current page is the last one in the array, or the top of the stack if we
* think of it that way. [Pushing](#push) a new page onto the top of the
* navigation stack causes the new page to be animated in, while [popping](#pop)
* the current page will navigate to the previous page in the stack.
*
* Unless you are using a directive like [NavPush](../../components/nav/NavPush/), or need a
* specific NavController, most times you will inject and use a reference to the
* nearest NavController to manipulate the navigation stack.
*
* ## Basic usage
* The simplest way to navigate through an app is to create and initialize a new
* nav controller using the `<ion-nav>` component. `ion-nav` extends the `NavController`
* class.
*
* ```typescript
* import { Component } from `@angular/core`;
* import { StartPage } from './start-page';
*
* @Component(
* template: `<ion-nav [root]="rootPage"></ion-nav>`
* })
* class MyApp {
* // set the rootPage to the first page we want displayed
* public rootPage: any = StartPage;
*
* constructor(){
* }
* }
*
* ```
*
* ### Injecting NavController
* Injecting NavController will always get you an instance of the nearest
* NavController, regardless of whether it is a Tab or a Nav.
*
* Behind the scenes, when Ionic instantiates a new NavController, it creates an
* injector with NavController bound to that instance (usually either a Nav or
* Tab) and adds the injector to its own providers. For more information on
* providers and dependency injection, see [Dependency Injection](https://angular.io/docs/ts/latest/guide/dependency-injection.html).
*
* Instead, you can inject NavController and know that it is the correct
* navigation controller for most situations (for more advanced situations, see
* [Menu](../../menu/Menu/) and [Tab](../../tab/Tab/)).
*
* ```ts
* import { NavController } from 'ionic-angular';
*
* class MyComponent {
* constructor(public navCtrl: NavController) {
*
* }
* }
* ```
*
* ### Navigating from the Root component
* What if you want to control navigation from your root app component?
* You can't inject `NavController` because any components that are navigation
* controllers are _children_ of the root component so they aren't available
* to be injected.
*
* By adding a reference variable to the `ion-nav`, you can use `@ViewChild` to
* get an instance of the `Nav` component, which is a navigation controller
* (it extends `NavController`):
*
* ```typescript
*
* import { Component, ViewChild } from '@angular/core';
* import { NavController } from 'ionic-angular';
*
* @Component({
* template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
* })
* export class MyApp {
* @ViewChild('myNav') nav: NavController
* public rootPage = TabsPage;
*
* // Wait for the components in MyApp's template to be initialized
* // In this case, we are waiting for the Nav with reference variable of "#myNav"
* ngOnInit() {
* // Let's navigate from TabsPage to Page1
* this.nav.push(Page1);
* }
* }
* ```
*
* ### Navigating from an Overlay Component
* What if you wanted to navigate from an overlay component (popover, modal, alert, etc)?
* In this example, we've displayed a popover in our app. From the popover, we'll get a
* reference of the root `NavController` in our app, using the `getRootNav()` method.
*
*
* ```typescript
* import { Component } from '@angular/core';
* import { App, ViewController } from 'ionic-angular';
*
* @Component({
* template: `
* <ion-content>
* <h1>My PopoverPage</h1>
* <button ion-button (click)="pushPage()">Call pushPage</button>
* </ion-content>
* `
* })
* class PopoverPage {
* constructor(
* public viewCtrl: ViewController
* public appCtrl: App
* ) {}
*
* pushPage() {
* this.viewCtrl.dismiss();
* this.appCtrl.getRootNav().push(SecondPage);
* }
* }
*```
*
*
* ## View creation
* Views are created when they are added to the navigation stack. For methods
* like [push()](#push), the NavController takes any component class that is
* decorated with `@Component` as its first argument. The NavController then
* compiles that component, adds it to the app and animates it into view.
*
* By default, pages are cached and left in the DOM if they are navigated away
* from but still in the navigation stack (the exiting page on a `push()` for
* example). They are destroyed when removed from the navigation stack (on
* [pop()](#pop) or [setRoot()](#setRoot)).
*
* ## Pushing a View
* To push a new view on to the navigation stack, use the `push` method.
* If the page has an [`<ion-navbar>`](../../navbar/Navbar/),
* a back button will automatically be added to the pushed view.
*
* Data can also be passed to a view by passing an object to the `push` method.
* The pushed view can then receive the data by accessing it via the `NavParams`
* class.
*
* ```typescript
* import { Component } from '@angular/core';
* import { NavController } from 'ionic-angular';
* import { OtherPage } from './other-page';
* @Component({
* template: `
* <ion-header>
* <ion-navbar>
* <ion-title>Login</ion-title>
* </ion-navbar>
* </ion-header>
*
* <ion-content>
* <button ion-button (click)="pushPage()">
* Go to OtherPage
* </button>
* </ion-content>
* `
* })
* export class StartPage {
* constructor(public navCtrl: NavController) {
* }
*
* pushPage(){
* // push another page on to the navigation stack
* // causing the nav controller to transition to the new page
* // optional data can also be passed to the pushed page.
* this.navCtrl.push(OtherPage, {
* id: "123",
* name: "Carl"
* });
* }
* }
*
* import { NavParams } from 'ionic-angular';
*
* @Component({
* template: `
* <ion-header>
* <ion-navbar>
* <ion-title>Other Page</ion-title>
* </ion-navbar>
* </ion-header>
* <ion-content>I'm the other page!</ion-content>`
* })
* class OtherPage {
* constructor(private navParams: NavParams) {
* let id = navParams.get('id');
* let name = navParams.get('name');
* }
* }
* ```
*
* ## Removing a view
* To remove a view from the stack, use the `pop` method.
* Popping a view will transition to the previous view.
*
* ```ts
* import { Component } from '@angular/core';
* import { NavController } from 'ionic-angular';
*
* @Component({
* template: `
* <ion-header>
* <ion-navbar>
* <ion-title>Other Page</ion-title>
* </ion-navbar>
* </ion-header>
* <ion-content>I'm the other page!</ion-content>`
* })
* class OtherPage {
* constructor(public navCtrl: NavController ){
* }
*
* popView(){
* this.navCtrl.pop();
* }
* }
* ```
*
* ## Lifecycle events
* Lifecycle events are fired during various stages of navigation. They can be
* defined in any component type which is pushed/popped from a `NavController`.
*
* ```ts
* import { Component } from '@angular/core';
*
* @Component({
* template: 'Hello World'
* })
* class HelloWorld {
* ionViewDidLoad() {
* console.log("I'm alive!");
* }
* ionViewWillLeave() {
* console.log("Looks like I'm about to leave :(");
* }
* }
* ```
*
* | Page Event | Returns | Description |
* |---------------------|-----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
* | `ionViewDidLoad` | void | Runs when the page has loaded. This event only happens once per page being created. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The `ionViewDidLoad` event is good place to put your setup code for the page. |
* | `ionViewWillEnter` | void | Runs when the page is about to enter and become the active page. |
* | `ionViewDidEnter` | void | Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page. |
* | `ionViewWillLeave` | void | Runs when the page is about to leave and no longer be the active page. |
* | `ionViewDidLeave` | void | Runs when the page has finished leaving and is no longer the active page. |
* | `ionViewWillUnload` | void | Runs when the page is about to be destroyed and have its elements removed. |
* | `ionViewCanEnter` | boolean/Promise<void> | Runs before the view can enter. This can be used as a sort of "guard" in authenticated views where you need to check permissions before the view can enter |
* | `ionViewCanLeave` | boolean/Promise<void> | Runs before the view can leave. This can be used as a sort of "guard" in authenticated views where you need to check permissions before the view can leave |
*
*
* ## Nav Guards
*
* In some cases, a developer should be able to control views leaving and entering. To allow for this, NavController has the `ionViewCanEnter` and `ionViewCanLeave` methods.
* Similar to Angular 2 route guards, but are more integrated with NavController. For example, if you wanted to prevent a user from leaving a view:
*
* ```ts
* export class MyClass{
* constructor(
* public navCtrl: NavController
* ){}
*
* pushPage(){
* this.navCtrl.push(DetailPage)
* .catch(()=> console.log('should I stay or should I go now'))
* }
*
* ionViewCanLeave(): boolean{
* // here we can either return true or false
* // depending on if we want to leave this view
* if(isValid(randomValue)){
* return true;
* } else {
* return false;
* }
* }
* }
* ```
*
* We need to make sure that or `navCtrl.push` has a catch in order to catch the and handle the error.
* If you need to prevent a view from entering, you can do the same thing
*
* ```ts
* export class MyClass{
* constructor(
* public navCtrl: NavController
* ){}
*
* pushPage(){
* this.navCtrl.push(DetailPage)
* .catch(()=> console.log('should I stay or should I go now'))
* }
*
* }
*
* export class DetailPage(){
* constructor(
* public navCtrl: NavController
* ){}
* ionViewCanEnter(): boolean{
* // here we can either return true or false
* // depending on if we want to leave this view
* if(isValid(randomValue)){
* return true;
* } else {
* return false;
* }
* }
* }
* ```
*
* Similar to `ionViewCanLeave` we still need a catch on the original `navCtrl.push` in order to handle it properly.
* When handling the back button in the `ion-navbar`, the catch is already taken care of for you by the framework.
*
* ## NavOptions
*
* Some methods on `NavController` allow for customizing the current transition.
* To do this, we can pass an object with the modified properites.
*
*
* | Property | Value | Description |
* |-----------|-----------|------------------------------------------------------------------------------------------------------------|
* | animate | `boolean` | Whether or not the transition should animate. |
* | animation | `string` | What kind of animation should be used. |
* | direction | `string` | The conceptual direction the user is navigating. For example, is the user navigating `forward`, or `back`? |
* | duration | `number` | The length in milliseconds the animation should take. |
* | easing | `string` | The easing for the animation. |
*
* The property 'animation' understands the following values: `md-transition`, `ios-transition` and `wp-transition`.
*
* @see {@link /docs/v2/components#navigation Navigation Component Docs}
*/
export abstract class NavController {
/**
* Observable to be subscribed to when a component is loaded.
* @returns {Observable} Returns an observable
*/
viewDidLoad: EventEmitter<any>;
/**
* Observable to be subscribed to when a component is about to be loaded.
* @returns {Observable} Returns an observable
*/
viewWillEnter: EventEmitter<any>;
/**
* Observable to be subscribed to when a component has fully become the active component.
* @returns {Observable} Returns an observable
*/
viewDidEnter: EventEmitter<any>;
/**
* Observable to be subscribed to when a component is about to leave, and no longer active.
* @returns {Observable} Returns an observable
*/
viewWillLeave: EventEmitter<any>;
/**
* Observable to be subscribed to when a component has fully left and is no longer active.
* @returns {Observable} Returns an observable
*/
viewDidLeave: EventEmitter<any>;
/**
* Observable to be subscribed to when a component is about to be unloaded and destroyed.
* @returns {Observable} Returns an observable
*/
viewWillUnload: EventEmitter<any>;
/**
* @private
*/
id: string;
/**
* The parent navigation instance. If this is the root nav, then
* it'll be `null`. A `Tab` instance's parent is `Tabs`, otherwise
* the parent would be another nav, if it's not already the root nav.
*/
parent: any;
/**
* @private
*/
config: Config;
/**
* Push a new component onto the current navigation stack. Pass any aditional information
* along as an object. This additional information is accessible through NavParams
*
* @param {Page} page The page component class you want to push on to the navigation stack
* @param {object} [params={}] Any nav-params you want to pass along to the next view
* @param {object} [opts={}] Nav options to go with this transition.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract push(page: any, params?: any, opts?: NavOptions, done?: Function): Promise<any>;
/**
* Inserts a component into the nav stack at the specified index. This is useful if
* you need to add a component at any point in your navigation stack.
*
*
* @param {number} insertIndex The index where to insert the page.
* @param {Page} page The component you want to insert into the nav stack.
* @param {object} [params={}] Any nav-params you want to pass along to the next page.
* @param {object} [opts={}] Nav options to go with this transition.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract insert(insertIndex: number, page: any, params?: any, opts?: NavOptions, done?: Function): Promise<any>;
/**
* Inserts an array of components into the nav stack at the specified index.
* The last component in the array will become instantiated as a view,
* and animate in to become the active view.
*
* @param {number} insertIndex The index where you want to insert the page.
* @param {array} insertPages An array of objects, each with a `page` and optionally `params` property.
* @param {object} [opts={}] Nav options to go with this transition.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract insertPages(insertIndex: number, insertPages: Array<{page: any, params?: any}>, opts?: NavOptions, done?: Function): Promise<any>;
/**
* Call to navigate back from a current component. Similar to `push()`, you
* can also pass navigation options.
*
* @param {object} [opts={}] Nav options to go with this transition.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract pop(opts?: NavOptions, done?: Function): Promise<any>;
/**
* Navigate back to the root of the stack, no matter how far back that is.
*
* @param {object} [opts={}] Nav options to go with this transition.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract popToRoot(opts?: NavOptions, done?: Function): Promise<any>;
/**
* @private
* Pop to a specific view in the history stack. If an already created
* instance of the page is not found in the stack, then it'll `setRoot`
* to the nav stack by removing all current pages and pushing on a
* new instance of the given page. Note that any params passed to
* this method are not used when an existing page instance has already
* been found in the stack. Nav params are only used by this method
* when a new instance needs to be created.
*
* @param {any} page A page can be a ViewController instance or string.
* @param {object} [params={}] Any nav-params to be used when a new view instance is created at the root.
* @param {object} [opts={}] Nav options to go with this transition.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract popTo(page: any, params?: any, opts?: NavOptions, done?: Function): Promise<any>;
/**
* @private
* Pop sequently all the pages in the stack.
*
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract popAll(): Promise<any[]>;
/**
* Removes a page from the nav stack at the specified index.
*
* @param {number} startIndex The starting index to remove pages from the stack. Default is the index of the last page.
* @param {number} [removeCount] The number of pages to remove, defaults to remove `1`.
* @param {object} [opts={}] Any options you want to use pass to transtion.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract remove(startIndex: number, removeCount?: number, opts?: NavOptions, done?: Function): Promise<any>;
/**
* Removes the specified view controller from the nav stack.
*
* @param {ViewController} [viewController] The viewcontroller to remove.
* @param {object} [opts={}] Any options you want to use pass to transtion.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract removeView(viewController: ViewController, opts?: NavOptions, done?: Function): Promise<any>;
/**
* Set the root for the current navigation stack.
* @param {Page|ViewController} page The name of the component you want to push on the navigation stack.
* @param {object} [params={}] Any nav-params you want to pass along to the next view.
* @param {object} [opts={}] Any options you want to use pass to transtion.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract setRoot(pageOrViewCtrl: any, params?: any, opts?: NavOptions, done?: Function): Promise<any>;
/**
* Set the views of the current navigation stack and navigate to the
* last view. By default animations are disabled, but they can be enabled
* by passing options to the navigation controller.You can also pass any
* navigation params to the individual pages in the array.
*
* @param {Array<{page:any, params: any}>} pages An array of objects, each with a `page` and optionally `params` property to load in the stack.
* @param {Object} [opts={}] Nav options to go with this transition.
* @returns {Promise} Returns a promise which is resolved when the transition has completed.
*/
abstract setPages(pages: {page: any, params?: any}[], opts?: NavOptions, done?: Function): Promise<any>;
/**
* @param {number} index The index of the page to get.
* @returns {ViewController} Returns the view controller that matches the given index.
*/
abstract getByIndex(index: number): ViewController;
/**
* @returns {ViewController} Returns the active page's view controller.
*/
abstract getActive(includeEntering?: boolean): ViewController;
/**
* Returns if the given view is the active view or not.
* @param {ViewController} view
* @returns {boolean}
*/
abstract isActive(view: ViewController): boolean;
/**
* Returns the view controller which is before the given view controller.
* If no view controller is passed in, then it'll default to the active view.
* @param {ViewController} view
* @returns {viewController}
*/
abstract getPrevious(view?: ViewController): ViewController;
/**
* Returns the first view controller in this nav controller's stack.
* @returns {ViewController}
*/
abstract first(): ViewController;
/**
* Returns the last page in this nav controller's stack.
* @returns {ViewController}
*/
abstract last(): ViewController;
/**
* Returns the index number of the given view controller.
* @param {ViewController} view
* @returns {number}
*/
abstract indexOf(view: ViewController): number;
/**
* Returns the number of views in this nav controller.
* @returns {number} The number of views in this stack, including the current view.
*/
abstract length(): number;
/**
* Returns the current stack of views in this nav controller.
* @returns {Array<ViewController>} the stack of view controllers in this nav controller.
*/
abstract getViews(): Array<ViewController>;
/**
* Returns the active child navigation.
*/
abstract getActiveChildNav(): any;
/**
* Returns if the nav controller is actively transitioning or not.
* @return {boolean}
*/
abstract isTransitioning(includeAncestors?: boolean): boolean
/**
* If it's possible to use swipe back or not. If it's not possible
* to go back, or swipe back is not enabled, then this will return `false`.
* If it is possible to go back, and swipe back is enabled, then this
* will return `true`.
* @returns {boolean}
*/
abstract canSwipeBack(): boolean;
/**
* Returns `true` if there's a valid previous page that we can pop
* back to. Otherwise returns `false`.
* @returns {boolean}
*/
abstract canGoBack(): boolean;
/**
* @private
*/
abstract registerChildNav(nav: any): void;
}
| mit |
gmhewett/bookshelf | www/Bookshelf/Bookshelf/App_Start/Startup.WebApi.cs | 1013 | namespace Bookshelf
{
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Owin;
public partial class Startup
{
public void ConfigureWebApi(IAppBuilder app)
{
HttpConfiguration.SuppressDefaultHostAuthentication();
HttpConfiguration.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
HttpConfiguration.MapHttpAttributeRoutes();
HttpConfiguration.Routes.MapHttpRoute(
name: "ApiActions",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
HttpConfiguration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseAutofacWebApi(HttpConfiguration);
app.UseWebApi(HttpConfiguration);
}
}
} | mit |
noppa/ng-hot-reload | packages/core/src/component.js | 2200 | import angularProvider from './ng/angular';
import isPrivateKey from './ng/private-key';
import controllerDefinition from './util/controller-definition.js';
function componentProvider(moduleName) {
const angular = angularProvider(),
{ isFunction, isArray, forEach } = angular;
/**
* Calls `this.directive` with "normalized" definition object.
*
* NOTE: This is almost an exact copy angular's own component function:
* https://github.com/angular/angular.js/blob/a03b75c6a812fcc2f616fc05c0f1710e03fca8e9/src/ng/compile.js#L1254
* and this function should be kept functionally equivalent to that one.
*
* @param {string} name Name of the component
* @param {Record<string, any>} options Component definition object
* @return {*} Whatever this.directive returns.
*/
function registerComponent(name, options) {
return this.directive(name, [
'$injector',
function($injector) {
const def = {
controller: options.controller || function() {},
controllerAs: identifierForController(options) || '$ctrl',
template: makeInjectable(
options.template || options.templateUrl ? options.template : ''),
templateUrl: makeInjectable(options.templateUrl),
transclude: options.transclude,
scope: {},
bindToController: options.bindings || {},
restrict: 'E',
require: options.require,
};
forEach(options, (val, key) => {
if (isPrivateKey(key)) {
def[key] = val;
}
});
function identifierForController(config) {
return controllerDefinition(config).controllerAs;
}
function makeInjectable(fn) {
if (isFunction(fn) || isArray(fn)) {
return function($element, $attrs) {
return $injector.invoke(fn, this, {
$element,
$attrs,
});
};
} else {
return fn;
}
}
return def;
},
]);
}
return {
create: registerComponent,
update: registerComponent,
};
}
export default componentProvider;
| mit |
Hanifah/e-fishauction | application/libraries/Ion_auth.php | 13910 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Name: Ion Auth
*
* Version: 2.5.2
*
* Author: Ben Edmunds
* ben.edmunds@gmail.com
* @benedmunds
*
* Added Awesomeness: Phil Sturgeon
*
* Location: http://github.com/benedmunds/CodeIgniter-Ion-Auth
*
* Created: 10.01.2009
*
* Description: Modified auth system based on redux_auth with extensive customization. This is basically what Redux Auth 2 should be.
* Original Author name has been kept but that does not mean that the method has not been modified.
*
* Requirements: PHP5 or above
*
*/
class Ion_auth
{
/**
* account status ('not_activated', etc ...)
*
* @var string
**/
protected $status;
/**
* extra where
*
* @var array
**/
public $_extra_where = array();
/**
* extra set
*
* @var array
**/
public $_extra_set = array();
/**
* caching of users and their groups
*
* @var array
**/
public $_cache_user_in_group;
/**
* __construct
*
* @return void
* @author Ben
**/
public function __construct()
{
$this->load->config('ion_auth', TRUE);
$this->load->library(array('email'));
$this->lang->load('ion_auth');
$this->load->helper(array('cookie', 'language','url'));
$this->load->library('session');
$this->load->model('ion_auth_model');
$this->_cache_user_in_group =& $this->ion_auth_model->_cache_user_in_group;
//auto-login the user if they are remembered
if (!$this->logged_in() && get_cookie($this->config->item('identity_cookie_name', 'ion_auth')) && get_cookie($this->config->item('remember_cookie_name', 'ion_auth')))
{
$this->ion_auth_model->login_remembered_user();
}
$email_config = $this->config->item('email_config', 'ion_auth');
if ($this->config->item('use_ci_email', 'ion_auth') && isset($email_config) && is_array($email_config))
{
$this->email->initialize($email_config);
}
$this->ion_auth_model->trigger_events('library_constructor');
}
/**
* __call
*
* Acts as a simple way to call model methods without loads of stupid alias'
*
**/
public function __call($method, $arguments)
{
if (!method_exists( $this->ion_auth_model, $method) )
{
throw new Exception('Undefined method Ion_auth::' . $method . '() called');
}
if($method == 'create_user')
{
return call_user_func_array(array($this, 'register'), $arguments);
}
if($method=='update_user')
{
return call_user_func_array(array($this, 'update'), $arguments);
}
return call_user_func_array( array($this->ion_auth_model, $method), $arguments);
}
/**
* __get
*
* Enables the use of CI super-global without having to define an extra variable.
*
* I can't remember where I first saw this, so thank you if you are the original author. -Militis
*
* @access public
* @param $var
* @return mixed
*/
public function __get($var)
{
return get_instance()->$var;
}
/**
* forgotten password feature
*
* @return mixed boolian / array
* @author Mathew
**/
public function forgotten_password($identity) //changed $email to $identity
{
if ( $this->ion_auth_model->forgotten_password($identity) ) //changed
{
// Get user information
$identifier = $this->ion_auth_model->identity_column; // use model identity column, so it can be overridden in a controller
$user = $this->where($identifier, $identity)->where('active', 1)->users()->row(); // changed to get_user_by_identity from email
if ($user)
{
$data = array(
'identity' => $user->{$this->config->item('identity', 'ion_auth')},
'forgotten_password_code' => $user->forgotten_password_code
);
if(!$this->config->item('use_ci_email', 'ion_auth'))
{
$this->set_message('forgot_password_successful');
return $data;
}
else
{
$message = $this->load->view($this->config->item('email_templates', 'ion_auth').$this->config->item('email_forgot_password', 'ion_auth'), $data, true);
$this->email->clear();
$this->email->from($this->config->item('admin_email', 'ion_auth'), $this->config->item('site_title', 'ion_auth'));
$this->email->to($user->email);
$this->email->subject($this->config->item('site_title', 'ion_auth') . ' - ' . $this->lang->line('email_forgotten_password_subject'));
$this->email->message($message);
if ($this->email->send())
{
$this->set_message('forgot_password_successful');
return TRUE;
}
else
{
$this->set_error('forgot_password_unsuccessful');
return FALSE;
}
}
}
else
{
$this->set_error('forgot_password_unsuccessful');
return FALSE;
}
}
else
{
$this->set_error('forgot_password_unsuccessful');
return FALSE;
}
}
/**
* forgotten_password_complete
*
* @return void
* @author Mathew
**/
public function forgotten_password_complete($code)
{
$this->ion_auth_model->trigger_events('pre_password_change');
$identity = $this->config->item('identity', 'ion_auth');
$profile = $this->where('forgotten_password_code', $code)->users()->row(); //pass the code to profile
if (!$profile)
{
$this->ion_auth_model->trigger_events(array('post_password_change', 'password_change_unsuccessful'));
$this->set_error('password_change_unsuccessful');
return FALSE;
}
$new_password = $this->ion_auth_model->forgotten_password_complete($code, $profile->salt);
if ($new_password)
{
$data = array(
'identity' => $profile->{$identity},
'new_password' => $new_password
);
if(!$this->config->item('use_ci_email', 'ion_auth'))
{
$this->set_message('password_change_successful');
$this->ion_auth_model->trigger_events(array('post_password_change', 'password_change_successful'));
return $data;
}
else
{
$message = $this->load->view($this->config->item('email_templates', 'ion_auth').$this->config->item('email_forgot_password_complete', 'ion_auth'), $data, true);
$this->email->clear();
$this->email->from($this->config->item('admin_email', 'ion_auth'), $this->config->item('site_title', 'ion_auth'));
$this->email->to($profile->email);
$this->email->subject($this->config->item('site_title', 'ion_auth') . ' - ' . $this->lang->line('email_new_password_subject'));
$this->email->message($message);
if ($this->email->send())
{
$this->set_message('password_change_successful');
$this->ion_auth_model->trigger_events(array('post_password_change', 'password_change_successful'));
return TRUE;
}
else
{
$this->set_error('password_change_unsuccessful');
$this->ion_auth_model->trigger_events(array('post_password_change', 'password_change_unsuccessful'));
return FALSE;
}
}
}
$this->ion_auth_model->trigger_events(array('post_password_change', 'password_change_unsuccessful'));
return FALSE;
}
/**
* forgotten_password_check
*
* @return void
* @author Michael
**/
public function forgotten_password_check($code)
{
$profile = $this->where('forgotten_password_code', $code)->users()->row(); //pass the code to profile
if (!is_object($profile))
{
$this->set_error('password_change_unsuccessful');
return FALSE;
}
else
{
if ($this->config->item('forgot_password_expiration', 'ion_auth') > 0) {
//Make sure it isn't expired
$expiration = $this->config->item('forgot_password_expiration', 'ion_auth');
if (time() - $profile->forgotten_password_time > $expiration) {
//it has expired
$this->clear_forgotten_password_code($code);
$this->set_error('password_change_unsuccessful');
return FALSE;
}
}
return $profile;
}
}
/**
* register
*
* @return void
* @author Mathew
**/
public function register($identity, $password, $email, $additional_data = array(), $group_ids = array()) //need to test email activation
{
$this->ion_auth_model->trigger_events('pre_account_creation');
$email_activation = $this->config->item('email_activation', 'ion_auth');
$id = $this->ion_auth_model->register($identity, $password, $email, $additional_data, $group_ids);
if (!$email_activation)
{
if ($id !== FALSE)
{
$this->set_message('account_creation_successful');
$this->ion_auth_model->trigger_events(array('post_account_creation', 'post_account_creation_successful'));
return $id;
}
else
{
$this->set_error('account_creation_unsuccessful');
$this->ion_auth_model->trigger_events(array('post_account_creation', 'post_account_creation_unsuccessful'));
return FALSE;
}
}
else
{
if (!$id)
{
$this->set_error('account_creation_unsuccessful');
return FALSE;
}
// deactivate so the user much follow the activation flow
$deactivate = $this->ion_auth_model->deactivate($id);
// the deactivate method call adds a message, here we need to clear that
$this->ion_auth_model->clear_messages();
if (!$deactivate)
{
$this->set_error('deactivate_unsuccessful');
$this->ion_auth_model->trigger_events(array('post_account_creation', 'post_account_creation_unsuccessful'));
return FALSE;
}
$activation_code = $this->ion_auth_model->activation_code;
$identity = $this->config->item('identity', 'ion_auth');
$user = $this->ion_auth_model->user($id)->row();
$data = array(
'identity' => $user->{$identity},
'id' => $user->id,
'email' => $email,
'activation' => $activation_code,
);
if(!$this->config->item('use_ci_email', 'ion_auth'))
{
$this->ion_auth_model->trigger_events(array('post_account_creation', 'post_account_creation_successful', 'activation_email_successful'));
$this->set_message('activation_email_successful');
return $data;
}
else
{
$message = $this->load->view($this->config->item('email_templates', 'ion_auth').$this->config->item('email_activate', 'ion_auth'), $data, true);
$this->email->clear();
$this->email->from($this->config->item('admin_email', 'ion_auth'), $this->config->item('site_title', 'ion_auth'));
$this->email->to($email);
$this->email->subject($this->config->item('site_title', 'ion_auth') . ' - ' . $this->lang->line('email_activation_subject'));
$this->email->message($message);
if ($this->email->send() == TRUE)
{
$this->ion_auth_model->trigger_events(array('post_account_creation', 'post_account_creation_successful', 'activation_email_successful'));
$this->set_message('activation_email_successful');
return $id;
}
}
$this->ion_auth_model->trigger_events(array('post_account_creation', 'post_account_creation_unsuccessful', 'activation_email_unsuccessful'));
$this->set_error('activation_email_unsuccessful');
return FALSE;
}
}
/**
* logout
*
* @return void
* @author Mathew
**/
public function logout()
{
$this->ion_auth_model->trigger_events('logout');
$identity = $this->config->item('identity', 'ion_auth');
if (substr(CI_VERSION, 0, 1) == '2')
{
$this->session->unset_userdata( array($identity => '', 'id' => '', 'user_id' => '') );
}
else
{
$this->session->unset_userdata( array($identity, 'id', 'user_id') );
}
// delete the remember me cookies if they exist
if (get_cookie($this->config->item('identity_cookie_name', 'ion_auth')))
{
delete_cookie($this->config->item('identity_cookie_name', 'ion_auth'));
}
if (get_cookie($this->config->item('remember_cookie_name', 'ion_auth')))
{
delete_cookie($this->config->item('remember_cookie_name', 'ion_auth'));
}
// Destroy the session
$this->session->sess_destroy();
//Recreate the session
if (substr(CI_VERSION, 0, 1) == '2')
{
$this->session->sess_create();
}
else
{
$this->session->sess_regenerate(TRUE);
}
$this->set_message('logout_successful');
return TRUE;
}
/**
* logged_in
*
* @return bool
* @author Mathew
**/
public function logged_in()
{
$this->ion_auth_model->trigger_events('logged_in');
return (bool) $this->session->userdata('identity');
}
/**
* logged_in
*
* @return integer
* @author jrmadsen67
**/
public function get_user_id()
{
$user_id = $this->session->userdata('user_id');
if (!empty($user_id))
{
return $user_id;
}
return null;
}
/**
* is_admin
*
* @return bool
* @author Ben Edmunds
**/
public function is_admin($id=false)
{
$this->ion_auth_model->trigger_events('is_admin');
$admin_group = $this->config->item('admin_group', 'ion_auth');
return $this->in_group($admin_group, $id);
}
/**
* in_group
*
* @param mixed group(s) to check
* @param bool user id
* @param bool check if all groups is present, or any of the groups
*
* @return bool
* @author Phil Sturgeon
**/
public function in_group($check_group, $id=false, $check_all = false)
{
$this->ion_auth_model->trigger_events('in_group');
$id || $id = $this->session->userdata('user_id');
if (!is_array($check_group))
{
$check_group = array($check_group);
}
if (isset($this->_cache_user_in_group[$id]))
{
$groups_array = $this->_cache_user_in_group[$id];
}
else
{
$users_groups = $this->ion_auth_model->get_users_groups($id)->result();
$groups_array = array();
foreach ($users_groups as $group)
{
$groups_array[$group->id] = $group->name;
}
$this->_cache_user_in_group[$id] = $groups_array;
}
foreach ($check_group as $key => $value)
{
$groups = (is_string($value)) ? $groups_array : array_keys($groups_array);
/**
* if !all (default), in_array
* if all, !in_array
*/
if (in_array($value, $groups) xor $check_all)
{
/**
* if !all (default), true
* if all, false
*/
return !$check_all;
}
}
/**
* if !all (default), false
* if all, true
*/
return $check_all;
}
}
| mit |
rngtng/websms-ruby | lib/websms.rb | 317 | # require 'mechanize'
#$:.unshift(File.dirname(__FILE__)) unless
# $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
# File.expand_path("../lib", __FILE__)
require 'websms/sms'
require 'websms/o2online'
# require 'websms/file'
# require 'websms/db'
module Websms
end
| mit |
charlescharles/mixcoin | src/mixcoin/mock_pool.go | 689 | package mixcoin
import (
"github.com/stretchr/testify/mock"
)
type MockPool struct {
mock.Mock
}
func (p *MockPool) ReceivingKeys() []string {
args := p.Mock.Called()
return args.Get(0).([]string)
}
func (p *MockPool) Scan(k []string) []PoolItem {
args := p.Mock.Called(k)
return args.Get(0).([]PoolItem)
}
func (p *MockPool) Filter(f func(PoolItem) bool) {
p.Mock.Called(f)
}
func (p *MockPool) Get(t PoolType) (PoolItem, error) {
args := p.Mock.Called(t)
return args.Get(0).(PoolItem), args.Error(1)
}
func (p *MockPool) Put(t PoolType, i PoolItem) {
p.Mock.Called(t, i)
}
func (p *MockPool) Shutdown() {
return
}
func NewMockPool() *MockPool {
return &MockPool{}
}
| mit |
thushanp/thushanp.github.io | vendor/twilio/sdk/Twilio/Rest/Api/V2010/Account/MessageContext.php | 5177 | <?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Api\V2010\Account;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Rest\Api\V2010\Account\Message\FeedbackList;
use Twilio\Rest\Api\V2010\Account\Message\MediaList;
use Twilio\Values;
use Twilio\Version;
/**
* @property \Twilio\Rest\Api\V2010\Account\Message\MediaList media
* @property \Twilio\Rest\Api\V2010\Account\Message\FeedbackList feedback
* @method \Twilio\Rest\Api\V2010\Account\Message\MediaContext media(string $sid)
*/
class MessageContext extends InstanceContext {
protected $_media = null;
protected $_feedback = null;
/**
* Initialize the MessageContext
*
* @param \Twilio\Version $version Version that contains the resource
* @param string $accountSid The account_sid
* @param string $sid Fetch by unique message Sid
* @return \Twilio\Rest\Api\V2010\Account\MessageContext
*/
public function __construct(Version $version, $accountSid, $sid) {
parent::__construct($version);
// Path Solution
$this->solution = array(
'accountSid' => $accountSid,
'sid' => $sid,
);
$this->uri = '/Accounts/' . rawurlencode($accountSid) . '/Messages/' . rawurlencode($sid) . '.json';
}
/**
* Deletes the MessageInstance
*
* @return boolean True if delete succeeds, false otherwise
*/
public function delete() {
return $this->version->delete('delete', $this->uri);
}
/**
* Fetch a MessageInstance
*
* @return MessageInstance Fetched MessageInstance
*/
public function fetch() {
$params = Values::of(array());
$payload = $this->version->fetch(
'GET',
$this->uri,
$params
);
return new MessageInstance(
$this->version,
$payload,
$this->solution['accountSid'],
$this->solution['sid']
);
}
/**
* Update the MessageInstance
*
* @param string $body The body
* @return MessageInstance Updated MessageInstance
*/
public function update($body) {
$data = Values::of(array(
'Body' => $body,
));
$payload = $this->version->update(
'POST',
$this->uri,
array(),
$data
);
return new MessageInstance(
$this->version,
$payload,
$this->solution['accountSid'],
$this->solution['sid']
);
}
/**
* Access the media
*
* @return \Twilio\Rest\Api\V2010\Account\Message\MediaList
*/
protected function getMedia() {
if (!$this->_media) {
$this->_media = new MediaList(
$this->version,
$this->solution['accountSid'],
$this->solution['sid']
);
}
return $this->_media;
}
/**
* Access the feedback
*
* @return \Twilio\Rest\Api\V2010\Account\Message\FeedbackList
*/
protected function getFeedback() {
if (!$this->_feedback) {
$this->_feedback = new FeedbackList(
$this->version,
$this->solution['accountSid'],
$this->solution['sid']
);
}
return $this->_feedback;
}
/**
* Magic getter to lazy load subresources
*
* @param string $name Subresource to return
* @return \Twilio\ListResource The requested subresource
* @throws \Twilio\Exceptions\TwilioException For unknown subresources
*/
public function __get($name) {
if (property_exists($this, '_' . $name)) {
$method = 'get' . ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown subresource ' . $name);
}
/**
* Magic caller to get resource contexts
*
* @param string $name Resource to return
* @param array $arguments Context parameters
* @return \Twilio\InstanceContext The requested resource context
* @throws \Twilio\Exceptions\TwilioException For unknown resource
*/
public function __call($name, $arguments) {
$property = $this->$name;
if (method_exists($property, 'getContext')) {
return call_user_func_array(array($property, 'getContext'), $arguments);
}
throw new TwilioException('Resource does not have a context');
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
$context = array();
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Api.V2010.MessageContext ' . implode(' ', $context) . ']';
}
} | mit |
sunyoboy/java-tutorial | java-tutorial/src/main/java/com/javase/net/jcip/examples/BetterAttributeStore.java | 760 | package com.javase.net.jcip.examples;
import java.util.*;
import java.util.regex.*;
import com.javase.net.jcip.annotations.*;
/**
* BetterAttributeStore
* <p/>
* Reducing lock duration
*
* @author Brian Goetz and Tim Peierls
*/
@ThreadSafe
public class BetterAttributeStore {
@GuardedBy("this") private final Map<String, String>
attributes = new HashMap<String, String>();
public boolean userLocationMatches(String name, String regexp) {
String key = "users." + name + ".location";
String location;
synchronized (this) {
location = attributes.get(key);
}
if (location == null)
return false;
else
return Pattern.matches(regexp, location);
}
}
| mit |
ykoziy/Design-Patterns-in-Java | Decorator/GarlicSub.java | 207 | public class GarlicSub implements Sub {
@Override
public String getDescription() {
return "Garlic Bread";
}
@Override
public double getCost() {
return 4.50;
}
}
| mit |
seekinternational/seek-asia-style-guide | docs/src/components/SketchExports/fixSketchRendering/fixSketchRendering.js | 3265 | import styles from './fixSketchRendering.less';
export default rootEl => {
// Require canvg dynamically because it can't run in a Node context
const canvg = require('canvg-fixed');
// Total hack until html-sketchapp supports before and after pseudo elements
// GitHub Issue: https://github.com/brainly/html-sketchapp/issues/20
Array.from(rootEl.querySelectorAll('*')).forEach(el => {
const elementBeforeStyles = window.getComputedStyle(el, ':before');
const elementAfterStyles = window.getComputedStyle(el, ':after');
const elementBeforeContent = elementBeforeStyles.content;
const elementAfterContent = elementAfterStyles.content;
if (elementBeforeContent) {
const virtualBefore = document.createElement('span');
virtualBefore.setAttribute('style', elementBeforeStyles.cssText);
virtualBefore.innerHTML = elementBeforeStyles.content.split('"').join('');
el.classList.add(styles.beforeReset);
el.prepend(virtualBefore);
}
if (elementAfterContent) {
const virtualAfter = document.createElement('span');
virtualAfter.setAttribute('style', elementAfterStyles.cssText);
virtualAfter.innerHTML = elementAfterStyles.content.split('"').join('');
el.classList.add(styles.afterReset);
el.appendChild(virtualAfter);
}
});
// Another hack to remove visually-hidden elements that html-sketchapp erroneously renders
Array.from(rootEl.querySelectorAll('*')).forEach(el => {
// Don't remove checkboxes or it breaks our custom checkbox CSS rules
// Plus, Sketch doesn't seem to render them, anyway
if (el.nodeName === 'INPUT' && el.type === 'checkbox') {
return;
}
const style = window.getComputedStyle(el);
if (
(style.position === 'absolute' && style.opacity === '0') ||
style.clip === 'rect(1px 1px 1px 1px)' // ScreenReaderOnly
) {
el.parentNode.removeChild(el);
}
});
// Another hack until html-sketchapp supports SVG
// GitHub Issue: https://github.com/brainly/html-sketchapp/issues/4
Array.from(rootEl.querySelectorAll('svg')).forEach(svg => {
const style = window.getComputedStyle(svg);
// Ensure cascading colours are transferred onto the SVG itself
svg.setAttribute('fill', style.fill);
svg.setAttribute('stroke', style.stroke);
Array.from(svg.querySelectorAll('path')).forEach(path => {
const pathStyle = window.getComputedStyle(path);
path.setAttribute('fill', pathStyle.fill);
path.setAttribute('stroke', pathStyle.stroke);
});
// Quadruple the SVG's size so we can maintain quality
const scale = 4;
const width = parseInt(style.width, 10) * scale;
const height = parseInt(style.height, 10) * scale;
svg.style.width = `${width}px`;
svg.style.height = `${height}px`;
// Parse SVG to canvas
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvg(canvas, svg.outerHTML);
// Replace original SVG with an image
const img = new Image();
img.src = canvas.toDataURL();
img.classList = svg.classList;
img.style.width = `${width / scale}px`;
img.style.height = `${height / scale}px`;
svg.parentNode.replaceChild(img, svg);
});
};
| mit |
danmakenoise/a_series_of_tubes | bin/example_servers/session_usage.rb | 501 | require 'rack'
require_relative '../../lib/tube_controller.rb'
APP_DIRECTORY = './bin/example_servers'
APP_NAME = 'counting'
class CountController < TubeController
def go
session["count"] ||= 0
session["count"] += 1
render :counting_show
end
end
server_app = Proc.new do |env|
request = Rack::Request.new env
response = Rack::Response.new
controller = CountController.new request, response
controller.go
response.finish
end
Rack::Server.start app: server_app, Port: 3000
| mit |
lucasprograms/js-chess | src/app/pieces/queen.js | 322 | (function () {
if (typeof Chess === "undefined") {
window.Chess = {};
}
var Queen = Chess.Queen = function(color, pos, type) {
Chess.Slideable.call(this, color, pos, type);
this.moveDirs = Chess.Slideable.DIAG_DIRS.concat(Chess.Slideable.HZ_AND_VT_DIRS);
};
Queen.inherits(Chess.Slideable);
})();
| mit |
andikanugraha11/CI-Dasar | application/models/Api_model.php | 477 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
*
*/
class Api_model extends CI_Model
{
public function hitungMember()
{
return $this->db->count_all_results('member');
}
public function getMember($size,$page)
{
return $this->db->get('mahasiswa', $size, $page);
}
// public function ibacorListDarah()
// {
// $obj = json_decode('http://ibacor.com/api/ayodonor?view=list_darah');
// return $obj;
// }
} | mit |
kuddai/EstateAgency | app/js/directives/askiEllipsis.js | 3376 | /*
@name: askEllipsis
@description:
It is angular wrapper above jquery plugin dotdotdot (http://dotdotdot.frebsite.nl/). It is used to cut long text and replace extra text with ...
aski-ellipsis attribute syntax should be "scope_var" or "{scope_var} in {css_query_of_parent_container}" where scope_var
is a binding variable containing text which will be cut through dotdotdot plugin. css_query_of_parent_container is needed
to set proper width and height bounds for dotdotdot plugin to keep aski-ellipsis directive responsive to changes of size of parent_container.
It relies on
If css_query_of_parent_container is not given then the direct parent of the element (element which contains aski-ellipsis directive)
is used.
To start updating on parent container resize scope event 'askResize::resize' must be invoked.
Usage examples:
1)
<div class="v-wrap">
<div class="v-box">
<div aski-ellipsis="offer.extra in .v-wrap"></div>
</div>
</div>
here v-wrap is used as parent container and offer.extra is our model in the scope
2)
<div class="v-wrap">
<div class="v-box">
<div aski-ellipsis="offer.extra"></div>
</div>
</div>
here v-box is used as parent container because we didn't specify css_query_of_parent_container explicitly and
v-box is direct parent of element which contains aski-ellipsis directive
*/
angular.module('EstateAgency').directive('askiEllipsis', ["$parse" ,function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, $el, attrs, ngModel) {
//parent container
var $ctr = (attrs.askiCtrQuery) ? $el.parents(attrs.ctrQuery) : $el.parent(),
//ellipsis symbol
ellipsisSym = attrs.askiEllipsis || '... ',
events = (attrs.askiUpdateOn || "askiEllipsis::update").split();
var updateView = function() {
//destroy dotdotdot plugin to ensure the default behaviour of height
$el.trigger("destroy.dot");
//restore auto height to ensure fit-content in case $ctr is not overflowed
$el.height("auto");
//update our view
$el.text(ngModel.$modelValue);
//replace excessive text with ellipsis symbol if $ctr is overflowed
if ($el.height() > $ctr.height()) {
$el.height($ctr.height());
$el.dotdotdot({
wrap: 'word',
fallbackToLetter: true,
ellipsis: ellipsisSym
});
}
};
//we must update in two cases: when our model is changed or when size of our parent container is changed.
ngModel.$render = updateView;
//subscribe for all update events (such as resize)
angular.forEach(events, function(eventName, key) {
scope.$on(eventName, updateView);
});
//cleaning up after ourselves
scope.$on("$destroy", function() {
//destroy dotdotdot plugin
$el.trigger("destroy.dot");
//$el.remove();
});
updateView();
}
};
}]); | mit |
bichbich/Famicity2 | src/MyAppBundle/Entity/User.php | 458 | <?php
namespace MyAppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
} | mit |
lupascugabrielcristian/PubMeWeb | Mobile/www/js/controllers/home.controller.js | 236 | var HomeCtrl = function ($scope, user) {
$scope.var = "Home Controller ok";
$scope.userLoggedIn = user.isLoggedIn();
};
HomeCtrl.$inject = ['$scope', 'user'];
angular.module('starter.controllers').controller('HomeCtrl', HomeCtrl);
| mit |
karim/adila | database/src/main/java/adila/db/degasvelte_sm2dt2397.java | 254 | // This file is automatically generated.
package adila.db;
/*
* Samsung Galaxy Tab 4 7.0
*
* DEVICE: degasvelte
* MODEL: SM-T2397
*/
final class degasvelte_sm2dt2397 {
public static final String DATA = "Samsung|Galaxy Tab 4 7.0|Galaxy Tab";
}
| mit |
NetOfficeFw/NetOffice | Source/Excel/Interfaces/ITableStyles.cs | 7639 | using System.Collections;
using System.Collections.Generic;
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.CollectionsGeneric;
namespace NetOffice.ExcelApi
{
/// <summary>
/// Interface ITableStyles
/// SupportByVersion Excel, 12,14,15,16
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
[EntityType(EntityType.IsInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Property), HasIndexProperty(IndexInvoke.Property, "_Default")]
public class ITableStyles : COMObject, IEnumerableProvider<NetOffice.ExcelApi.TableStyle>
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(ITableStyles);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public ITableStyles(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public ITableStyles(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyles(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyles(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyles(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyles(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyles() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyles(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.Application Application
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("Excel", 12,14,15,16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
public Int32 Count
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "Count");
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
/// <param name="index">object index</param>
[SupportByVersion("Excel", 12,14,15,16)]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty]
public NetOffice.ExcelApi.TableStyle this[object index]
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.TableStyle>(this, "_Default", NetOffice.ExcelApi.TableStyle.LateBindingApiWrapperType, index);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="tableStyleName">string tableStyleName</param>
[SupportByVersion("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.TableStyle Add(string tableStyleName)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.TableStyle>(this, "Add", NetOffice.ExcelApi.TableStyle.LateBindingApiWrapperType, tableStyleName);
}
#endregion
#region IEnumerableProvider<NetOffice.ExcelApi.TableStyle>
ICOMObject IEnumerableProvider<NetOffice.ExcelApi.TableStyle>.GetComObjectEnumerator(ICOMObject parent)
{
return NetOffice.Utils.GetComObjectEnumeratorAsProperty(parent, this, false);
}
IEnumerable IEnumerableProvider<NetOffice.ExcelApi.TableStyle>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator)
{
return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false);
}
#endregion
#region IEnumerable<NetOffice.ExcelApi.TableStyle>
/// <summary>
/// SupportByVersion Excel, 12,14,15,16
/// </summary>
[SupportByVersion("Excel", 12, 14, 15, 16)]
public IEnumerator<NetOffice.ExcelApi.TableStyle> GetEnumerator()
{
NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable);
foreach (NetOffice.ExcelApi.TableStyle item in innerEnumerator)
yield return item;
}
#endregion
#region IEnumerable
/// <summary>
/// SupportByVersion Excel, 12,14,15,16
/// </summary>
[SupportByVersion("Excel", 12,14,15,16)]
IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator()
{
return NetOffice.Utils.GetProxyEnumeratorAsProperty(this, false);
}
#endregion
#pragma warning restore
}
} | mit |
liuycsd/bypy | bypy/gvar.py | 875 | #!/usr/bin/env python
# encoding: utf-8
# PYTHON_ARGCOMPLETE_OK
# from __future__ imports must occur at the beginning of the file
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import locale
import time
from . import const
## global variables
SystemLanguageCode, SystemEncoding = locale.getdefaultlocale()
# the previous time stdout was flushed, maybe we just flush every time, or maybe this way performs better
# http://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print
last_stdout_flush = time.time()
#last_stdout_flush = 0
# save cache if more than 10 minutes passed
last_cache_save = time.time()
# mutable, the actual ones used, capital ones are supposed to be immutable
# this is introduced to support mirrors
pcsurl = const.PcsUrl
cpcsurl = const.CPcsUrl
dpcsurl = const.DPcsUrl
| mit |
wix/wix-style-react | packages/wix-style-react/src/Breadcrumbs/Breadcrumbs.driver.d.ts | 567 | import { BaseDriver } from 'wix-ui-test-utils/driver-factory';
export interface BreadcrumbsDriver extends BaseDriver {
breadcrumbsLength: () => number;
breadcrumbContentAt: (position: number) => string | null;
clickBreadcrumbAt: (position: number) => any;
getActiveItemId: () => number | null;
isLarge: () => boolean;
isMedium: () => boolean;
isOnWhiteBackground: () => boolean;
isOnGrayBackground: () => boolean;
isOnDarkBackground: () => boolean;
getLabelClassList: (position: number) => string;
isActiveLinkAt: (index: number) => boolean;
}
| mit |
lutsykigor/Perfectial.EntityFramework.Enterprise.Sample | packages/Portable.DataAnnotations.1.0.0/src/Portable.DataAnnotations.Net45Portable/ValidationAttributes/Schema/DatabaseGeneratedOption.cs | 608 | namespace System.ComponentModel.DataAnnotations.Schema
{
/// <summary>
/// The pattern used to generate values for a property in the database.
/// </summary>
public enum DatabaseGeneratedOption
{
/// <summary>
/// The database does not generate values.
/// </summary>
None,
/// <summary>
/// The database generates a value when a row is inserted.
/// </summary>
Identity,
/// <summary>
/// The database generates a value when a row is inserted or updated.
/// </summary>
Computed
}
} | mit |
MayaKaka/cartoonjs | src/shapes/Rect.js | 655 |
define(function (require) {
'use strict';
var Shape = require('shapes/Shape');
var Rect = Shape.extend({
type: 'Rect',
draw: function(ctx) {
var hasFill = this.setFill(ctx),
hasStroke = this.setStroke(ctx);
// 绘制矩形
ctx.beginPath();
ctx.rect(0, 0, this.width, this.height);
ctx.closePath();
hasFill && ctx.fill();
hasStroke && ctx.stroke();
},
_initGraphics: function(props) {
this.style({
fill: props.fill,
stroke: props.stroke,
strokeWidth: props.strokeWidth || 1
});
}
});
return Rect;
}); | mit |
ianunruh/fountain | spec/support/envelope_shared.rb | 1355 | shared_examples 'an envelope' do
describe '#headers' do
it 'acts like Hash' do
expect(subject.headers).to be_a(Hash)
end
end
describe '#timestamp' do
it 'acts like Time' do
expect(subject.timestamp).to be_a(Time)
end
end
describe '#and_headers' do
it 'returns a duplicate envelope with merged headers' do
x = { foo: 0, bar: 1 }
y = { foo: 2, baz: 3 }
mx = subject.and_headers(x)
expect(mx.headers).to eql(x)
my = mx.and_headers(y)
expect(my.headers).to eql(x.merge(y))
end
it 'returns itself when no additional headers are given' do
m = subject.and_headers({})
expect(m).to be(subject)
end
end
describe '#with_headers' do
it 'returns a duplicate envelope with replaced headers' do
x = { foo: 0, bar: 1 }
y = { foo: 2, baz: 3 }
mx = subject.with_headers(x)
expect(mx.headers).to be(x)
my = mx.with_headers(y)
expect(my.headers).to be(y)
end
it 'returns itself when the replacement headers are the same' do
x = { foo: 0 }
mx = subject.with_headers(x)
my = mx.with_headers(x)
expect(mx).to be(my)
end
end
describe '#payload_type' do
it 'returns the class of the payload' do
expect(subject.payload_type).to be(subject.payload.class)
end
end
end
| mit |
GreanTech/Exude | Src/Exude.UnitTests/Scenario.cs | 2742 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace Grean.Exude.UnitTests
{
public class Scenario
{
[FirstClassTests]
public static IEnumerable<ITestCase> YieldFirstClassTests()
{
yield return new TestCase(_ => Assert.Equal(1, 1));
yield return new TestCase(_ => Assert.Equal(2, 2));
yield return new TestCase(_ => Assert.Equal(3, 3));
yield return new TestCase(() => Assert.Equal(1, 1));
yield return new TestCase(() => Assert.Equal(2, 2));
yield return new TestCase(() => Assert.Equal(3, 3));
}
[FirstClassTests]
public static ITestCase[] ProjectTestCasesAsArray()
{
var testCases = new[] {
new { x = 1, y = 2 },
new { x = 3, y = 8 },
new { x = 42, y = 1337 },
};
return testCases
.Select(tc => new TestCase(_ =>
Assert.True(tc.x < tc.y)))
.ToArray();
}
public void AParameterizedTest(DateTimeOffset x, DateTimeOffset y)
{
Assert.True(x < y);
}
[FirstClassTests]
public static TestCase<Scenario>[] RunAParameterizedTest()
{
var testCases = new[]
{
new
{
x = new DateTimeOffset(2002, 10, 12, 18, 15, 0, TimeSpan.FromHours(1)),
y = new DateTimeOffset(2007, 4, 21, 18, 15, 0, TimeSpan.FromHours(1))
},
new
{
x = new DateTimeOffset(1970, 11, 25, 16, 10, 0, TimeSpan.FromHours(1)),
y = new DateTimeOffset(1972, 6, 6, 8, 5, 0, TimeSpan.FromHours(1))
},
new
{
x = new DateTimeOffset(2014, 3, 2, 17, 18, 45, TimeSpan.FromHours(1)),
y = new DateTimeOffset(2014, 3, 2, 17, 18, 45, TimeSpan.FromHours(0))
}
};
return testCases
.Select(tc =>
new TestCase<Scenario>(
s => s.AParameterizedTest(tc.x, tc.y)))
.ToArray();
}
public static class Module
{
[FirstClassTests]
public static IEnumerable<ITestCase> YieldFirstClassTests()
{
yield return new TestCase(() => Assert.Equal(1, 1));
yield return new TestCase(() => Assert.Equal(2, 2));
yield return new TestCase(() => Assert.Equal(3, 3));
}
}
}
}
| mit |
ddsc/webclient | app/scripts/lizard/collections/Annotation.js | 98 | Lizard.Collections.Annotation = Backbone.Collection.extend({
model: Lizard.Models.Annotation
});
| mit |
henzk/schnipp.js | src/schnipp/dynforms/fields/hiddeninput.js | 847 | /**
* hiddeninput field
*
* @param {Object} field_descriptor field specific part of the form schema
* @param {Object} field_data initial value for the field
* @constructor
* @class schnipp.dynforms.fields.hiddeninput
* @extends schnipp.dynforms.primitive_field
**/
schnipp.dynforms.fields.hiddeninput = function(field_descriptor, field_data) {
var self = schnipp.dynforms.primitive_field(field_descriptor, field_data)
self.dom.input = $(
'<input type="hidden" name="' +
self.field_descriptor.name +
'" class="fieldtype_' + self.field_descriptor.type +
'"/>'
).val(self.get_initial_data())
self.super_init = self.initialize
self.initialize = function() {
self.super_init()
self.dom.main.css('display', 'none')
return self.dom.input
}
return self
}
| mit |
suzdalnitski/Zenject | UnityProject/Assets/Plugins/Zenject/OptionalExtras/UnitTests/Editor/Injection/TestStructInjection.cs | 749 | using System;
using System.Collections.Generic;
using Zenject;
using NUnit.Framework;
using ModestTree;
using Assert=ModestTree.Assert;
namespace Zenject.Tests.Injection
{
[TestFixture]
public class TestStructInjection : ZenjectUnitTestFixture
{
struct Test1
{
}
class Test2
{
public Test2(Test1 t1)
{
}
}
[Test]
public void TestCase1()
{
Container.Bind<Test1>().FromInstance(new Test1()).NonLazy();
Container.Bind<Test2>().AsSingle().NonLazy();
Container.ResolveDependencyRoots();
var t2 = Container.Resolve<Test2>();
Assert.That(t2 != null);
}
}
}
| mit |
markovandooren/rejuse | src/main/java/org/aikodi/rejuse/association/Association.java | 11238 | package org.aikodi.rejuse.association;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* <p>A class of objects that can be used to set up bi-directional association between objects.</p>
*
* <center><img src="doc-files/Relation.png"/></center>
*
* <p>This class provides the general interface that is needed in order to create different types
* of bindings that can be created by taking two arbitrary multiplicities.</p>
*
* <p>Note: The collection of event listeners is initialized lazily, are removed when no event listeners
* are registered anymore.</p>
*
* @author Marko van Dooren
*/
public abstract class Association<FROM,TO> implements IAssociation<FROM, TO> {
/**
* Initialize a new association for the given object.
* The new association will be unconnected.
*
* @param object
* The object at this side of the binding.
*/
/*@
@ public behavior
@
@ pre object != null;
@
@ post getObject() == object;
@*/
public Association(FROM object) {
if(object == null) {
throw new IllegalArgumentException("The parent of an association end cannot be null.");
}
_object = object;
}
/**
* Check whether or not the given association is connected
* to this one.
*
* @param association
* The association which is possibly on the other end
* of the binding.
*/
/*@
@ public behavior
@
@ post \result == getOtherAssociations().contains(association);
@*/
// @Override
public /*@ pure @*/ boolean contains(Association<? extends TO,? super FROM> association) {
Collection<Association<? extends TO, ? super FROM>> internalAssociations = internalAssociations();
return internalAssociations == null ? false : internalAssociations.contains(association);
}
/*@
@ also public behavior
@
@ post \result == (other == this);
@*/
@Override
public /*@ pure @*/ boolean equals(Object other) {
return other == this;
}
/**
* Add the given association as a participant in this
* binding.
*
* If the new object is not null and replaces another one, {@link #fireElementReplaced(Object, Object)}
* is called. If the new object is null and replaces another one, {@link #fireElementRemoved(Object)}
* is called. If the new object is not null and does not replace another one, {@link #fireElementAdded(Object)}
* is called.
*/
/*@
@ protected behavior
@
@ pre isValidElement(other);
@
@ post registered(\old(getOtherAssociations()), other);
@*/
protected abstract boolean register(Association<? extends TO,? super FROM> other);
protected void checkLock() {
checkLock(this);
}
/**
* Throw an exception if this association end is locked.
*/
protected void checkLock(Association<?,?> association) {
if(association != null && association.isLocked()) {
throw new LockException("Trying to modify locked reference. Locked object: "+association.getObject().getClass().getName());
}
}
/**
* Remove the given association end as a participant in this
* association.
*/
/*@
@ protected behavior
@
@ pre contains(other);
@
@ post unregistered(\old(getOtherAssociations()), other);
@*/
protected abstract void unregister(Association<? extends TO,? super FROM> other);
/**
* Check whether or not the given association may be connected to
* this association.
*/
/*@
@ protected behavior
@
@ post \result == true | \result == false;
@*/
protected /*@ pure @*/ abstract boolean isValidElement(Association<? extends TO,? super FROM> association);
/**
* Check whether or not the current state corresponds to connecting
* to the given association when being connected to the associations
* in the given list.
*
* @param oldConnections
* The List of associations this association was connected to before.
* @param registered
* The association to which this association has been connected.
*/
/*@
@ public behavior
@
@ pre oldConnections != null;
@ pre ! oldConnections.contains(null);
@
@ post ! contains(registered) ==> \result == false;
@ post ! (\forall Association r; r != registered;
@ oldConnections.contains(r) == contains(r)) ==> \result == false;
@*/
// @Override
public /*@ pure @*/ abstract boolean registered(List<Association<? extends TO,? super FROM>> oldConnections, Association<? extends TO,? super FROM> registered);
/**
* Check whether or not the current state corresponds to disconnecting
* from the given association when being connected to the assocations
* in the given list.
*
* @param oldConnections
* The List of associations this association was connected to before.
* @param registered
* The association to which this association has been connected.
*/
/*@
@ public behavior
@
@ pre oldConnections != null;
@ pre ! oldConnections.contains(null);
@
@ post contains(unregistered) ==> \result == false;
@ post ! oldConnections.contains(unregistered) ==> \result == false;
@ post ! (\forall Association r; r != unregistered;
@ oldConnections.contains(r) == contains(r)) ==> \result == false;
@*/
// @Override
public /*@ pure @*/ abstract boolean unregistered(List<Association<? extends TO,? super FROM>> oldConnections, Association<? extends TO,? super FROM> unregistered);
// @Override
public abstract void addOtherEndsTo(Collection<? super TO> collection);
// public abstract List<TO> view();
/**
* Return the association on the other side of the binding.
*/
/*@
@ public behavior
@
@ post \result != null;
@ post ! \result.contains(null);
@*/
// @Override
public /*@ pure @*/ abstract List<Association<? extends TO,? super FROM>> getOtherAssociations();
protected /*@ pure @*/ abstract Collection<Association<? extends TO,? super FROM>> internalAssociations();
/**
* Return the object on represented by this association end.
*/
/*@
@ public behavior
@
@ post \result != null;
@*/
// @Override
public /*@ pure @*/ FROM getObject() {
return _object;
}
/**
* The object on this side of the binding.
*/
private FROM _object;
/**
* Replace the connection with the first association by a connection with the second association.
*/
/*@
@ public behavior
@
@ pre element != null;
@ pre newElement != null;
@
@ post replaced(\old(getOtherRelations()), oldAssociation, newAssociation);
@ post oldAssociation.unregistered(\old(other.getOtherAssociations()), this);
@ post newAssociation.registered(\old(oldAssociation.getOtherAssociations()),this);
@*/
// @Override
public abstract void replace(Association<? extends TO,? super FROM> element, Association<? extends TO,? super FROM> newElement);
/*
* True if this association end is locked.
* False if this association end is not locked.
*/
private boolean _locked = false;
/**
* Lock this end of the association.
*/
/*@
@ public behavior
@
@ post isLocked();
@*/
// @Override
public void lock() {
_locked=true;
}
// @Override
public void unlock() {
_locked=false;
}
/**
* Check if this association end is locked.
*/
// @Override
public boolean isLocked() {
return _locked;
}
// @Override
public abstract int size();
/**
* Register the given association listener as an event listener to
* this association end.
* @param listener
* The listener to be registered.
*/
/*@
@ public behavior
@
@ pre listener != null;
@
@ post listeners().contains(listener);
@*/
// @Override
public void addListener(AssociationListener<? super TO> listener) {
if(listener == null) {
throw new IllegalArgumentException("An association listener cannot be null.");
}
if(_listeners == null) {
_listeners = new HashSet<AssociationListener<? super TO>>();
}
_listeners.add(listener);
}
/**
* Remove the given association listener as an event listener from
* this association end.
*
* @param listener
* The listener to be removed.
*/
/*@
@ public behavior
@
@ pre listener != null;
@
@ post ! listeners().contains(listener);
@*/
// @Override
public void removeListener(AssociationListener<? super TO> listener) {
if(_listeners != null) {
_listeners.remove(listener);
// clean up if there are no listeners anymore.
if(_listeners.isEmpty()) {
_listeners = null;
}
}
}
// @Override
public Set<AssociationListener<? super TO>> listeners() {
return new HashSet<AssociationListener<? super TO>>(_listeners);
}
private Set<AssociationListener<? super TO>> _listeners;
public abstract void flushCache();
/**
* If events are enabled, send "element added" events to all listeners.
*/
protected void fireElementAdded(TO addedElement) {
flushCache();
if(! _eventsBlocked && _listeners != null) {
for(AssociationListener<? super TO> listener: _listeners) {
listener.notifyElementAdded(addedElement);
}
}
}
/**
* If events are enabled, send "element removed" events to all listeners.
*/
protected void fireElementRemoved(TO removedElement) {
flushCache();
if(! _eventsBlocked && _listeners != null) {
for(AssociationListener<? super TO> listener: _listeners) {
listener.notifyElementRemoved(removedElement);
}
}
}
/**
* If events are enabled, send "element replaced" events to all listeners.
*/
protected void fireElementReplaced(TO oldElement, TO newElement) {
flushCache();
if(! _eventsBlocked && _listeners != null) {
for(AssociationListener<? super TO> listener: _listeners) {
listener.notifyElementReplaced(oldElement, newElement);
}
}
}
private boolean _eventsBlocked;
/**
* Disable sending of events. This can be used to prevent register and unregister methods
* from sending events when a replace is done.
* @return
*/
/*@
@ behavior
@
@ post eventsBlocked() == true;
@*/
protected void disableEvents() {
_eventsBlocked = true;
}
/**
* Enable sending of events.
*/
/*@
@ behavior
@
@ post eventsBlocked() == false;
@*/
protected void enableEvents() {
_eventsBlocked = false;
}
/**
* Check whether or not events are blocked.
* @return
*/
protected boolean eventsBlocked() {
return _eventsBlocked;
}
/**
* Remove all connections. An exception is thrown if either this association, or an association to which it is connected, is locked.
*/
/*@
@ post size() == 0;
@*/
// @Override
public abstract void clear();
public void enableCache() {
_isCaching = true;
}
public void disableCache() {
_isCaching = false;
}
public boolean isCaching() {
return _isCaching;
}
private boolean _isCaching;
public boolean containsObject(TO to) {
if(to != null) {
for(TO connected: getOtherEnds()) {
if(connected.equals(to)) {
return true;
}
}
}
return false;
}
}
| mit |
ajatdarojat45/sppi | application/views/pr/list.php | 17597 | <!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<small></small>
</h1>
<ol class="breadcrumb">
<li><a href="<?php echo base_url();?>auth/dashboard"><i class="fa fa-dashboard"></i> Dashboard</a></li>
<li class="active">PR</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="box box-primary collapsed-box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Panduan</h3>
<div class="box-tools pull-right">
<button type="button" data-toggle="tooltip" title="Lihat Panduan" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-plus"></i>
</button>
<button type="button" data-toggle="tooltip" title="Hapus Panduan" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body" style="overflow-y: scroll; height: 200px;">
<pre class="prettyprint">
<code class="javascript">
Halaman ini berisi data Purchase Order (PR) dan ada beberapa tombol pada halaman ini. Tombol <button type="button" class="btn btn-primary btn-xs" data-toggle="tooltip" title="Tambah PR"> <i class="fa fa-plus"></i> Tambah</button> digunakan untuk menambah data Purchase Order (PR), tombol <a data-toggle="tooltip" title="Detail PR"><i class="fa fa-file-pdf-o"></i></a> digunakan untuk melihat data detail Purchase Order (PR), tombol <a data-toggle="tooltip" title="Edit PR"><i class="fa fa-edit"></i></a> digunakan untuk merubah data Purchase Order (PR) dan tombol <a data-toggle="tooltip" title="Hapus PR"><i class="fa fa-trash"></i></a> digunakan untuk menghapus Purchase Order (PR).
</code>
</pre>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="nav-tabs-custom">
<!-- <ul class="nav nav-tabs">
<li class="active"><a href="#list" data-toggle="tab">LIST</a></li>
<li><a href="#form" data-toggle="tab">FORM</a></li>
<br>
</ul> -->
<div class="tab-content">
<!-- Font Awesome Icons -->
<div class="tab-pane active" id="list">
<section id="new">
<h4 class="page-header">PURCHASE REQUEST (PR)</h4>
<div class="row fontawesome-icon-list">
</div>
<div class="box-header">
<h3 class="box-title">
<span data-toggle="tooltip" title="Tambah PR">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> <i class="fa fa-plus-circle"></i> Tambah</button>
</span>
</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="table-responsive">
<table id="example1" class="table table-hover table-striped">
<thead>
<tr>
<th style="text-align:center">No</th>
<th style="text-align:center">Nomor PR</th>
<th style="text-align:center">Dibuat</th>
<th style="text-align:center">Disetujui</th>
<th style="text-align:center">Notes</th>
<!-- <th style="text-align:center">Dibuat Oleh</th> -->
<!-- <th style="text-align:center">Keterangan</th> -->
<th style="text-align:center">Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($pr as $a): ?>
<tr>
<td style="text-align:center"><?php echo ++$start ?></td>
<td ><?php echo $a->nomor_pr?></td>
<td style="text-align:center">
<?php
$aa = $a->created_pr;
echo date('d M. Y', strtotime($aa));
?>
</td>
<td style="text-align:center">
<?php
$aa = $a->approved_pr;
if ($a->approved_pr != '0000-00-00') {
echo date('d M. Y', strtotime($aa));
}
?>
</td>
<td>
<!-- <?php echo $a->notes_pr?> -->
<?php
$num_char = 50;
$text = $a->notes_pr;
if (strlen($text) >= $num_char) {
$char = $text{$num_char - 1};
while($char != ' ') {
$char = $text{--$num_char}; // Cari spasi pada posisi 49, 48, 47, dst...
}
echo substr($text, 0, $num_char) . '...';
}
else {
echo $text;
}
?>
</td>
<!-- <td><?php echo $a->nama_karyawan?></td> -->
<!-- <td><?php echo $a->ket_pr?></td> -->
<td style="text-align:center">
<a href="<?php echo base_url()?>pr/report_pr/<?php echo $a->id_pr?>" data-toggle="tooltip" title="Detail Purchase Request (PR)" target="_blank">
<i class="fa fa-file-pdf-o"></i>
</a>
<span data-toggle="tooltip" title="Edit Detail Purchase Request (PR)">
<a data-toggle="modal" data-target="#editpr" id-pr="<?php echo $a->id_pr;?>" class="btneditpr">
<i class="fa fa-edit"></i>
</a>
</span>
<span data-toggle="tooltip" title="Hapus PR">
<a class="delete-link" href="<?php echo base_url();?>pr/delete2/<?php echo $a->id_pr;?>/<?php echo $a->hapus;?>">
<i class="fa fa-trash"></i>
</a>
</span>
</td>
</tr>
<?php endforeach ?>
</tbody>
<tfoot>
<tr>
<th style="text-align:center">No</th>
<th style="text-align:center">Nomor PR</th>
<th style="text-align:center">Dibuat</th>
<th style="text-align:center">Disetujui</th>
<th style="text-align:center">Notes</th>
<!-- <th style="text-align:center">Dibuat Oleh</th> -->
<!-- <th style="text-align:center">Keterangan</th> -->
<th style="text-align:center">Action</th>
</tr>
</tfoot>
</table>
</div>
</div>
<!-- /.box-body -->
</section>
</div>
<!-- /#fa-icons -->
<!-- /.tab-content -->
</div>
<!-- /.nav-tabs-custom -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><center>Form PR</center></h4>
</div>
<div class="modal-body">
<form action="<?php echo base_url(); ?>pr/create_action" id="" method="post" name="login">
<!-- <img id="close" src="<?php echo base_url()?>assets/popup/close.png" onclick ="div_hide()"><br><br> -->
<div class="form-group has-feedback">
<div class="row">
<div class="col-md-4 col-lg-4">
<label for="int">Nomor PR</label>
<input type="text" class="form-control" placeholder="Nomor PR" name="nomor_pr" id="nama_pegawai" value="" required/>
<!-- <span class="glyphicon glyphicon-user form-control-feedback"></span> -->
</div>
<div class="col-md-4 col-lg-4">
<label for="int">Tanggal Buat</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control" placeholder="" name="created_pr" id="created_pr" value="" required/>
</div>
<!-- <span class="glyphicon glyphicon-user form-control-feedback"></span> -->
</div>
<div class="col-md-4 col-lg-4">
<label for="int">Tanggal Disetujui</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control" placeholder="" name="approved_pr" id="approved_pr" value=""/>
</div>
<!-- <span class="glyphicon glyphicon-user form-control-feedback"></span> -->
</div>
</div>
</div>
<div class="form-group">
<label for="int">Notes PR</label>
<textarea class="form-control" rows="2" name="notes_pr" placeholder="Notes" value="" required></textarea>
</div>
<div class="form-group">
<label for="int">Keterangan</label>
<textarea class="form-control" rows="3" name="ket_pr" placeholder="Keterangan" value=""></textarea>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<input type="hidden" name="id_pr" value="" />
</div>
</div>
</div>
<div class="modal-footer">
<!-- <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> -->
<span data-toggle="tooltip" title="Tutup Modal">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Tutup</button>
</span>
<span data-toggle="tooltip" title="Simpan Data">
<button type="submit" class="btn btn-primary " href="">Simpan</button>
</span>
</div>
</form>
</div>
</div>
</div>
<!-- modal ediit -->
<div class="modal fade" id="editpr" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><center>Form Edit PR</center></h4>
</div>
<div class="modal-body">
<form action="<?php echo base_url(); ?>pr/update_action" id="" method="post" name="login">
<!-- <img id="close" src="<?php echo base_url()?>assets/popup/close.png" onclick ="div_hide()"><br><br> -->
<div class="form-group has-feedback">
<div class="row">
<div class="col-md-4 col-lg-4">
<label for="int">Nomor PR</label>
<input type="text" class="form-control" placeholder="Nomor PR" name="nomor_pr2" id="nomor_pr2" value="" required/>
<!-- <span class="glyphicon glyphicon-user form-control-feedback"></span> -->
</div>
<div class="col-md-4 col-lg-4">
<label for="int">Tanggal Buat</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control" placeholder="" name="created_pr2" id="created_pr2" value="" required/>
</div>
<!-- <span class="glyphicon glyphicon-user form-control-feedback"></span> -->
</div>
<div class="col-md-4 col-lg-4">
<label for="int">Tanggal Disetujui</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control" placeholder="" name="approved_pr2" id="approved_pr2" value=""/>
</div>
<!-- <span class="glyphicon glyphicon-user form-control-feedback"></span> -->
</div>
</div>
</div>
<div class="form-group">
<label for="int">Notes PR</label>
<textarea class="form-control" rows="2" name="notes_pr2" id="notes_pr2" placeholder="Notes" value="" required></textarea>
</div>
<div class="form-group">
<label for="int">Keterangan</label>
<textarea class="form-control" rows="3" name="ket_pr2" id="ket_pr2" placeholder="Keterangan" value=""></textarea>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<input type="hidden" name="id_pr2" id="id_pr2" value="" />
</div>
</div>
</div>
<div class="modal-footer">
<!-- <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> -->
<span data-toggle="tooltip" title="Tutup Modal">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Tutup</button>
</span>
<span data-toggle="tooltip" title="Simpan Perubahan">
<button type="submit" class="btn btn-primary" href="">Simpan</button>
</span>
</div>
</form>
</div>
</div>
</div> | mit |
jibanez74/BusinessPanel | src/app/guards/settings.guard.ts | 559 | import { Injectable } from '@angular/core';
import { SettingsService } from '../services/settings.service';
import { Router, CanActivate } from '@angular/router';
@Injectable ()
export class SettingsGuard implements CanActivate {
constructor (
private _router: Router,
public _settings: SettingsService
) {}
canActivate (): boolean {
if (this._settings.setSettings().allowRegistration) {
return true;
} else {
this._router.navigate(['/login']);
return false;
}
}
} | mit |
chribi/predictable | app/src/main/java/de/chribi/predictable/startscreen/StartScreenView.java | 213 | package de.chribi.predictable.startscreen;
import de.chribi.predictable.PredictionItemView;
public interface StartScreenView extends PredictionItemView, ShowMoreFooterView {
void showAddPredictionView();
}
| mit |
olamedia/yuki | experiments/model/document/yDocumentModel.php | 1415 | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* yDocumentModel
*
* @package yuki
* @subpackage model
* @author olamedia
* @license http://www.opensource.org/licenses/mit-license.php MIT
*/
class yDocumentModel{
const
primaryKey = 'primaryKey',
documentId = 'documentId'
;
protected $_properties = array(
'id'=>array(
'class'=>'stringProperty',
'primaryKey'=>true, // CouchDB will force '_id' as field name
'autoIncrement'=>false,
'documentId'=>true,
'field'=>'id'
),
'title'=>array(
'class'=>'stringProperty',
'field'=>'title'
),
'data'=>array(
'class'=>'jsonProperty',
'field'=>'data'
)
);
public function getId(){
}
public static function get($id){
}
public function save(){
if (!$this->isDraft()){
return;
}
if ($this->isSaved()){
$this->update();
}else{
$this->insert();
}
}
public function insert(){
$query = new yModelQuery();
$query->setType('INSERT');
$query->setDocumentId($this->getDocumentId());
$query->setDataObject($this->getDataObject());
}
public function update(){
}
}
| mit |
nnaabbcc/exercise | python/plot/exercise_subplot_1.py | 488 | #!/usr/bin/env python
#!encoding=utf-8
import matplotlib.pyplot as plt
import numpy as np
def f(t):
return np.exp(-t) * np.cos(2 * np.pi * t)
if __name__ == '__main__' :
t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)
plt.figure(1)
plt.subplot(2, 2, 1)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')
plt.subplot(2, 2, 2)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')
plt.subplot(2, 1, 2)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()
| mit |
earwig/earwigbot | earwigbot/wiki/copyvios/parsers.py | 14045 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import json
from os import path
import re
from io import StringIO
import urllib.parse
import urllib.request
import mwparserfromhell
from earwigbot import importer
from earwigbot.exceptions import ParserExclusionError, ParserRedirectError
bs4 = importer.new("bs4")
nltk = importer.new("nltk")
converter = importer.new("pdfminer.converter")
pdfinterp = importer.new("pdfminer.pdfinterp")
pdfpage = importer.new("pdfminer.pdfpage")
__all__ = ["ArticleTextParser", "get_parser"]
class _BaseTextParser:
"""Base class for a parser that handles text."""
TYPE = None
def __init__(self, text, url=None, args=None):
self.text = text
self.url = url
self._args = args or {}
def __repr__(self):
"""Return the canonical string representation of the text parser."""
return "{0}(text={1!r})".format(self.__class__.__name__, self.text)
def __str__(self):
"""Return a nice string representation of the text parser."""
name = self.__class__.__name__
return "<{0} of text with size {1}>".format(name, len(self.text))
class ArticleTextParser(_BaseTextParser):
"""A parser that can strip and chunk wikicode article text."""
TYPE = "Article"
TEMPLATE_MERGE_THRESHOLD = 35
NLTK_DEFAULT = "english"
NLTK_LANGS = {
"cs": "czech",
"da": "danish",
"de": "german",
"el": "greek",
"en": "english",
"es": "spanish",
"et": "estonian",
"fi": "finnish",
"fr": "french",
"it": "italian",
"nl": "dutch",
"no": "norwegian",
"pl": "polish",
"pt": "portuguese",
"sl": "slovene",
"sv": "swedish",
"tr": "turkish"
}
def _merge_templates(self, code):
"""Merge template contents in to wikicode when the values are long."""
for template in code.filter_templates(recursive=code.RECURSE_OTHERS):
chunks = []
for param in template.params:
if len(param.value) >= self.TEMPLATE_MERGE_THRESHOLD:
self._merge_templates(param.value)
chunks.append(param.value)
if chunks:
subst = " ".join(map(str, chunks))
code.replace(template, " " + subst + " ")
else:
code.remove(template)
def _get_tokenizer(self):
"""Return a NLTK punctuation tokenizer for the article's language."""
datafile = lambda lang: "file:" + path.join(
self._args["nltk_dir"], "tokenizers", "punkt", lang + ".pickle")
lang = self.NLTK_LANGS.get(self._args.get("lang"), self.NLTK_DEFAULT)
try:
nltk.data.load(datafile(self.NLTK_DEFAULT))
except LookupError:
nltk.download("punkt", self._args["nltk_dir"])
return nltk.data.load(datafile(lang))
def _get_sentences(self, min_query, max_query, split_thresh):
"""Split the article text into sentences of a certain length."""
def cut_sentence(words):
div = len(words)
if div == 0:
return []
length = len(" ".join(words))
while length > max_query:
div -= 1
length -= len(words[div]) + 1
result = []
if length >= split_thresh:
result.append(" ".join(words[:div]))
return result + cut_sentence(words[div + 1:])
tokenizer = self._get_tokenizer()
sentences = []
if not hasattr(self, "clean"):
self.strip()
for sentence in tokenizer.tokenize(self.clean):
if len(sentence) <= max_query:
sentences.append(sentence)
else:
sentences.extend(cut_sentence(sentence.split()))
return [sen for sen in sentences if len(sen) >= min_query]
def strip(self):
"""Clean the page's raw text by removing templates and formatting.
Return the page's text with all HTML and wikicode formatting removed,
including templates, tables, and references. It retains punctuation
(spacing, paragraphs, periods, commas, (semi)-colons, parentheses,
quotes), original capitalization, and so forth. HTML entities are
replaced by their unicode equivalents.
The actual stripping is handled by :py:mod:`mwparserfromhell`.
"""
def remove(code, node):
"""Remove a node from a code object, ignoring ValueError.
Sometimes we will remove a node that contains another node we wish
to remove, and we fail when we try to remove the inner one. Easiest
solution is to just ignore the exception.
"""
try:
code.remove(node)
except ValueError:
pass
wikicode = mwparserfromhell.parse(self.text)
# Preemtively strip some links mwparser doesn't know about:
bad_prefixes = ("file:", "image:", "category:")
for link in wikicode.filter_wikilinks():
if link.title.strip().lower().startswith(bad_prefixes):
remove(wikicode, link)
# Also strip references:
for tag in wikicode.filter_tags(matches=lambda tag: tag.tag == "ref"):
remove(wikicode, tag)
# Merge in template contents when the values are long:
self._merge_templates(wikicode)
clean = wikicode.strip_code(normalize=True, collapse=True)
self.clean = re.sub(r"\n\n+", "\n", clean).strip()
return self.clean
def chunk(self, max_chunks, min_query=8, max_query=128, split_thresh=32):
"""Convert the clean article text into a list of web-searchable chunks.
No greater than *max_chunks* will be returned. Each chunk will only be
a sentence or two long at most (no more than *max_query*). The idea is
to return a sample of the article text rather than the whole, so we'll
pick and choose from parts of it, especially if the article is large
and *max_chunks* is low, so we don't end up just searching for just the
first paragraph.
This is implemented using :py:mod:`nltk` (https://nltk.org/). A base
directory (*nltk_dir*) is required to store nltk's punctuation
database, and should be passed as an argument to the constructor. It is
typically located in the bot's working directory.
"""
sentences = self._get_sentences(min_query, max_query, split_thresh)
if len(sentences) <= max_chunks:
return sentences
chunks = []
while len(chunks) < max_chunks:
if len(chunks) % 5 == 0:
chunk = sentences.pop(0) # Pop from beginning
elif len(chunks) % 5 == 1:
chunk = sentences.pop() # Pop from end
elif len(chunks) % 5 == 2:
chunk = sentences.pop(len(sentences) / 2) # Pop from Q2
elif len(chunks) % 5 == 3:
chunk = sentences.pop(len(sentences) / 4) # Pop from Q1
else:
chunk = sentences.pop(3 * len(sentences) / 4) # Pop from Q3
chunks.append(chunk)
return chunks
def get_links(self):
"""Return a list of all external links in the article.
The list is restricted to things that we suspect we can parse: i.e.,
those with schemes of ``http`` and ``https``.
"""
schemes = ("http://", "https://")
links = mwparserfromhell.parse(self.text).ifilter_external_links()
return [str(link.url) for link in links
if link.url.startswith(schemes)]
class _HTMLParser(_BaseTextParser):
"""A parser that can extract the text from an HTML document."""
TYPE = "HTML"
hidden_tags = [
"script", "style"
]
def _fail_if_mirror(self, soup):
"""Look for obvious signs that the given soup is a wiki mirror.
If so, raise ParserExclusionError, which is caught in the workers and
causes this source to excluded.
"""
if "mirror_hints" not in self._args:
return
func = lambda attr: attr and any(
hint in attr for hint in self._args["mirror_hints"])
if soup.find_all(href=func) or soup.find_all(src=func):
raise ParserExclusionError()
@staticmethod
def _get_soup(text):
"""Parse some text using BeautifulSoup."""
try:
return bs4.BeautifulSoup(text, "lxml")
except ValueError:
return bs4.BeautifulSoup(text)
def _clean_soup(self, soup):
"""Clean a BeautifulSoup tree of invisible tags."""
is_comment = lambda text: isinstance(text, bs4.element.Comment)
for comment in soup.find_all(text=is_comment):
comment.extract()
for tag in self.hidden_tags:
for element in soup.find_all(tag):
element.extract()
return "\n".join(soup.stripped_strings)
def _open(self, url, **kwargs):
"""Try to read a URL. Return None if it couldn't be read."""
opener = self._args.get("open_url")
if not opener:
return None
result = opener(url, **kwargs)
return result.content if result else None
def _load_from_blogspot(self, url):
"""Load dynamic content from Blogger Dynamic Views."""
match = re.search(r"'postId': '(\d+)'", self.text)
if not match:
return ""
post_id = match.group(1)
url = "https://%s/feeds/posts/default/%s?" % (url.netloc, post_id)
params = {
"alt": "json",
"v": "2",
"dynamicviews": "1",
"rewriteforssl": "true",
}
raw = self._open(url + urllib.parse.urlencode(params),
allow_content_types=["application/json"])
if raw is None:
return ""
try:
parsed = json.loads(raw)
except ValueError:
return ""
try:
text = parsed["entry"]["content"]["$t"]
except KeyError:
return ""
soup = self._get_soup(text)
return self._clean_soup(soup.body)
def parse(self):
"""Return the actual text contained within an HTML document.
Implemented using :py:mod:`BeautifulSoup <bs4>`
(https://www.crummy.com/software/BeautifulSoup/).
"""
url = urllib.parse.urlparse(self.url) if self.url else None
soup = self._get_soup(self.text)
if not soup.body:
# No <body> tag present in HTML ->
# no scrapable content (possibly JS or <iframe> magic):
return ""
self._fail_if_mirror(soup)
body = soup.body
if url and url.netloc == "web.archive.org" and url.path.endswith(".pdf"):
playback = body.find(id="playback")
if playback and "src" in playback.attrs:
raise ParserRedirectError(playback.attrs["src"])
content = self._clean_soup(body)
if url and url.netloc.endswith(".blogspot.com") and not content:
content = self._load_from_blogspot(url)
return content
class _PDFParser(_BaseTextParser):
"""A parser that can extract text from a PDF file."""
TYPE = "PDF"
substitutions = [
("\x0c", "\n"),
("\u2022", " "),
]
def parse(self):
"""Return extracted text from the PDF."""
output = StringIO()
manager = pdfinterp.PDFResourceManager()
conv = converter.TextConverter(manager, output)
interp = pdfinterp.PDFPageInterpreter(manager, conv)
try:
pages = pdfpage.PDFPage.get_pages(StringIO(self.text))
for page in pages:
interp.process_page(page)
except Exception: # pylint: disable=broad-except
return output.getvalue().decode("utf8")
finally:
conv.close()
value = output.getvalue().decode("utf8")
for orig, new in self.substitutions:
value = value.replace(orig, new)
return re.sub(r"\n\n+", "\n", value).strip()
class _PlainTextParser(_BaseTextParser):
"""A parser that can unicode-ify and strip text from a plain text page."""
TYPE = "Text"
def parse(self):
"""Unicode-ify and strip whitespace from the plain text document."""
converted = bs4.UnicodeDammit(self.text).unicode_markup
return converted.strip() if converted else ""
_CONTENT_TYPES = {
"text/html": _HTMLParser,
"application/xhtml+xml": _HTMLParser,
"application/pdf": _PDFParser,
"application/x-pdf": _PDFParser,
"text/plain": _PlainTextParser
}
def get_parser(content_type):
"""Return the parser most able to handle a given content type, or None."""
return _CONTENT_TYPES.get(content_type)
| mit |
logankoester/tweetshrink | spec/spec_helper.rb | 129 | require 'spec'
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'lib/tweetshrink'
Spec::Runner.configure do |config|
end
| mit |
Azure/azure-sdk-for-go | services/compute/mgmt/2021-04-01/compute/virtualmachineruncommands.go | 29124 | package compute
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// VirtualMachineRunCommandsClient is the compute Client
type VirtualMachineRunCommandsClient struct {
BaseClient
}
// NewVirtualMachineRunCommandsClient creates an instance of the VirtualMachineRunCommandsClient client.
func NewVirtualMachineRunCommandsClient(subscriptionID string) VirtualMachineRunCommandsClient {
return NewVirtualMachineRunCommandsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewVirtualMachineRunCommandsClientWithBaseURI creates an instance of the VirtualMachineRunCommandsClient client
// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign
// clouds, Azure stack).
func NewVirtualMachineRunCommandsClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineRunCommandsClient {
return VirtualMachineRunCommandsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate the operation to create or update the run command.
// Parameters:
// resourceGroupName - the name of the resource group.
// VMName - the name of the virtual machine where the run command should be created or updated.
// runCommandName - the name of the virtual machine run command.
// runCommand - parameters supplied to the Create Virtual Machine RunCommand operation.
func (client VirtualMachineRunCommandsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMName string, runCommandName string, runCommand VirtualMachineRunCommand) (result VirtualMachineRunCommandsCreateOrUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.CreateOrUpdate")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, VMName, runCommandName, runCommand)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client VirtualMachineRunCommandsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, VMName string, runCommandName string, runCommand VirtualMachineRunCommand) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"runCommandName": autorest.Encode("path", runCommandName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"vmName": autorest.Encode("path", VMName),
}
const APIVersion = "2021-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", pathParameters),
autorest.WithJSON(runCommand),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) CreateOrUpdateSender(req *http.Request) (future VirtualMachineRunCommandsCreateOrUpdateFuture, err error) {
var resp *http.Response
future.FutureAPI = &azure.Future{}
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = future.result
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineRunCommand, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete the operation to delete the run command.
// Parameters:
// resourceGroupName - the name of the resource group.
// VMName - the name of the virtual machine where the run command should be deleted.
// runCommandName - the name of the virtual machine run command.
func (client VirtualMachineRunCommandsClient) Delete(ctx context.Context, resourceGroupName string, VMName string, runCommandName string) (result VirtualMachineRunCommandsDeleteFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.Delete")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.DeletePreparer(ctx, resourceGroupName, VMName, runCommandName)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client VirtualMachineRunCommandsClient) DeletePreparer(ctx context.Context, resourceGroupName string, VMName string, runCommandName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"runCommandName": autorest.Encode("path", runCommandName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"vmName": autorest.Encode("path", VMName),
}
const APIVersion = "2021-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) DeleteSender(req *http.Request) (future VirtualMachineRunCommandsDeleteFuture, err error) {
var resp *http.Response
future.FutureAPI = &azure.Future{}
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = future.result
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets specific run command for a subscription in a location.
// Parameters:
// location - the location upon which run commands is queried.
// commandID - the command id.
func (client VirtualMachineRunCommandsClient) Get(ctx context.Context, location string, commandID string) (result RunCommandDocument, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: location,
Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, location, commandID)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client VirtualMachineRunCommandsClient) GetPreparer(ctx context.Context, location string, commandID string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"commandId": autorest.Encode("path", commandID),
"location": autorest.Encode("path", location),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands/{commandId}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) GetResponder(resp *http.Response) (result RunCommandDocument, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetByVirtualMachine the operation to get the run command.
// Parameters:
// resourceGroupName - the name of the resource group.
// VMName - the name of the virtual machine containing the run command.
// runCommandName - the name of the virtual machine run command.
// expand - the expand expression to apply on the operation.
func (client VirtualMachineRunCommandsClient) GetByVirtualMachine(ctx context.Context, resourceGroupName string, VMName string, runCommandName string, expand string) (result VirtualMachineRunCommand, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.GetByVirtualMachine")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetByVirtualMachinePreparer(ctx, resourceGroupName, VMName, runCommandName, expand)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "GetByVirtualMachine", nil, "Failure preparing request")
return
}
resp, err := client.GetByVirtualMachineSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "GetByVirtualMachine", resp, "Failure sending request")
return
}
result, err = client.GetByVirtualMachineResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "GetByVirtualMachine", resp, "Failure responding to request")
return
}
return
}
// GetByVirtualMachinePreparer prepares the GetByVirtualMachine request.
func (client VirtualMachineRunCommandsClient) GetByVirtualMachinePreparer(ctx context.Context, resourceGroupName string, VMName string, runCommandName string, expand string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"runCommandName": autorest.Encode("path", runCommandName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"vmName": autorest.Encode("path", VMName),
}
const APIVersion = "2021-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(expand) > 0 {
queryParameters["$expand"] = autorest.Encode("query", expand)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetByVirtualMachineSender sends the GetByVirtualMachine request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) GetByVirtualMachineSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetByVirtualMachineResponder handles the response to the GetByVirtualMachine request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) GetByVirtualMachineResponder(resp *http.Response) (result VirtualMachineRunCommand, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List lists all available run commands for a subscription in a location.
// Parameters:
// location - the location upon which run commands is queried.
func (client VirtualMachineRunCommandsClient) List(ctx context.Context, location string) (result RunCommandListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List")
defer func() {
sc := -1
if result.rclr.Response.Response != nil {
sc = result.rclr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: location,
Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("compute.VirtualMachineRunCommandsClient", "List", err.Error())
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, location)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.rclr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure sending request")
return
}
result.rclr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "List", resp, "Failure responding to request")
return
}
if result.rclr.hasNextLink() && result.rclr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListPreparer prepares the List request.
func (client VirtualMachineRunCommandsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"location": autorest.Encode("path", location),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) ListResponder(resp *http.Response) (result RunCommandListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client VirtualMachineRunCommandsClient) listNextResults(ctx context.Context, lastResults RunCommandListResult) (result RunCommandListResult, err error) {
req, err := lastResults.runCommandListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client VirtualMachineRunCommandsClient) ListComplete(ctx context.Context, location string) (result RunCommandListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx, location)
return
}
// ListByVirtualMachine the operation to get all run commands of a Virtual Machine.
// Parameters:
// resourceGroupName - the name of the resource group.
// VMName - the name of the virtual machine containing the run command.
// expand - the expand expression to apply on the operation.
func (client VirtualMachineRunCommandsClient) ListByVirtualMachine(ctx context.Context, resourceGroupName string, VMName string, expand string) (result VirtualMachineRunCommandsListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.ListByVirtualMachine")
defer func() {
sc := -1
if result.vmrclr.Response.Response != nil {
sc = result.vmrclr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listByVirtualMachineNextResults
req, err := client.ListByVirtualMachinePreparer(ctx, resourceGroupName, VMName, expand)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "ListByVirtualMachine", nil, "Failure preparing request")
return
}
resp, err := client.ListByVirtualMachineSender(req)
if err != nil {
result.vmrclr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "ListByVirtualMachine", resp, "Failure sending request")
return
}
result.vmrclr, err = client.ListByVirtualMachineResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "ListByVirtualMachine", resp, "Failure responding to request")
return
}
if result.vmrclr.hasNextLink() && result.vmrclr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListByVirtualMachinePreparer prepares the ListByVirtualMachine request.
func (client VirtualMachineRunCommandsClient) ListByVirtualMachinePreparer(ctx context.Context, resourceGroupName string, VMName string, expand string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"vmName": autorest.Encode("path", VMName),
}
const APIVersion = "2021-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(expand) > 0 {
queryParameters["$expand"] = autorest.Encode("query", expand)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByVirtualMachineSender sends the ListByVirtualMachine request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) ListByVirtualMachineSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListByVirtualMachineResponder handles the response to the ListByVirtualMachine request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) ListByVirtualMachineResponder(resp *http.Response) (result VirtualMachineRunCommandsListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByVirtualMachineNextResults retrieves the next set of results, if any.
func (client VirtualMachineRunCommandsClient) listByVirtualMachineNextResults(ctx context.Context, lastResults VirtualMachineRunCommandsListResult) (result VirtualMachineRunCommandsListResult, err error) {
req, err := lastResults.virtualMachineRunCommandsListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listByVirtualMachineNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByVirtualMachineSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listByVirtualMachineNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByVirtualMachineResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "listByVirtualMachineNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByVirtualMachineComplete enumerates all values, automatically crossing page boundaries as required.
func (client VirtualMachineRunCommandsClient) ListByVirtualMachineComplete(ctx context.Context, resourceGroupName string, VMName string, expand string) (result VirtualMachineRunCommandsListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.ListByVirtualMachine")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByVirtualMachine(ctx, resourceGroupName, VMName, expand)
return
}
// Update the operation to update the run command.
// Parameters:
// resourceGroupName - the name of the resource group.
// VMName - the name of the virtual machine where the run command should be updated.
// runCommandName - the name of the virtual machine run command.
// runCommand - parameters supplied to the Update Virtual Machine RunCommand operation.
func (client VirtualMachineRunCommandsClient) Update(ctx context.Context, resourceGroupName string, VMName string, runCommandName string, runCommand VirtualMachineRunCommandUpdate) (result VirtualMachineRunCommandsUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineRunCommandsClient.Update")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, VMName, runCommandName, runCommand)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Update", nil, "Failure preparing request")
return
}
result, err = client.UpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.VirtualMachineRunCommandsClient", "Update", result.Response(), "Failure sending request")
return
}
return
}
// UpdatePreparer prepares the Update request.
func (client VirtualMachineRunCommandsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, VMName string, runCommandName string, runCommand VirtualMachineRunCommandUpdate) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"runCommandName": autorest.Encode("path", runCommandName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"vmName": autorest.Encode("path", VMName),
}
const APIVersion = "2021-04-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", pathParameters),
autorest.WithJSON(runCommand),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualMachineRunCommandsClient) UpdateSender(req *http.Request) (future VirtualMachineRunCommandsUpdateFuture, err error) {
var resp *http.Response
future.FutureAPI = &azure.Future{}
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = future.result
return
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client VirtualMachineRunCommandsClient) UpdateResponder(resp *http.Response) (result VirtualMachineRunCommand, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| mit |
spokanelibrary/spl-widgets | class/SPL_Widget_Home_Page.php | 45845 | <?php
class SPL_Widget_Home_Page extends SPL_Widget {
var $id;
var $ttl = 600; // cache ttl in seconds (0=noexpiry, so set to 1 for testing)
var $kiosk;
var $title;
var $subtitle;
var $thumb = 'large';
var $hover = 'false'; // 'false' or 'hover'
var $limit = 16;
var $params;
var $slides;
function __construct($params) {
parent::__construct();
$this->params = $params;
$this->output = $this->getHomePageSlides();
}
protected function getHomePageSlides() {
$cache = new Memcached();
$servers = $cache->getServerList();
if ( !isset($servers[1]) ) {
$cache->addServer('127.0.0.1', 11211);
}
$key = 'spl-slides-'.hash('md5',implode($this->params));
$slides = $cache->get($key);
if ( !$slides ) {
$slides = $this->buildHomePageSlides();
if ( stristr('www', $_SERVER['HTTP_HOST']) ) {
$cache->set($key, $slides, $this->ttl);
}
}
if ( in_array('refresh', $this->params) ) {
$slides = $this->buildHomePageSlides();
}
return $slides;
}
protected function buildHomePageSlides() {
$this->id = get_the_ID();
if ( isset($this->params['limit']) ) {
$this->limit = $this->params['limit'];
}
if ( isset($this->params['title']) ) {
$this->title = $this->params['title'];
}
if ( isset($this->params['subtitle']) ) {
$this->subtitle = $this->params['subtitle'];
}
$slides = array();
if ( in_array('slides', $this->params) ) {
$slides = $this->getCarouselSlides();
}
if ( in_array('facebook', $this->params) ) {
$posts = $this->getCarouselFacebook();
if ( is_array( $posts ) ) {
foreach ( $posts as $p => $post ) {
$slides[] = $post;
}
}
}
if ( in_array('fiction-queen', $this->params) ) {
$posts = $this->getCarouselFictionQueen();
if ( is_array( $posts ) ) {
foreach ( $posts as $p => $post ) {
$slides[] = $post;
}
}
}
if ( in_array('this-week', $this->params) ) {
$posts = $this->getCarouselThisWeek();
if ( is_array( $posts ) ) {
foreach ( $posts as $p => $post ) {
$slides[] = $post;
}
}
}
if ( in_array('posts', $this->params) ) {
$posts = $this->getCarouselPosts();
if ( is_array( $posts ) ) {
foreach ( $posts as $p => $post ) {
$slides[] = $post;
}
}
}
if ( in_array('calendar', $this->params) ) {
$calendar = $this->getCarouselCalendar();
if ( is_array( $calendar ) ) {
foreach ( $calendar as $c => $cal ) {
$slides[] = $cal;
}
}
}
if ( in_array('browse', $this->params) ) {
$list = $this->getCarouselBrowseList();
if ( is_array( $list ) ) {
foreach ( $list as $i => $item ) {
$slides[] = $item;
}
}
}
if ( in_array('browse-group', $this->params) ) {
$count = 5;
$apis = array(
'star-fiction'=>array('label'=>'Fiction', 'icon'=>'book', 'link'=>'/browse/star-fiction/')
, 'star-non-fiction'=>array('label'=>'Non-Fiction', 'icon'=>'book', 'link'=>'/browse/star-non-fiction/')
, 'dvd'=> array('label'=>'DVDs', 'icon'=>'play-circle', 'link'=>'/browse/dvd/')
, 'music'=>array('label'=>'Music', 'icon'=>'music', 'link'=>'/browse/music/')
);
$lists = array();
foreach ( $apis as $api=>$title ) {
$list = $this->getCarouselBrowseList($count, $api);
if ( is_array( $list ) ) {
$lists[$api] = $list;
}
}
for ($i=0; $i<$count; $i++ ) {
$slide = new stdClass();
$slide->format = 'browse-group';
$slide->position = $i;
foreach ( $apis as $api=>$detail ) {
$slide->list[$api]['meta'] = $apis[$api];
$slide->list[$api]['item'] = $lists[$api][$i];
}
$slides[] = $slide;
}
}
if ( in_array('pages', $this->params) ) {
$pages = $this->getCarouselPages();
if ( is_array( $pages ) ) {
foreach ( $pages as $p => $page ) {
$slides[] = $page;
}
}
}
if ( isset($this->params['promo']) ) {
$promos = explode(',', $this->params['promo']);
if ( is_array($promos) ) {
foreach ( $promos as $p => $promo ) {
$slides[] = $this->getCarouselPromo($promo);
}
}
}
if ( in_array('news', $this->params) ) {
$slides[] = $this->getCarouselNews();
}
if ( in_array('news-mailgun', $this->params) ) {
$slides[] = $this->getCarouselNewsMailgun();
}
if ( is_array($slides) ) {
//$slides = array_reverse($slides);
if ( in_array('shuffle', $this->params) ) {
shuffle($slides);
}
if ( isset($this->limit) ) {
$slides = array_slice($slides, 0, $this->limit);
}
}
$this->slides = $slides;
if ( in_array('carousel', $this->params) ) {
return $this->getSlidesCarousel();
} else {
return $this->getSlidesFormatted();
}
}
protected function getSlidesFormatted() {
$html = '';
if ( is_array($this->slides) ) {
foreach ( $this->slides as $s => $slide ) {
$html .= $this->getSlideFormatted($slide);
}
}
return $html;
}
protected function getSlidesCarousel() {
if ( !is_array($this->slides) ) {
return;
}
$key = hash('md5',implode($this->params));
$carousel = '';
$auto = null;
if ( in_array('auto', $this->params) ) {
$auto = 'data-ride="carousel" ';
}
$interval = null;
if ( isset($this->params['interval']) ) {
$interval = 'data-interval="'.($this->params['interval']*1000).'" ';
}
$vertical= null;
if ( in_array('vertical', $this->params) ) {
$vertical = 'vertical';
}
$hover = $this->hover;
if ( in_array('pause', $this->params) ) {
$hover = 'hover';
}
if ( 'false' == $hover ) {
$pause = 'data-pause="'.$hover.'" ';
}
$carousel .= PHP_EOL;
$carousel .= '<div style="width:100%;" id="spl-carousel-'.$key.'" class="carousel slide '.$vertical.'" '.$auto.$pause.$interval.'>'.PHP_EOL;
if ( in_array('control', $this->params) ) {
$carousel .= '<div class="carousel-controls">'.PHP_EOL;
$carousel .= '<a class="left carousel-control" href="#spl-carousel-'.$key.'" data-slide="prev"><span class="glyphicon glyphicon-circle-arrow-left"></span></a>'.PHP_EOL;
$carousel .= '<a class="right carousel-control" href="#spl-carousel-'.$key.'" data-slide="next"><span class="glyphicon glyphicon-circle-arrow-right"></span></a>'.PHP_EOL;
if ( in_array('pips', $this->params) ) {
$carousel .= '<ol class="carousel-indicators">'.PHP_EOL;
$i = 0;
foreach ( $this->slides as $s => $slide ) {
$active = '';
if ( 0 == $i ) {
$active = ' class="active"';
}
$carousel .= '<li data-target="#spl-carousel-'.$key.'" data-slide-to="'.$i.'"'.$active.'></li>'.PHP_EOL;
$i++;
}
$carousel .= '</ol>'.PHP_EOL;
}
$carousel .= '</div>'.PHP_EOL; // .carousel-controls
}
$carousel .= '<div class="carousel-inner">'.PHP_EOL;
foreach ( $this->slides as $s => $slide ) {
$active = null;
if ( 0 == $s ) {
$active = ' active';
}
$carousel .= '<div class="item'.$active.'">'.PHP_EOL;
$carousel .= $this->getSlideFormatted($slide);
$carousel .= '</div>'.PHP_EOL; // .item
}
$carousel .= '</div>'.PHP_EOL; // .carousel-inner
$carousel .= '</div>'.PHP_EOL; // .carousel
$carousel .= PHP_EOL;
if ( isset($this->params['timeout']) ) {
// convert minutes to microseconds
$timeout = $this->params['timeout'] * (1000 * 60);
$carousel .= '
<script>
setTimeout(function(){
window.location.reload(1);
}, '.$timeout.');
</script>
';
}
return $carousel;
}
protected function getSlideFormatted($slide) {
$html = '';
$col['left'] = 'col-md-5';
$col['right'] = 'col-md-7';
//$html .= '<div class="spl-tile">'.PHP_EOL;
switch ( $slide->format ) {
case 'news-mailgun':
case 'news':
//$html .= '<div class="panel panel-default">'.PHP_EOL;
//$html .= '<div class="panel-body">'.PHP_EOL;
//$html .= '<div class="spl-tile">'.PHP_EOL;
$html .= '<h5 class="text-success" style="padding:0;">'.$slide->date.'</h5> '.PHP_EOL;
$html .= '<h2>'.PHP_EOL;
$html .= '<a href="'.$slide->url.'">'.$slide->title.'</a>'.PHP_EOL;
$html .= '</h2>'.PHP_EOL;
$html .= '<div class="row">'.PHP_EOL;
$html .= '<div class="col-sm-4">'.PHP_EOL;
if ( $slide->img ) {
$html .= '<a href="'.$slide->url.'">';
$html .= '<img class="img-responsive" style="max-height:160px; margin:auto;" src="'.$slide->img.'">'.PHP_EOL;
$html .= '</a>';
}
$html .= '</div>'.PHP_EOL;
$html .= '<div class="col-sm-8">'.PHP_EOL;
$html .= '<h3 class="text-muted normal" style="margin-top:0px; padding-top:0;">also in this issue…</h3>'.PHP_EOL;
$html .= $slide->content;
//$html .= '<div class="text-right">'.PHP_EOL;
$html .= '<a class="btn btn-success" href="'.$slide->url.'">Read Library News →</a>';
//$html .= '<a class="btn btn-success" href="https://www.surveymonkey.com/r/MDPDSBK">Take our survey →</a>';
//$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
break;
case 'promo':
$html .= '<div class="spl-tile spl-tile-boxed '.$slide->class.'">'.PHP_EOL;
$html .= '<div class="row">'.PHP_EOL;
if ( $slide->img ) {
$html .= '<div class="col-md-4" style="">'.PHP_EOL;
$html .= '<img class="img-responsive" style="max-height:220px;" src="'.$slide->img.'">'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
$html .= '<div class="col-md-8">'.PHP_EOL;
} else {
$html .= '<div class="col-md-12">'.PHP_EOL;
}
$html .= '<div class="spl-tile-body">'.PHP_EOL;
$html .= '<h4>'.$slide->title.'</h4>'.PHP_EOL;
$html .= '<h5 class="normal">'.PHP_EOL;
$html .= $slide->subtitle.PHP_EOL;
$html .= '</h5>'.PHP_EOL;
$html .= '<p><small>'.$slide->content.'</small></p>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a class="btn btn-sm '.$slide->btnclass.'" href="'.$slide->url.'">'.$slide->btntext.' →</a>';
}
$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
//$html .= $slide->subtitle.PHP_EOL;
$html .= '</div>'.PHP_EOL;
break;
case 'browse-group':
//$html .= $slide->position.PHP_EOL;
//$html .= '<div style="height:40px;"></div>'.PHP_EOL;
$html .= '<div class="row">'.PHP_EOL;
foreach ( $slide->list as $api=>$title ) {
$html .= '<div class="col-sm-3">'.PHP_EOL;
//$html .= '<div class="panel panel-default" style="border-left-width:5px;">'.PHP_EOL;
//$html .= '<div class="panel-body">'.PHP_EOL;
$html .= '<div style="height:186px; overflow:hidden;">'.PHP_EOL;
if ( $title['item']->img ) {
$img = '<img style="max-height:180px; margin:auto;" class="img-responsive img-rounded" src="'.$title['item']->img.'">';
if ( $title['item']->url ) {
$html .= '<a href="'.$title['item']->url.'">'.$img.'</a>'.PHP_EOL;
} else {
$html .= $img.PHP_EOL;
}
}
$html .= '</div>'.PHP_EOL;
$html .= '<div style="height:50px; overflow:hidden;">'.PHP_EOL;
$html .= '<h6 class="text-center">';
if ( $title['item']->title ) {
$title['item']->title = preg_replace("/\[[^\[\]]*\]/", '', $title['item']->title);
}
if ( $title['item']->url ) {
$html .= '<a href="'.$title['item']->url.'">'.$title['item']->title.'</a>'.PHP_EOL;
} else {
$html .= $title['item']->title.PHP_EOL;
}
$html .= '</h6>';
$html .= PHP_EOL;
$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '<div class="panel-footer">'.PHP_EOL;
//$html .= '<h5 class="text-center">';
$html .= '<p>'.PHP_EOL;
//btn btn-block btn-sm btn-default
$html .= '<a class="btn btn-block btn-default" href="'.$title['meta']['link'].'">';
$html .= '<i class="glyphicon glyphicon-'.$title['meta']['icon'].'"></i> '.$title['meta']['label'].'<small class="hidden-sm"> →</small>';
$html .= '</a>'.PHP_EOL;
$html .= '</p>'.PHP_EOL;
//$html .= '</h5>';
//$html .= PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
}
$html .= '</div>'.PHP_EOL;
//$html .= '<pre>'.PHP_EOL;
//$html .= print_r($slide, true);
//$html .= '</pre>'.PHP_EOL;
break;
case 'browse':
//$html .= '<div class="col-sm-6 col-md-3">'.PHP_EOL;
//$html .= '<div class="panel panel-default" style="border-left-width:5px;">'.PHP_EOL;
//$html .= '<div class="panel-body">'.PHP_EOL;
//$html .= '<div class="spl-tile">'.PHP_EOL;
//$html .= '<h6 class="text-muted uppercase">Reading List</h6>'.PHP_EOL;
if ( $slide->img ) {
$img = '<img style="max-height:180px; margin-auto;" class="img-responsive img-rounded" src="'.$slide->img.'">';
$html .= '<p>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$img.'</a>'.PHP_EOL;
} else {
$html .= $img.PHP_EOL;
}
$html .= '</p>'.PHP_EOL;
}
$html .= '<h5>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$slide->title.'</a>'.PHP_EOL;
} else {
$html .= $slide->title.PHP_EOL;
}
$html .='</h5>'.PHP_EOL;
/*
if ( $slide->author ) {
$html .= '<small>';
$html .= '<span class="text-muted">';
$html .= 'by ';
$html .= '</span>';
$html .= $slide->author;
$html .= '</small>'.PHP_EOL;
}
*/
/*
if ( $slide->content ) {
$html .= '<p><small>';
$html .= $slide->content;
$html .= '</small></p>'.PHP_EOL;
}
*/
/*
if ( $slide->url ) {
$html .= '<div class="text-right">'.PHP_EOL;
$html .= '<a href="'.$slide->url.'"><small>More →</small></a>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
}
*/
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
break;
case 'calendar-embedded':
//$html .= '<div class="spl-tile spl-tile-success">'.PHP_EOL;
//$html .= '<h4 class="text-center" style=""><i class="glyphicon glyphicon-calendar"></i> Join Us</h4>'.PHP_EOL;
//$html .= '<div class="panel-body">'.PHP_EOL;
if ( $slide->location ) {
$html .= '<h6 class="uppercase text-success">'.PHP_EOL;
if ( $slide->branch ) {
$html .= '<a href="/'.$slide->branch.'/"><span class="text-success">'.$slide->location.'</span></a>'.PHP_EOL;
} else {
$html .= $slide->location.PHP_EOL;
}
$html .= '</h6>'.PHP_EOL;
}
$html .= '<h5>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$slide->title.'</a>'.PHP_EOL;
} else {
$html .= $slide->title.PHP_EOL;
}
$html .= '</h5>'.PHP_EOL;
//$html .= '<h5 class="normal">'.$slide->datetime.'</h5 >'.PHP_EOL;
$html .= '<h6 class="uppercase">'.$slide->date.'</h6 >'.PHP_EOL;
$html .= '<h5 class=""><i class="glyphicon glyphicon-time text-muted"></i> '.$slide->time.'</h5>'.PHP_EOL;
if ( $slide->img ) {
/*
$html .= '<div style="height:100px; overflow:hidden;">'.PHP_EOL;
$html .= '<img class="img-responsive" style="margin:auto;" src="'.$slide->img.'">'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
*/
//$html .= '<div style="height:50px; background-image:url('.$slide->img.'); background-repeat:no-repeat; background-position:center;">'.PHP_EOL;
//$html .= ' '.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
}
if ( $slide->url ) {
$html .= '<h5 class="text-right">'.PHP_EOL;
$html .= '<a href="'.$slide->url.'">Learn More</a> <span class="text-muted">→</span>'.PHP_EOL;
$html .= '</h5>'.PHP_EOL;
}
//$html .= '<small>'.$slide->content.'</small>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL; // .panel-body
break;
case 'calendar':
$html .= '<div class="spl-tile spl-tile-success">'.PHP_EOL;
$html .= '<h6 class="text-success uppercase">Event</h6>'.PHP_EOL;
if ( $slide->location ) {
$html .= '<h6 class="normal">'.PHP_EOL;
if ( $slide->branch ) {
$html .= '<a href="'.$slide->branch.'">'.'@ '.$slide->location.'</a>'.PHP_EOL;
} else {
$html .= '@ '.$slide->location.PHP_EOL;
}
$html .= '</h6>'.PHP_EOL;
}
$html .= '<h5>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$slide->title.'</a>'.PHP_EOL;
} else {
$html .= $slide->title.PHP_EOL;
}
$html .= '</h5>'.PHP_EOL;
//$html .= '<h5 class="normal">'.$slide->datetime.'</h5 >'.PHP_EOL;
$html .= '<h6 class="normal uppercase">'.$slide->date.'</h6 >'.PHP_EOL;
$html .= '<h5 class=""><i class="glyphicon glyphicon-time text-muted"></i> '.$slide->time.'</h5 >'.PHP_EOL;
if ( $slide->img ) {
//$html .= '<img class="img-responsive img-rounded" src="'.$slide->img.'">'.PHP_EOL;
$html .= '<div style="height:50px; background-image:url('.$slide->img.'); background-repeat:no-repeat; background-position:center;">'.PHP_EOL;
$html .= ' '.PHP_EOL;
$html .= '</div>'.PHP_EOL;
}
//$html .= '<small>'.$slide->content.'</small>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
break;
case 'slide':
if ( $slide->img ) {
if ( !in_array('carousel', $this->params) ) {
$html .= '<div class="col-sm-4">'.PHP_EOL;
$html .= '<div class="spl-tile spl-tile-boxed">'.PHP_EOL;
}
$img .= '<img class="img-responsive" style="max-height:280px;" src="'.$slide->img.'">'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$img.'</a>'.PHP_EOL;
} else {
$html .= $img.PHP_EOL;
}
$html .= '<div class="spl-tile-body">'.PHP_EOL;
if ( $slide->title ) {
if ( $slide->url ) {
$html .= '<a class="" href="'.$slide->url.'"><h4>'.$slide->title.'</h4></a>'.PHP_EOL;
} else {
$html .= '<h4>'.$slide->title.'</h4>'.PHP_EOL;
}
}
if ( $slide->subtitle ) {
$html .= '<h5>'.PHP_EOL;
$html .= $slide->subtitle.PHP_EOL;
$html .= '</h5>'.PHP_EOL;
}
if ( $slide->content ) {
$html .= '<small>'.PHP_EOL;
$html .= $slide->content.PHP_EOL;
$html .= '</small>'.PHP_EOL;
}
if ( $slide->url ) {
//$html .= '<div style="background:#fff; border-left:1px solid #666; border-bottom:1px solid #666; position:absolute; top:0; right:0;">'.PHP_EOL;
//$html .= '<a class="btn btn-sm btn-link" href="'.$slide->url.'"><i class="glyphicon glyphicon-share-alt"></i></a>';
//$html .= '</div>'.PHP_EOL;
}
$html .= '</div>'.PHP_EOL;
if ( !in_array('carousel', $this->params) ) {
$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
}
}
break;
case 'facebook':
if ( $slide->img ) {
//$html .= '<div class="spl-hero-panel spl-hero-default">'.PHP_EOL;
$html .= '<h5 style="margin-bottom: 6px;">'.PHP_EOL;
$html .= '<a class="" href="http://facebook.com/spokanelibrary" title="">';
$html .= '<img class="" style="width:16px; height:16px; margin-top:-4px;" src="/assets/img/icons/32px/facebook.png">';
$html .= ' ';
$html .= $slide->date;
$html .= '</a>'.PHP_EOL;
$html .= '</h5>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
//$html .= '<div class="spl-tile-body">'.PHP_EOL;
//$html .= '<div class="spl-tile">'.PHP_EOL;
//$html .= '<h6 class="text-center" style="margin-top:0;">Posted: '.$slide->date.'</h6>'.PHP_EOL;
$html .= '<p>'.PHP_EOL;
$img .= '<img class="img-responsive img-rounded" style="margin:auto; max-height:140px;" src="'.$slide->img.'">'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.PHP_EOL;
$html .= $img;
$html .= '</a>'.PHP_EOL;
} else {
$html .= $img.PHP_EOL;
}
$html .= '</p>'.PHP_EOL;
//$html .= '<a class="" href="http://facebook.com/spokanelibrary" title="">';
//$html .= '<img class="" style="width:16px; height:16px;" src="/assets/img/icons/32px/facebook.png">';
//$html .= '</a>'.PHP_EOL;
$html .= '<small>'.PHP_EOL;
$html .= '<p style="color:#666;">'.PHP_EOL;
$html .= make_clickable( $slide->content ).PHP_EOL;
$html .= '</p>'.PHP_EOL;
$html .= '</small>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<h6 class="text-right">'.PHP_EOL;
$html .= '<a class="" href="'.$slide->url.'">';
$html .= '<b>More →</b>';
$html .= '</a>'.PHP_EOL;
$html .= '</h6>'.PHP_EOL;
}
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL;
$html .= '<hr>'.PHP_EOL;
}
break;
case 'facebook-orig':
if ( $slide->img ) {
$html .= '<div class="spl-hero-panel spl-hero-default">'.PHP_EOL;
$html .= '<div class="spl-tile-body">'.PHP_EOL;
$html .= '<h6 class="text-center" style="margin-top:0;">Posted: '.$slide->date.'</h6>'.PHP_EOL;
$html .= '<p>'.PHP_EOL;
$img .= '<img class="img-responsive img-rounded" style="margin:auto; max-height:140px;" src="'.$slide->img.'">'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.PHP_EOL;
$html .= $img;
$html .= '</a>'.PHP_EOL;
} else {
$html .= $img.PHP_EOL;
}
$html .= '</p>'.PHP_EOL;
$html .= '<p>'.PHP_EOL;
$html .= '<a class="" href="http://facebook.com/spokanelibrary" title="">';
$html .= '<img class="" style="width:16px; height:16px;" src="/assets/img/icons/32px/facebook.png">';
$html .= '</a>'.PHP_EOL;
$html .= '<small>'.PHP_EOL;
$html .= make_clickable( $slide->content ).PHP_EOL;
$html .= '</small>'.PHP_EOL;
$html .= '</p>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<h6 class="text-right">'.PHP_EOL;
$html .= '<a class="" href="'.$slide->url.'">';
$html .= '<b>More →</b>';
$html .= '</a>'.PHP_EOL;
$html .= '</h6>'.PHP_EOL;
}
$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
}
break;
case 'fiction-queen':
$html .= '<div class="spl-tile spl-tile-boxed">'.PHP_EOL;
$html .= '<div class="spl-tile-body">'.PHP_EOL;
//$html .= '<a class="pull-right" href="/fiction-queen/"><small>More →</small></a>'.PHP_EOL;
$html .= '<h4 class="text-warning">The Fiction Queen <small>and her subjects</small></h4>'.PHP_EOL;
$html .= '<h6 class="text-success uppercase">Reviews and recomendations from Spokane Public Library\'s <b>Susan Creed</b></h6>'.PHP_EOL;
$html .= '<div class="serif spl-fiction-queen">'.PHP_EOL;
$html .= '<img style="width:120px; height:120px; margin-right:10px; margin-bottom:6px;" class="pull-left" src="'.$slide->img.'">'.PHP_EOL;
$html .= '<h4>'.$slide->title.'</h4>'.PHP_EOL;
$html .= $slide->content.PHP_EOL;
$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
break;
case 'this-week':
//$html .= '<div class="row">'.PHP_EOL;
//$html .= '<div class="col-sm-8 col-md-8 col-lg-9">'.PHP_EOL;
$html .= '<div class="panel-body">'.PHP_EOL;
$html .= '<h4>'.PHP_EOL;
$html .= '<i class="glyphicon glyphicon-calendar"></i>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$slide->title.'</a>'.PHP_EOL;
} else {
$html .= $slide->title.PHP_EOL;
}
//$html .= $slide->title.PHP_EOL;
$html .= '</h4>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL; // .col
//$html .= '</div>'.PHP_EOL; // .row
//$html .= '<div class="row">'.PHP_EOL;
//$html .= '<div class="col-sm-8 col-md-8 col-lg-9">'.PHP_EOL;
//$html .= '<div class="alert alert-warning">'.PHP_EOL;
$html .= '<div class="row">'.PHP_EOL;
if ( $slide->img ) {
//$slide->img = 'http://lorempixel.com/400/400/abstract/'.rand(1,10);
$html .= '<div class="hidden-xs col-sm-3" style="">'.PHP_EOL;
$img .= '<img class="img-responsive img-rounded" style="max-height:200px; margin:auto;" src="'.$slide->img.'">'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$img.'</a>'.PHP_EOL;
} else {
$html .= $img.PHP_EOL;
}
$html .= '</div>'.PHP_EOL; // .col
}
$html .= '<div class="col-sm-9">'.PHP_EOL;
if ( $slide->subtitle ) {
$html .= '<h5>'.PHP_EOL;
$html .= $slide->subtitle.PHP_EOL;
$html .= '</h5>'.PHP_EOL;
}
$html .= '<p class="">'.$slide->content.'</p>'.PHP_EOL;
/*
if ( $slide->url ) {
$html .= '<p class="text-right">'.PHP_EOL;
$html .= '<a class="btn btn-link" href="'.$slide->url.'"><b>Continued →</b></a>';
$html .= '</p>'.PHP_EOL;
}
*/
if ( $slide->url ) {
$html .= '<h5 class="text-right">'.PHP_EOL;
$html .= '<a href="'.$slide->url.'">Learn More</a> <span class="text-muted">→</span>';
$html .= '</h5>'.PHP_EOL;
}
$html .= '</div>'.PHP_EOL; // .col
$html .= '</div>'.PHP_EOL; // .row
//$html .= '</div>'.PHP_EOL;
$html .= '</div>'.PHP_EOL; // .panel-body
//$html .= '</div>'.PHP_EOL; // .col
//$html .= '<div class="col-sm-4 col-md-4 col-lg-3">'.PHP_EOL;
//$html .= '<div class="panel spl-hero-panel spl-hero-muted">'.PHP_EOL;
//$html .= '<h4 class="text-center" style=""><i class="glyphicon glyphicon-calendar"></i> Join Us</h4>'.PHP_EOL;
//$html .= do_shortcode('[spl_widget home-page carousel pause auto calendar embedded refresh]');
//$html .= '</div>'.PHP_EOL;
//$html .= '</div>'.PHP_EOL; // .col
//$html .= '</div>'.PHP_EOL; // .row
break;
case 'post':
case 'page':
default:
//if ( $slide->img ) {
$html .= '<div class="spl-hero-panel spl-hero-primary" style="margin-bottom:10px;">'.PHP_EOL;
$html .= '<h4>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<a href="'.$slide->url.'">'.$slide->title.'</a>'.PHP_EOL;
} else {
$html .= $slide->title.PHP_EOL;
}
$html .= '</h4>'.PHP_EOL;
$html .= '</div>'.PHP_EOL;
$html .= '<div class="spl-tile '.$slide->class.'">'.PHP_EOL;
//$html .= '<div class="spl-tile-body">'.PHP_EOL;
$html .= '<div class="row">'.PHP_EOL;
if ( $slide->img ) {
$https_img = preg_replace("/^http:/i", "https:", $slide->img);
$html .= '<div class="col-md-5" style="">'.PHP_EOL;
$img .= '<img class="img-responsive img-rounded" style="max-height:200px; margin:auto;" src="'.$https_img.'">'.PHP_EOL;
if ( $slide->url ) {
$https_url = preg_replace("/^http:/i", "https:", $slide->url);
$html .= '<a href="'.$https_url.'">'.$img.'</a>'.PHP_EOL;
} else {
$html .= $img.PHP_EOL;
}
$html .= '</div>'.PHP_EOL; // .col
}
$html .= '<div class="col-md-7">'.PHP_EOL;
if ( $slide->subtitle ) {
$html .= '<h5>'.PHP_EOL;
$html .= $slide->subtitle.PHP_EOL;
$html .= '</h5>'.PHP_EOL;
}
$html .= '<p><small>'.$slide->content.'</small></p>'.PHP_EOL;
if ( $slide->url ) {
$html .= '<p class="text-right">'.PHP_EOL;
$html .= '<a class="btn btn-link" href="'.$slide->url.'"><b>Continued →</b></a>';
$html .= '<p>'.PHP_EOL;
}
$html .= '</div>'.PHP_EOL; // .col
$html .= '</div>'.PHP_EOL; // .row
//$html .= '</div>'.PHP_EOL; // .spl-tile-body
$html .= '</div>'.PHP_EOL; // .spl-tile
//}
break;
}
return $html;
}
protected function getCarouselExcerpt($content, $chars=175, $elide='…') {
if ( strlen($content) > $chars) {
$str = substr($content,0,$chars);
$str = substr($str,0,strrpos($str,' '));
if (substr($str, -1) != '.' && substr($str, -1) != '!') {
$str = $str.$elide;
}
} else {
$str = $content;
}
return $str;
}
protected function getCarouselFictionQueen($limit=1) {
$slides = array();
global $post;
$count = $limit;
//$slug = 'readers-corner';
$meta = 'fiction-queen';
//query subpages
$args = array(
'posts_per_page' => $count
//, 'category_name' => $slug
,'meta_key' => $meta
, 'post_type' => 'post'
, 'orderby' => 'post_date'
, 'order' => 'DESC'
);
$posts = new WP_query($args);
if ($posts->have_posts()) :
while ($posts->have_posts()) : $posts->the_post();
$slide = new stdClass();
$slide->format = 'fiction-queen';
$slide->img = '/assets/img/promos/spl-fiction-queen.jpg';
$slide->title = get_the_title();
$slide->content = preg_replace('/<img[^>]+./','', apply_filters('the_content', get_the_content()));
$slides[] = $slide;
endwhile;
endif;
wp_reset_postdata();
return $slides;
}
protected function getCarouselThisWeek($limit=1, $days=10, $meta='this-week', $category='featured') {
$slides = null;
$args = array(
'post_type' => 'post',
'orderby' => 'post_date',
'order' => 'DESC',
'post_status' => 'publish',
//'numberposts' => $limit,
'posts_per_page' => $limit,
'meta_key' => $meta,
//'category_name' => $category,
'date_query' => array( 'column' => 'post_date'
,'after' => '-'.$days.' days' )
);
$posts = new WP_query($args);
if ($posts->have_posts()) {
add_filter( 'excerpt_more', 'spl_carousel_excerpt_more' );
while ($posts->have_posts()) {
$posts->the_post();
$slide = new stdClass;
$slide->format = 'this-week';
$slide->url = get_permalink();
if ( has_post_thumbnail() ) {
$slide->img = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), $this->thumb);
$slide->img = $slide->img[0];
}
//$slide->id = get_the_ID();
$slide->title = get_the_title();
$slide->content = get_the_excerpt();
$slide->content = $this->getCarouselExcerpt($slide->content, 380);
$slides[] = $slide;
}
remove_filter( 'excerpt_more', 'spl_carousel_excerpt_more' );
}
wp_reset_postdata();
return $slides;
}
protected function getCarouselFacebook($limit=3) {
$feed = SPL_Widget::curlProxy('https://graph.facebook.com/spokanelibrary/posts?access_token=289675684463099|XhXcLjuFeUpR40hl9cfexCBjl3c', null, 'get');
if ( $feed && $feed->response ) {
$posts = json_decode($feed->response);
if ( is_array($posts->data) ) {
$posts = $posts->data;
foreach ( $posts as $post) {
$date = new datetime($post->created_time);
$slide = new stdClass;
$slide->format = 'facebook';
$slide->img = $post->picture;
if ( false === stristr($post->link, 'facebook.com/spokanelibrary/photos') ) {
$slide->url = $post->link;
}
//$slide->title = '';
$slide->date = $date->format('D, M j').'<sup style="text-transform:lowercase;">'.$date->format('S').'</sup>';
//$slide->subtitle = $post->description;
$slide->content = $post->message;
//$slide->content = $this->getCarouselExcerpt($slide->content, 100);
$slides[] = $slide;
}
$slides = array_slice($slides, 0, $limit);
return $slides;
}
}
}
protected function getCarouselNewsMailgun() {
//return $this->getCarouselNews();
$slide = new stdClass;
$slide->format = 'news';
$q = new WP_Query( 'post_type=newsletter&post_status=publish&posts_per_page=1' );
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id($q->post->ID), 'medium');
$slide->url = get_permalink($q->post->ID);
$slide->img = $thumb[0];
$slide->title = $q->post->post_title;
$slide->excerpt = $q->post->post_excerpt;
$slide->date = get_post_meta($q->post->ID
,'_spl_mailgun_newsletter_subtitle'
,true
);
$posts = array();
for ( $i=1; $i<= 12; $i++ ) {
$select = SPL_Mailgun_Newsletter::getPostSelect($q->post->ID, $i);
if ( !empty($select) ) {
$posts[$i] = $select;
}
}
if ( !empty($posts) ) {
if ( isset($params['link_posts']) ) {
$html .= '<ul class="">';
foreach ( $posts as $post ) {
$html .= '<li><b><a href="'.$post->link.'">'.$post->title.'</a></b></li>';
}
$html .= '</ul>';
} else {
$html .= '<ul class="">';
foreach ( $posts as $post ) {
$html .= '<li><b>';
$html .= ''.$post->title.'';
$html .= '</b></li>';
}
$html .= '</ul>';
}
//$html .= '<h4><a class="" href="'.get_the_permalink($q->post->ID).'">Read Library News →</a></h4>';
} elseif ( !empty($slide->excerpt) ) {
$html = $slide->excerpt;
}
$slide->content = $html;
return $slide;
}
protected function getCarouselNews() {
$slide = new stdClass;
$slide->format = 'news';
//$slide->url = '/news/';
$slide->url = 'http://news.spokanelibrary.org/newsletter/july-mid-month-news/';
$slide->img = 'http://news.spokanelibrary.org/wordpress/media/Hoopla_blue_square.png';
$slide->title = 'Have you tried Hoopla?';
$slide->date = 'July';
$slide->content = '
<ul class="text-muted">
<li><a href="http://news.spokanelibrary.org/local-authors-at-the-libraries/">Local Authors at the Libraries <small class="text-muted">→</small></a></li>
<li><a href="http://news.spokanelibrary.org/srp-programs-15/">Escape the Ordinary with Summer Events for Kids and Families <small class="text-muted">→</small></a></li>
<li><a href="http://news.spokanelibrary.org/dewey_7-15/">Cool off with Dewey <small class="text-muted">→</small></a></li>
<li><a href="http://news.spokanelibrary.org/fiction_queen2/">The Fiction Queen Recommends <small class="text-muted">→</small></a></li>
<li><a href="http://news.spokanelibrary.org/five-songs7-15-15/">Five Songs from You and Me and Him by local author, Kris Dinnison <small class="text-muted">→</small></a></li>
</ul>
';
/*
$slide->img = 'http://news.spokanelibrary.org/wordpress/media/Shadle_Sunday_hours2-300x282.jpg';
$slide->title = 'New Year, New You, New Day for the Library';
//$slide->subtitle = 'Subtitle';
$slide->date = 'January';
$slide->content = '
<ul class="text-muted">
<li><a href="http://news.spokanelibrary.org/new-year-new-you/"><b>What’s on your “to do” list for 2015?</b> <small class="text-muted">→</small></a></li>
<li><a href="http://news.spokanelibrary.org/dewey_1-15/"><b>Dewey’s (self) helpful side</b> <small class="text-muted">→</small></a></li>
<li><a href="http://news.spokanelibrary.org/5_magazines_1-15/"><b>Five Magazines instead of Five Songs This Month</b> <small class="text-muted">→</small></a></li>
</ul>
';
*/
return $slide;
}
protected function getCarouselPromo($promo) {
$slide = new stdClass;
$slide->format = 'promo';
switch ($promo) {
case 'yearbooks':
$slide->class = 'spl-tile-brown';
$slide->btnclass = 'btn-alt';
$slide->btntext = 'Browse yearbooks';
$slide->url = '/yearbooks/';
$slide->img = '/assets/img/promos/spl-yearbooks-promo-classroom.jpg';
$slide->title = 'Blast from the past';
$slide->subtitle = 'Spokane high shool yearbooks: 1911 to 1977.';
$slide->content = 'Now available online.';
$slide->promo = '
<img class="img-responsive" src="/assets/img/promos/spl-yearbooks-promo-sm.jpg">
';
break;
case 'tech':
$slide->class = 'spl-tile-blue';
$slide->btnclass = 'btn-default';
$slide->btntext = 'Get started now';
$slide->url = '/tech/';
$slide->img = '/assets/img/promos/spl-apple-devices-portrait.png';
$slide->title = 'Technology training & certification';
$slide->subtitle = 'Self-paced or instructor-led courses for all skill levels.';
$slide->content = 'Windows, Office, SQL Server, Illustrator, InDesign…';
$slide->promo = '
';
break;
default:
/*
$slide->url = '';
$slide->img = '';
$slide->title = '';
$slide->subtitle = '';
$slide->content = '';
*/
break;
}
return $slide;
}
protected function getCarouselBrowseList($limit=4, $api='star') {
$list = SPL_Widget::curlPostProxy('http://api.spokanelibrary.org/browse/'.$api);
//$list = SPL_Widget::curlPostProxy('http://api.spokanelibrary.org/new/?menu='.$api);
$list = json_decode($list);
$slides = array();
if ( is_array($list->titles) ) {
$titles = array_slice($list->titles, 0, $limit*2);
unset($list);
foreach ( $titles as $title ) {
//if ( !empty($title->summary) && ( !empty($title->isbn) || !empty($title->upc) ) ) {
if ( !empty($title->upc) ) {
$title->upc = str_pad($title->upc, 12, '0', STR_PAD_LEFT);
}
if ( !empty($title->upc) ) {
$ebsco = $title->upc;
} elseif ( !empty($title->isbn) ) {
$ebsco = $title->isbn;
}
$slide = new stdClass();
$slide->format = 'browse';
$slide->title = $this->getCarouselExcerpt($title->title, 65);
$slide->author = $title->author;
$slide->img = 'https://contentcafe2.btol.com/ContentCafe/jacket.aspx?UserID=ebsco-test&Password=ebsco-test&Return=T&Type=M&Value='.$ebsco;
$slide->url = '/bib/'.$title->bib.'/';
$slide->content = $this->getCarouselExcerpt($title->summary, 85);
$slide->isbn = $title->isbn;
$slide->upc = $title->upc;
$slides[] = $slide;
//}
}
}
$slides = array_slice($slides, 0, $limit);
return $slides;
}
protected function getCarouselCalendar($limit=10, $chars=75) {
$feed = null;
$uri = 'http://www.trumba.com/calendars/spl-web-feed.rss';
add_filter( 'wp_feed_cache_transient_lifetime', function() {
return 0;
});
$rss = fetch_feed( $uri );
remove_all_filters( 'wp_feed_cache_transient_lifetime' );
if ( ! is_wp_error( $rss ) ) {
$maxitems = $rss->get_item_quantity( $limit );
$feed = $rss->get_items( 0, $maxitems );
}
$slides = null;
if ( is_array($feed) ) {
$slides = array();
foreach ( $feed as $item ) {
$event = new stdClass();
$location = $item->get_item_tags('urn:ietf:params:xml:ns:xcal', 'location');
$formatteddatetime = $item->get_item_tags('http://schemas.trumba.com/rss/x-trumba', 'formatteddatetime');
$description = $item->get_item_tags('urn:ietf:params:xml:ns:xcal', 'description');
$customfields = $item->get_item_tags('http://schemas.trumba.com/rss/x-trumba', 'customfield');
$event->format = 'calendar';
if ( in_array('embedded', $this->params) ) {
$event->format = 'calendar-embedded';
}
$event->title = esc_html( $item->get_title() );
$event->url = esc_url( $item->get_permalink() );
$event->datetime = esc_html( $formatteddatetime[0]['data'] );
$event->time = trim(strrchr($event->datetime, ','), ',');
$event->date = trim(strstr($event->datetime, $event->time, true), ',');
try {
$dt = new datetime($event->date);
$event->date = $dt->format('l, F j').'<sup style="text-transform:lowercase;">'.$dt->format('S').'</sup>';
}
catch (Exception $e) {
//echo 'Caught exception: ', $e->getMessage(), "\n";
$dt = new datetime();
$ts = strtotime($event->date);
$dt->setTimestamp($ts);
// Actually just leave the provided format alone.
}
$event->location = esc_html( $location[0]['data'] );
$description = esc_html( $description[0]['data'] );
$description = substr($description,0,$chars);
$description = substr($description,0,strrpos($description," "));
if (substr($description, -1) != '.' && substr($description, -1) != '!') {
$description = $description.'…';
}
$event->content = $description;
switch ( $location[0]['data'] ) {
case 'East Side Library':
$event->branch = 'east-side';
break;
case 'Hillyard Library':
$event->branch = 'hillyard';
break;
case 'Indian Trail Library':
$event->branch = 'indian-trail';
break;
case 'Shadle Library':
$event->branch = 'shadle';
break;
case 'South Hill Library':
$event->branch = 'south-hill';
break;
case 'Downtown Library':
$event->branch = 'downtown';
break;
default:
break;
}
if ( is_array($customfields) ) {
foreach( $customfields as $f => $field ) {
$fieldname = trim($field['attribs']['']['name']);
switch ( $fieldname ) {
case 'Event image':
$event->img = $field['data'];
break;
default:
//$field['attribs']['']['name'];
//$field['data'];
break;
}
}
}
$slides[] = $event;
}
}
return $slides;
}
protected function getCarouselPages($limit=12, $meta='featured') {
/*
$slide = new stdClass();
$slide->url = './';
//$slide->img = 'img.png';
$slide->title = 'Featured page';
$slide->subtitle = 'subtitle';
$slide->content = 'A featured page is like a featured post. Only different.';
$slides[] = $slide;
*/
$slides = null;
$args = array(
'post_type' => 'page',
'orderby' => 'post_date',
'order' => 'DESC',
'post_status' => 'publish',
//'numberposts' => $limit,
'posts_per_page' => $limit,
'meta_key' => 'featured'
//'category_name' => $category,
//'date_query' => array( 'column' => 'post_date'
// ,'after' => '-'.$days.' days' )
);
$posts = new WP_query($args);
if ($posts->have_posts()) {
add_filter( 'excerpt_more', 'spl_carousel_excerpt_more' );
while ($posts->have_posts()) {
$posts->the_post();
$slide = new stdClass;
$slide->format = 'page';
$slide->url = get_permalink();
if ( has_post_thumbnail() ) {
$slide->img = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), $this->thumb);
$slide->img = $slide->img[0];
}
//$slide->id = get_the_ID();
$slide->title = get_the_title();
$slide->content = get_the_excerpt();
$slides[] = $slide;
}
remove_filter( 'excerpt_more', 'spl_carousel_excerpt_more' );
}
wp_reset_postdata();
return $slides;
}
protected function getCarouselPosts($limit=3, $days=14, $category='featured') {
$slides = null;
$args = array(
'post_type' => 'post',
'orderby' => 'post_date',
'order' => 'DESC',
'post_status' => 'publish',
//'numberposts' => $limit,
'posts_per_page' => $limit,
'category_name' => $category,
'date_query' => array( 'column' => 'post_date'
,'after' => '-'.$days.' days' )
);
$posts = new WP_query($args);
if ($posts->have_posts()) {
add_filter( 'excerpt_more', 'spl_carousel_excerpt_more' );
while ($posts->have_posts()) {
$posts->the_post();
$slide = new stdClass;
$slide->format = 'post';
$slide->url = get_permalink();
if ( has_post_thumbnail() ) {
$slide->img = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), $this->thumb);
$slide->img = $slide->img[0];
}
//$slide->id = get_the_ID();
$slide->title = get_the_title();
$slide->content = get_the_excerpt();
$slide->content = $this->getCarouselExcerpt($slide->content, 280);
$slides[] = $slide;
}
remove_filter( 'excerpt_more', 'spl_carousel_excerpt_more' );
}
wp_reset_postdata();
return $slides;
}
protected function getCarouselSlides() {
$slides = null;
$id = $this->id;
if ( isset($this->params['slug']) ) {
$imgPage = get_page_by_path($this->params['slug']);
}
if ( $imgPage ) {
$id = $imgPage->ID;
}
$orderby = 'menu_order';
if ( in_array('random', $this->params) ) {
$orderby = 'rand';
}
$args = array(
'post_type' => 'attachment',
'orderby' => $orderby,
'order' => 'ASC',
'numberposts' => null,
'post_status' => null,
'post_parent' => $id
);
$attachments = get_posts($args);
if ( is_array($attachments) ) {
foreach ( $attachments as $a => $attachment) {
$slide = new stdClass;
$slide->format = 'slide';
$slide->url = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$slide->img = wp_get_attachment_image_src($attachment->ID, $this->thumb);
$slide->img = $slide->img[0];
//$slide->img = $attachment->guid;
$slide->title = $attachment->post_title;
$slide->subtitle = $attachment->post_excerpt;
$slide->content = $attachment->post_content;
$slides[] = $slide;
}
}
return $slides;
}
}
?>
| mit |
voxsoftware/icevw | org/vox/icevw/server/assets/js/require.js | 6609 | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1)
var Require= __webpack_require__(2).default
var icevw= core.org.icevw
icevw.client.Require= Require
exports.default= Require
/***/ },
/* 1 */
/***/ function(module, exports) {
core.org= core.org||{}
var icevw= core.org.icevw= core.org.icevw||{}
icevw.client= icevw.client||{}
module.exports= exports= icevw
/***/ },
/* 2 */
/***/ function(module, exports) {
var vox = core.VW.Web.Vox;
{
var Require = function Require() {
Require.constructor ? Require.constructor.apply(this, arguments) : Require.$super && Require.$super.constructor.apply(this, arguments);
};
Require.constructor = function () {
this.initEvents();
};
Require.prototype.start = function () {
var self = this;
var form = this.form = $('.modal form');
form.find('[name]').each(function () {
this.value = self.arguments[this.name];
});
if (self.arguments.enabled) {
self.load();
}
$('.modal').voxmodal()[0].open();
};
Require.prototype.load = function callee$0$0() {
var self, req;
return regeneratorRuntime.async(function callee$0$0$(context$1$0) {
while (1)
switch (context$1$0.prev = context$1$0.next) {
case 0:
$('.modal .load').show();
$('.modal a').hide();
self = this;
req = new core.VW.Http.Request('/api/load');
req.body = self.arguments;
req.method = 'POST';
context$1$0.prev = 6;
context$1$0.next = 9;
return regeneratorRuntime.awrap(vox.platform.getJsonResponseAsync(req));
case 9:
response = context$1$0.sent;
context$1$0.next = 17;
break;
case 12:
context$1$0.prev = 12;
context$1$0.t0 = context$1$0['catch'](6);
$('.modal').voxmodal()[0].close();
window.parent.postMessage(JSON.stringify({
'type': 'icevw.adquireerror',
'error': context$1$0.t0
}), self.arguments.domain);
return context$1$0.abrupt('return', false);
case 17:
window.parent.postMessage(JSON.stringify({
'type': 'icevw.adquiredandloaded',
'data': response
}), self.arguments.domain);
return context$1$0.abrupt('return', true);
case 19:
case 'end':
return context$1$0.stop();
}
}, null, this, [[
6,
12
]]);
};
Require.prototype.initEvents = function () {
this.events = {};
var self = this;
this.events.permitir = function callee$0$0() {
var req, response;
return regeneratorRuntime.async(function callee$0$0$(context$1$0) {
while (1)
switch (context$1$0.prev = context$1$0.next) {
case 0:
context$1$0.prev = 0;
req = new core.VW.Http.Request();
req.form = self.form;
context$1$0.next = 5;
return regeneratorRuntime.awrap(vox.platform.getJsonResponseAsync(req));
case 5:
response = context$1$0.sent;
window.parent.postMessage(JSON.stringify({
'type': 'icevw.adquired',
'data': response
}), self.arguments.domain);
context$1$0.next = 9;
return regeneratorRuntime.awrap(self.load());
case 9:
context$1$0.next = 15;
break;
case 11:
context$1$0.prev = 11;
context$1$0.t0 = context$1$0['catch'](0);
$('.modal').voxmodal()[0].close();
window.parent.postMessage(JSON.stringify({
'type': 'icevw.adquireerror',
'error': context$1$0.t0
}), self.arguments.domain);
case 15:
case 'end':
return context$1$0.stop();
}
}, null, this, [[
0,
11
]]);
};
this.events.nopermitir = function () {
$('.modal').voxmodal()[0].close();
window.parent.postMessage(JSON.stringify({
'type': 'icevw.notauthorized',
'error': 'No fue autorizado para ejecutar ICEVW'
}), self.arguments.domain);
};
};
}
exports.default = Require;
/***/ }
/******/ ]); | mit |
jthiv/OccupyTheSystem | application/views/dashboard/inbox.php | 1737 | <?PHP
$arrStanceRequests = $this->stanceRequests;
echo "<h2>Inbox</h2>";
echo "<hr>";
echo "<div id='inbox_wrapper'>";
echo "<div id='inbox_network' class='inbox'>";
echo "<span class='title'><p>Your Network</p></span>";
echo "<em>-Coming Soon-</em>";
echo "</div>";
echo "<div id='inbox_stanceRequests' class='inbox'>";
echo "<span class='title'><p>Stance Requests</p></span>";
if(empty($arrStanceRequests)){
echo "<em>-You have no stance requests-</em>";
}else{
foreach($arrStanceRequests as $req){
//print_r($req);
echo "<p class='reqs'><a href='http://www.occupythesystem.org/overview/showuserprofile/".$req->sender_userID."'>".$req->user_name."</a> wants you to take a stance on <a href='http://www.occupythesystem.org/congress/bill/".$req->billID."'>a bill(".$req->billID.")</a></p>";
}
}
echo "</div>";
echo "<div id='inbox_privateMail' class='inbox'>";
//echo "<span id='inbox_compose_link' class='links'>Compose Message</span>";
// echo "<div id='inbox_compose'>";
// echo "<span class='title'><p>Compose Message</p></span>";
// echo "To: <input type='text' name='message_to' /> <br />";
// echo "Subject: <input type='text' name='message_subject' /><br />";
// echo "Message:<br /><textarea></textarea><br />";
// echo "<input type='submit' class='button' />";
// echo "</div>";
echo "<span class='title'><p>Private Messages</p></span>";
echo "<em>-Coming Soon-</em>";
echo "</div>";
echo "</div>";
?>
<script>
$("#inbox_compose_link").click(function(){
$("#inbox_compose").toggle('slow');
});
</script> | mit |
Pangv/verein | verein/src/de/lebk/verein/event/EventInfoDialog.java | 1605 | package de.lebk.verein.event;
import de.lebk.verein.login.Auth;
import de.lebk.verein.member.Member;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @author sopaetzel
*/
class EventInfoDialog extends JDialog {
private Event event;
private JButton btnDeleteEvent;
public EventInfoDialog(Event event) {
this.event = event;
this.setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
init();
}
private void init() {
btnDeleteEvent = new JButton("Veranstaltung entfernen");
JLabel lblTitle = new JLabel(event.getTitle());
JLabel lblEventType = new JLabel(event.getEventType());
JLabel lblOrganizer = new JLabel(event.getOrganizer().getFullName());
this.add(lblTitle);
this.add(lblEventType);
this.add(lblOrganizer);
if (event.getAttendeeCount() > 0) {
for (Member member : event.getAttendees()) {
JLabel lblAttendee = new JLabel(member.getFullName());
this.add(lblAttendee);
}
} else {
this.add(new JLabel("keine Teilnehmner"));
}
this.add(btnDeleteEvent);
this.actionListeners();
this.pack();
this.setVisible(true);
}
private void actionListeners() {
btnDeleteEvent.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Auth.getInstance().getClub().getEvents().remove(event);
}
});
}
}
| mit |
benstuijts/darkage-framework | server/config/unit/simple_soldier.js | 454 | 'use strict';
const Graphic = require("../../ECS/components/Graphic");
const Meta = require("../../ECS/components/Meta");
module.exports = [
Graphic({
type: "sprite",
image: {
"idle": {
src: "./images/worldmap/unit/legereenheid.png",
width: 48, height: 48,
xpos: 0, ypos: 0
}
}
}),
Meta({
name: "A group if simple soldiers level 1"
})
]; | mit |
PeqNP/GameKit | specs/royal.client_spec.lua | 11356 | --
-- TODO:
-- ? Fix: Make sure the sprite frames are not loaded into the cache until ALL files are downloaded.
--
require "lang.Signal"
require "specs.Cocos2d-x"
require "Logger"
require "HTTPResponseType"
Log.setLevel(LogLevel.Severe)
local HTTP = require("shim.HTTP")
local Promise = require("Promise")
local AdConfig = require("royal.AdConfig")
local AdManifest = require("royal.AdManifest")
local Client = require("royal.Client")
local AdUnit = require("royal.AdUnit")
local Error = require("Error")
local System = require("shim.System")
System.FileExists = function(path)
return true
end
describe("Client", function()
local subject
local http
local config
local url
before_each(function()
http = HTTP()
config = AdConfig("/path/")
url = "http://www.example.com:80/ad/com.example.game/"
subject = Client(http, config, url)
end)
pending("getAdConfig")
describe("fetch config", function()
local cache
local promise
local adRequest
local plistRequest
local pngRequest
local wasCalled
local success
local manifest
local _error
local jsonStr
local ad_called
local plist_called
local png_called
local function fetch_config()
wasCalled = false
promise = subject.fetchConfig()
promise.done(function(_manifest)
manifest = _manifest
end)
promise.fail(function(__error)
_error = __error
end)
promise.always(function()
wasCalled = true
end)
end
function new_requests()
adRequest = Promise()
plistRequest = Promise()
pngRequest = Promise()
end
before_each(function()
ad_called = false
plist_called = false
png_called = false
cache = cc.SpriteFrameCache:getInstance()
stub(cache, "removeSpriteFrames")
new_requests()
function http.get(path, responseType, callback)
if path == "http://www.example.com:80/ad/com.example.game/royal.json" then
ad_called = true
return adRequest
elseif path == "http://www.example.com:80/ad/com.example.game/sd/royal.plist" then
plist_called = true
return plistRequest
elseif path == "http://www.example.com:80/ad/com.example.game/sd/royal.png" then
png_called = true
return pngRequest
else
print("Invalid path: ".. path)
end
end
spy.on(http, "get")
jsonStr = "{\"created\": 1000, \"units\": [{\"id\": 2, \"startdate\": 4, \"enddate\": 5, \"url\": \"http://www.example.com\", \"reward\": 25, \"title\": \"A title!\", \"config\": null}]}"
end)
context("when the config is not cached", function()
local jsonDict
before_each(function()
fetch_config()
end)
it("should NOT have made call to remove plist's sprite frames", function()
assert.stub(cache.removeSpriteFrames).was_not.called()
end)
it("should have returned a Promise", function()
assert.truthy(promise.kindOf(Promise))
end)
it("should have made request for json manifest", function()
assert.truthy(ad_called)
end)
it("should have NOT sent plist request", function()
assert.falsy(plist_called)
end)
it("should have NOT sent png request", function()
assert.falsy(png_called)
end)
it("should still have network request in-flight", function()
assert.falsy(wasCalled)
end)
-- @todo Add test when data provided to us from server is corrupted. This should
-- use internal methods which already handle this breakage. But this must fail
-- gracefully by rejecting the promise.
context("when the request succeeds", function()
before_each(function()
stub(config, "write")
adRequest.resolve(200, jsonStr)
end)
it("should have saved the manifest", function()
assert.stub(config.write).was.called_with("royal.json", jsonStr, "wb")
end)
it("should have made request for plist", function()
assert.truthy(plist_called)
end)
it("should have made request for png", function()
assert.truthy(png_called)
end)
it("should not have resolved the promise yet", function()
assert.falsy(wasCalled)
end)
it("should have no errors", function()
local e = subject.getErrors()
assert.equals(0, #e)
end)
describe("when the remaining requests succeed", function()
before_each(function()
stub(cache, "addSpriteFrames")
plistRequest.resolve(200, "PLIST-DATA")
pngRequest.resolve(200, "PNG-DATA")
end)
it("should have resolved the promise", function()
assert.truthy(wasCalled)
end)
it("should have returned the manifest", function()
assert.truthy(manifest)
assert.equal(AdManifest, manifest.getClass())
end)
it("should have written plist to disk", function()
assert.stub(config.write).was.called_with("royal.plist", "PLIST-DATA", "wb")
end)
it("should have written png to disk", function()
assert.stub(config.write).was.called_with("royal.png", "PNG-DATA", "wb")
end)
it("should have made call to cache the plist", function()
assert.stub(cache.addSpriteFrames).was.called_with(cache, "/path/royal.plist")
end)
describe("when fetchConfig() is called a subsequent time", function()
before_each(function()
new_requests()
fetch_config()
end)
it("should have made call to clear the cache", function()
assert.stub(cache.removeSpriteFrames).was.called_with(cache, config.getPlistFilepath())
end)
end)
end)
describe("when the remaining requests fail", function()
before_each(function()
plistRequest.reject(100, "Some error")
pngRequest.reject(404, "Resource not found")
end)
it("should have resolved the promise", function()
assert.truthy(wasCalled)
end)
it("should have returned failure", function()
assert.truthy(_error)
assert.equal(Error, _error.getClass())
end)
it("should have created two errors", function()
local e = subject.getErrors()
assert.equals(2, #e)
end)
-- @note Nothing should have been written to disk. There's no reason
-- to perform a sanity check.
describe("when fetch config is called a subsequent time", function()
before_each(function()
new_requests()
fetch_config()
end)
it("should have cleared the errors", function()
local e = subject.getErrors()
assert.equals(0, #e)
end)
it("should NOT have made call to clear the cache", function()
assert.stub(cache.removeSpriteFrames).was_not.called()
end)
end)
end)
end)
context("when the request fails", function()
before_each(function()
stub(config, "write")
adRequest.reject(500, "Internal server error")
end)
it("should have failed", function()
assert.truthy(_error)
assert.equal(Error, _error.getClass())
end)
-- @note No need to check if the plist/png files were downloaded. Those are
-- sanity checks only.
it("should have one error", function()
local e = subject.getErrors()
assert.equals(1, #e)
end)
it("should NOT have written any files to disk", function()
assert.stub(config.write).was.not_called()
end)
end)
end)
context("when the cached manifest is the same", function()
local cached
before_each(function()
stub(config, "write")
cached = AdManifest(1000, {})
subject.setCachedManifest(cached)
fetch_config()
adRequest.resolve(200, jsonStr)
end)
it("should have resolved the promise", function()
assert.truthy(wasCalled)
end)
it("should have returned the cached manifest", function()
assert.truthy(manifest)
assert.equal(cached, manifest)
end)
-- @note Should not have made requests to plist/png files.
end)
context("when the cached manifest is old", function()
local cached
before_each(function()
stub(config, "write")
cached = AdManifest(999, {})
subject.setCachedManifest(cached)
fetch_config()
adRequest.resolve(200, jsonStr)
end)
it("should NOT have resolved the promise", function()
assert.falsy(wasCalled)
end)
it("should have made request for plist", function()
assert.truthy(plist_called)
end)
it("should have made request for png", function()
assert.truthy(png_called)
end)
-- @note The cycle should now be the same as if there was no cached manifest.
end)
end)
-- @todo Make requests resolved out of order to ensure that the correct
-- request is removed after it completes.
-- @todo when two or more downloads fail.
end)
| mit |
bitrise-io/steps-new-xcode-test | simulator/simulator_test.go | 3794 | package simulator
import (
"fmt"
"os"
"path/filepath"
"testing"
mockcommand "github.com/bitrise-steplib/steps-xcode-test/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type testingMocks struct {
commandFactory *mockcommand.CommandFactory
}
func Test_GivenSimulator_WhenResetLaunchServices_ThenPerformsAction(t *testing.T) {
// Given
xcodePath := "/some/path"
manager, mocks := createSimulatorAndMocks()
mocks.commandFactory.On("Create", "sw_vers", []string{"-productVersion"}, mock.Anything).Return(createCommand("11.6"))
mocks.commandFactory.On("Create", "xcode-select", []string{"--print-path"}, mock.Anything).Return(createCommand(xcodePath))
lsregister := "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
simulatorPath := filepath.Join(xcodePath, "Applications/Simulator.app")
mocks.commandFactory.On("Create", lsregister, []string{"-f", simulatorPath}, mock.Anything).Return(createCommand(""))
// When
err := manager.ResetLaunchServices()
// Then
assert.NoError(t, err)
}
func Test_GivenSimulator_WhenBoot_ThenBootsTheRequestedSimulator(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
identifier := "test-identifier"
parameters := []string{"simctl", "boot", identifier}
mocks.commandFactory.On("Create", "xcrun", parameters, mock.Anything).Return(createCommand(""))
// When
err := manager.SimulatorBoot(identifier)
// Then
assert.NoError(t, err)
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
func Test_GivenSimulator_WhenEnableVerboseLog_ThenEnablesIt(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
identifier := "test-identifier"
parameters := []string{"simctl", "logverbose", identifier, "enable"}
mocks.commandFactory.On("Create", "xcrun", parameters, mock.Anything).Return(createCommand(""))
// When
err := manager.SimulatorEnableVerboseLog(identifier)
// Then
assert.NoError(t, err)
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
func Test_GivenSimulator_WhenCollectDiagnostics_ThenCollectsIt(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
mocks.commandFactory.On("Create", "xcrun", mock.Anything, mock.Anything).Return(createCommand(""))
// When
diagnosticsOutDir, err := manager.SimulatorCollectDiagnostics()
defer func() {
// Do not forget to clen up the temp dir
_ = os.RemoveAll(diagnosticsOutDir)
}()
// Then
assert.NoError(t, err)
parameters := []string{"simctl", "diagnose", "-b", "--no-archive", fmt.Sprintf("--output=%s", diagnosticsOutDir)}
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
func Test_GivenSimulator_WhenShutdown_ThenShutsItDown(t *testing.T) {
// Given
manager, mocks := createSimulatorAndMocks()
identifier := "test-identifier"
parameters := []string{"simctl", "shutdown", identifier}
mocks.commandFactory.On("Create", "xcrun", parameters, mock.Anything).Return(createCommand(""))
// When
err := manager.SimulatorShutdown(identifier)
// Then
assert.NoError(t, err)
mocks.commandFactory.AssertCalled(t, "Create", "xcrun", parameters, mock.Anything)
}
// Helpers
func createSimulatorAndMocks() (Manager, testingMocks) {
commandFactory := new(mockcommand.CommandFactory)
manager := NewManager(commandFactory)
return manager, testingMocks{
commandFactory: commandFactory,
}
}
func createCommand(output string) *mockcommand.Command {
command := new(mockcommand.Command)
command.On("PrintableCommandArgs").Return("")
command.On("Run").Return(nil)
command.On("RunAndReturnExitCode").Return(0, nil)
command.On("RunAndReturnTrimmedCombinedOutput").Return(output, nil)
return command
}
| mit |
cdnjs/cdnjs | ajax/libs/venn.js/0.2.11/venn.js | 65291 | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-selection'), require('d3-transition')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-selection', 'd3-transition'], factory) :
factory((global.venn = {}),global.d3,global.d3);
}(this, function (exports,d3Selection,d3Transition) { 'use strict';
/** finds the zeros of a function, given two starting points (which must
* have opposite signs */
function bisect(f, a, b, parameters) {
parameters = parameters || {};
var maxIterations = parameters.maxIterations || 100,
tolerance = parameters.tolerance || 1e-10,
fA = f(a),
fB = f(b),
delta = b - a;
if (fA * fB > 0) {
throw "Initial bisect points must have opposite signs";
}
if (fA === 0) return a;
if (fB === 0) return b;
for (var i = 0; i < maxIterations; ++i) {
delta /= 2;
var mid = a + delta,
fMid = f(mid);
if (fMid * fA >= 0) {
a = mid;
}
if ((Math.abs(delta) < tolerance) || (fMid === 0)) {
return mid;
}
}
return a + delta;
}
// need some basic operations on vectors, rather than adding a dependency,
// just define here
function zeros(x) { var r = new Array(x); for (var i = 0; i < x; ++i) { r[i] = 0; } return r; }
function zerosM(x,y) { return zeros(x).map(function() { return zeros(y); }); }
function dot(a, b) {
var ret = 0;
for (var i = 0; i < a.length; ++i) {
ret += a[i] * b[i];
}
return ret;
}
function norm2(a) {
return Math.sqrt(dot(a, a));
}
function multiplyBy(a, c) {
for (var i = 0; i < a.length; ++i) {
a[i] *= c;
}
}
function weightedSum(ret, w1, v1, w2, v2) {
for (var j = 0; j < ret.length; ++j) {
ret[j] = w1 * v1[j] + w2 * v2[j];
}
}
/** minimizes a function using the downhill simplex method */
function fmin(f, x0, parameters) {
parameters = parameters || {};
var maxIterations = parameters.maxIterations || x0.length * 200,
nonZeroDelta = parameters.nonZeroDelta || 1.1,
zeroDelta = parameters.zeroDelta || 0.001,
minErrorDelta = parameters.minErrorDelta || 1e-6,
minTolerance = parameters.minErrorDelta || 1e-5,
rho = parameters.rho || 1,
chi = parameters.chi || 2,
psi = parameters.psi || -0.5,
sigma = parameters.sigma || 0.5,
callback = parameters.callback,
maxDiff,
temp;
// initialize simplex.
var N = x0.length,
simplex = new Array(N + 1);
simplex[0] = x0;
simplex[0].fx = f(x0);
for (var i = 0; i < N; ++i) {
var point = x0.slice();
point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
simplex[i+1] = point;
simplex[i+1].fx = f(point);
}
var sortOrder = function(a, b) { return a.fx - b.fx; };
var centroid = x0.slice(),
reflected = x0.slice(),
contracted = x0.slice(),
expanded = x0.slice();
for (var iteration = 0; iteration < maxIterations; ++iteration) {
simplex.sort(sortOrder);
if (callback) {
callback(simplex);
}
maxDiff = 0;
for (i = 0; i < N; ++i) {
maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
}
if ((Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta) &&
(maxDiff < minTolerance)) {
break;
}
// compute the centroid of all but the worst point in the simplex
for (i = 0; i < N; ++i) {
centroid[i] = 0;
for (var j = 0; j < N; ++j) {
centroid[i] += simplex[j][i];
}
centroid[i] /= N;
}
// reflect the worst point past the centroid and compute loss at reflected
// point
var worst = simplex[N];
weightedSum(reflected, 1+rho, centroid, -rho, worst);
reflected.fx = f(reflected);
// if the reflected point is the best seen, then possibly expand
if (reflected.fx <= simplex[0].fx) {
weightedSum(expanded, 1+chi, centroid, -chi, worst);
expanded.fx = f(expanded);
if (expanded.fx < reflected.fx) {
temp = simplex[N];
simplex[N] = expanded;
expanded = temp;
} else {
temp = simplex[N];
simplex[N] = reflected;
reflected = temp;
}
}
// if the reflected point is worse than the second worst, we need to
// contract
else if (reflected.fx >= simplex[N-1].fx) {
var shouldReduce = false;
if (reflected.fx > worst.fx) {
// do an inside contraction
weightedSum(contracted, 1+psi, centroid, -psi, worst);
contracted.fx = f(contracted);
if (contracted.fx < worst.fx) {
temp = simplex[N];
simplex[N] = contracted;
contracted = temp;
} else {
shouldReduce = true;
}
} else {
// do an outside contraction
weightedSum(contracted, 1-psi * rho, centroid, psi*rho, worst);
contracted.fx = f(contracted);
if (contracted.fx <= reflected.fx) {
temp = simplex[N];
simplex[N] = contracted;
contracted = temp;
} else {
shouldReduce = true;
}
}
if (shouldReduce) {
// do reduction. doesn't actually happen that often
for (i = 1; i < simplex.length; ++i) {
weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
simplex[i].fx = f(simplex[i]);
}
}
} else {
temp = simplex[N];
simplex[N] = reflected;
reflected = temp;
}
}
simplex.sort(sortOrder);
return {f : simplex[0].fx,
solution : simplex[0]};
}
function minimizeConjugateGradient(f, initial, params) {
// allocate all memory up front here, keep out of the loop for perfomance
// reasons
var current = {x: initial.slice(), fx: 0, fxprime: initial.slice()},
next = {x: initial.slice(), fx: 0, fxprime: initial.slice()},
yk = initial.slice(),
pk, temp,
a = 1,
maxIterations;
params = params || {};
maxIterations = params.maxIterations || initial.length * 5;
current.fx = f(current.x, current.fxprime);
pk = current.fxprime.slice();
multiplyBy(pk, -1);
for (var i = 0; i < maxIterations; ++i) {
if (params.history) {
params.history.push({x: current.x.slice(),
fx: current.fx,
fxprime: current.fxprime.slice()});
}
a = wolfeLineSearch(f, pk, current, next, a);
if (!a) {
// faiiled to find point that satifies wolfe conditions.
// reset direction for next iteration
for (var j = 0; j < pk.length; ++j) {
pk[j] = -1 * current.fxprime[j];
}
} else {
// update direction using Polak–Ribiere CG method
weightedSum(yk, 1, next.fxprime, -1, current.fxprime);
var delta_k = dot(current.fxprime, current.fxprime),
beta_k = Math.max(0, dot(yk, next.fxprime) / delta_k);
weightedSum(pk, beta_k, pk, -1, next.fxprime);
temp = current;
current = next;
next = temp;
}
if (norm2(current.fxprime) <= 1e-5) {
break;
}
}
if (params.history) {
params.history.push({x: current.x.slice(),
fx: current.fx,
fxprime: current.fxprime.slice()});
}
return current;
}
var c1 = 1e-6;
var c2 = 0.1;
/// searches along line 'pk' for a point that satifies the wolfe conditions
/// See 'Numerical Optimization' by Nocedal and Wright p59-60
function wolfeLineSearch(f, pk, current, next, a) {
var phi0 = current.fx, phiPrime0 = dot(current.fxprime, pk),
phi = phi0, phi_old = phi0,
phiPrime = phiPrime0,
a0 = 0;
a = a || 1;
function zoom(a_lo, a_high, phi_lo) {
for (var iteration = 0; iteration < 16; ++iteration) {
a = (a_lo + a_high)/2;
weightedSum(next.x, 1.0, current.x, a, pk);
phi = next.fx = f(next.x, next.fxprime);
phiPrime = dot(next.fxprime, pk);
if ((phi > (phi0 + c1 * a * phiPrime0)) ||
(phi >= phi_lo)) {
a_high = a;
} else {
if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
return a;
}
if (phiPrime * (a_high - a_lo) >=0) {
a_high = a_lo;
}
a_lo = a;
phi_lo = phi;
}
}
return 0;
}
for (var iteration = 0; iteration < 10; ++iteration) {
weightedSum(next.x, 1.0, current.x, a, pk);
phi = next.fx = f(next.x, next.fxprime);
phiPrime = dot(next.fxprime, pk);
if ((phi > (phi0 + c1 * a * phiPrime0)) ||
(iteration && (phi >= phi_old))) {
return zoom(a0, a, phi_old);
}
if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
return a;
}
if (phiPrime >= 0 ) {
return zoom(a, a0, phi);
}
phi_old = phi;
a0 = a;
a *= 2;
}
return 0;
}
var SMALL = 1e-10;
/** Returns the intersection area of a bunch of circles (where each circle
is an object having an x,y and radius property) */
function intersectionArea(circles, stats) {
// get all the intersection points of the circles
var intersectionPoints = getIntersectionPoints(circles);
// filter out points that aren't included in all the circles
var innerPoints = intersectionPoints.filter(function (p) {
return containedInCircles(p, circles);
});
var arcArea = 0, polygonArea = 0, arcs = [], i;
// if we have intersection points that are within all the circles,
// then figure out the area contained by them
if (innerPoints.length > 1) {
// sort the points by angle from the center of the polygon, which lets
// us just iterate over points to get the edges
var center = getCenter(innerPoints);
for (i = 0; i < innerPoints.length; ++i ) {
var p = innerPoints[i];
p.angle = Math.atan2(p.x - center.x, p.y - center.y);
}
innerPoints.sort(function(a,b) { return b.angle - a.angle;});
// iterate over all points, get arc between the points
// and update the areas
var p2 = innerPoints[innerPoints.length - 1];
for (i = 0; i < innerPoints.length; ++i) {
var p1 = innerPoints[i];
// polygon area updates easily ...
polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
// updating the arc area is a little more involved
var midPoint = {x : (p1.x + p2.x) / 2,
y : (p1.y + p2.y) / 2},
arc = null;
for (var j = 0; j < p1.parentIndex.length; ++j) {
if (p2.parentIndex.indexOf(p1.parentIndex[j]) > -1) {
// figure out the angle halfway between the two points
// on the current circle
var circle = circles[p1.parentIndex[j]],
a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y),
a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
var angleDiff = (a2 - a1);
if (angleDiff < 0) {
angleDiff += 2*Math.PI;
}
// and use that angle to figure out the width of the
// arc
var a = a2 - angleDiff/2,
width = distance(midPoint, {
x : circle.x + circle.radius * Math.sin(a),
y : circle.y + circle.radius * Math.cos(a)
});
// pick the circle whose arc has the smallest width
if ((arc === null) || (arc.width > width)) {
arc = { circle : circle,
width : width,
p1 : p1,
p2 : p2};
}
}
}
if (arc !== null) {
arcs.push(arc);
arcArea += circleArea(arc.circle.radius, arc.width);
p2 = p1;
}
}
} else {
// no intersection points, is either disjoint - or is completely
// overlapped. figure out which by examining the smallest circle
var smallest = circles[0];
for (i = 1; i < circles.length; ++i) {
if (circles[i].radius < smallest.radius) {
smallest = circles[i];
}
}
// make sure the smallest circle is completely contained in all
// the other circles
var disjoint = false;
for (i = 0; i < circles.length; ++i) {
if (distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
disjoint = true;
break;
}
}
if (disjoint) {
arcArea = polygonArea = 0;
} else {
arcArea = smallest.radius * smallest.radius * Math.PI;
arcs.push({circle : smallest,
p1: { x: smallest.x, y : smallest.y + smallest.radius},
p2: { x: smallest.x - SMALL, y : smallest.y + smallest.radius},
width : smallest.radius * 2 });
}
}
polygonArea /= 2;
if (stats) {
stats.area = arcArea + polygonArea;
stats.arcArea = arcArea;
stats.polygonArea = polygonArea;
stats.arcs = arcs;
stats.innerPoints = innerPoints;
stats.intersectionPoints = intersectionPoints;
}
return arcArea + polygonArea;
}
/** returns whether a point is contained by all of a list of circles */
function containedInCircles(point, circles) {
for (var i = 0; i < circles.length; ++i) {
if (distance(point, circles[i]) > circles[i].radius + SMALL) {
return false;
}
}
return true;
}
/** Gets all intersection points between a bunch of circles */
function getIntersectionPoints(circles) {
var ret = [];
for (var i = 0; i < circles.length; ++i) {
for (var j = i + 1; j < circles.length; ++j) {
var intersect = circleCircleIntersection(circles[i],
circles[j]);
for (var k = 0; k < intersect.length; ++k) {
var p = intersect[k];
p.parentIndex = [i,j];
ret.push(p);
}
}
}
return ret;
}
function circleIntegral(r, x) {
var y = Math.sqrt(r * r - x * x);
return x * y + r * r * Math.atan2(x, y);
}
/** Returns the area of a circle of radius r - up to width */
function circleArea(r, width) {
return circleIntegral(r, width - r) - circleIntegral(r, -r);
}
/** euclidean distance between two points */
function distance(p1, p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) +
(p1.y - p2.y) * (p1.y - p2.y));
}
/** Returns the overlap area of two circles of radius r1 and r2 - that
have their centers separated by distance d. Simpler faster
circle intersection for only two circles */
function circleOverlap(r1, r2, d) {
// no overlap
if (d >= r1 + r2) {
return 0;
}
// completely overlapped
if (d <= Math.abs(r1 - r2)) {
return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
}
var w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d),
w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
return circleArea(r1, w1) + circleArea(r2, w2);
}
/** Given two circles (containing a x/y/radius attributes),
returns the intersecting points if possible.
note: doesn't handle cases where there are infinitely many
intersection points (circles are equivalent):, or only one intersection point*/
function circleCircleIntersection(p1, p2) {
var d = distance(p1, p2),
r1 = p1.radius,
r2 = p2.radius;
// if to far away, or self contained - can't be done
if ((d >= (r1 + r2)) || (d <= Math.abs(r1 - r2))) {
return [];
}
var a = (r1 * r1 - r2 * r2 + d * d) / (2 * d),
h = Math.sqrt(r1 * r1 - a * a),
x0 = p1.x + a * (p2.x - p1.x) / d,
y0 = p1.y + a * (p2.y - p1.y) / d,
rx = -(p2.y - p1.y) * (h / d),
ry = -(p2.x - p1.x) * (h / d);
return [{x: x0 + rx, y : y0 - ry },
{x: x0 - rx, y : y0 + ry }];
}
/** Returns the center of a bunch of points */
function getCenter(points) {
var center = {x: 0, y: 0};
for (var i =0; i < points.length; ++i ) {
center.x += points[i].x;
center.y += points[i].y;
}
center.x /= points.length;
center.y /= points.length;
return center;
}
/** given a list of set objects, and their corresponding overlaps.
updates the (x, y, radius) attribute on each set such that their positions
roughly correspond to the desired overlaps */
function venn(areas, parameters) {
parameters = parameters || {};
parameters.maxIterations = parameters.maxIterations || 500;
var initialLayout = parameters.initialLayout || bestInitialLayout;
// add in missing pairwise areas as having 0 size
areas = addMissingAreas(areas);
// initial layout is done greedily
var circles = initialLayout(areas);
// transform x/y coordinates to a vector to optimize
var initial = [], setids = [], setid;
for (setid in circles) {
if (circles.hasOwnProperty(setid)) {
initial.push(circles[setid].x);
initial.push(circles[setid].y);
setids.push(setid);
}
}
// optimize initial layout from our loss function
var totalFunctionCalls = 0;
var solution = fmin(
function(values) {
totalFunctionCalls += 1;
var current = {};
for (var i = 0; i < setids.length; ++i) {
var setid = setids[i];
current[setid] = {x: values[2 * i],
y: values[2 * i + 1],
radius : circles[setid].radius,
// size : circles[setid].size
};
}
return lossFunction(current, areas);
},
initial,
parameters);
// transform solution vector back to x/y points
var positions = solution.solution;
for (var i = 0; i < setids.length; ++i) {
setid = setids[i];
circles[setid].x = positions[2 * i];
circles[setid].y = positions[2 * i + 1];
}
return circles;
}
var SMALL$1 = 1e-10;
/** Returns the distance necessary for two circles of radius r1 + r2 to
have the overlap area 'overlap' */
function distanceFromIntersectArea(r1, r2, overlap) {
// handle complete overlapped circles
if (Math.min(r1, r2) * Math.min(r1,r2) * Math.PI <= overlap + SMALL$1) {
return Math.abs(r1 - r2);
}
return bisect(function(distance) {
return circleOverlap(r1, r2, distance) - overlap;
}, 0, r1 + r2);
}
/** Missing pair-wise intersection area data can cause problems:
treating as an unknown means that sets will be laid out overlapping,
which isn't what people expect. To reflect that we want disjoint sets
here, set the overlap to 0 for all missing pairwise set intersections */
function addMissingAreas(areas) {
areas = areas.slice();
// two circle intersections that aren't defined
var ids = [], pairs = {}, i, j, a, b;
for (i = 0; i < areas.length; ++i) {
var area = areas[i];
if (area.sets.length == 1) {
ids.push(area.sets[0]);
} else if (area.sets.length == 2) {
a = area.sets[0];
b = area.sets[1];
pairs[[a, b]] = true;
pairs[[b, a]] = true;
}
}
ids.sort(function(a, b) { return a > b; });
for (i = 0; i < ids.length; ++i) {
a = ids[i];
for (j = i + 1; j < ids.length; ++j) {
b = ids[j];
if (!([a, b] in pairs)) {
areas.push({'sets': [a, b],
'size': 0});
}
}
}
return areas;
}
/// Returns two matrices, one of the euclidean distances between the sets
/// and the other indicating if there are subset or disjoint set relationships
function getDistanceMatrices(areas, sets, setids) {
// initialize an empty distance matrix between all the points
var distances = zerosM(sets.length, sets.length),
constraints = zerosM(sets.length, sets.length);
// compute required distances between all the sets such that
// the areas match
areas.filter(function(x) { return x.sets.length == 2; })
.map(function(current) {
var left = setids[current.sets[0]],
right = setids[current.sets[1]],
r1 = Math.sqrt(sets[left].size / Math.PI),
r2 = Math.sqrt(sets[right].size / Math.PI),
distance = distanceFromIntersectArea(r1, r2, current.size);
distances[left][right] = distances[right][left] = distance;
// also update constraints to indicate if its a subset or disjoint
// relationship
var c = 0;
if (current.size + 1e-10 >= Math.min(sets[left].size,
sets[right].size)) {
c = 1;
} else if (current.size <= 1e-10) {
c = -1;
}
constraints[left][right] = constraints[right][left] = c;
});
return {distances: distances, constraints: constraints};
}
/// computes the gradient and loss simulatenously for our constrained MDS optimizer
function constrainedMDSGradient(x, fxprime, distances, constraints) {
var loss = 0, i;
for (i = 0; i < fxprime.length; ++i) {
fxprime[i] = 0;
}
for (i = 0; i < distances.length; ++i) {
var xi = x[2 * i], yi = x[2 * i + 1];
for (var j = i + 1; j < distances.length; ++j) {
var xj = x[2 * j], yj = x[2 * j + 1],
dij = distances[i][j],
constraint = constraints[i][j];
var squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi),
distance = Math.sqrt(squaredDistance),
delta = squaredDistance - dij * dij;
if (((constraint > 0) && (distance <= dij)) ||
((constraint < 0) && (distance >= dij))) {
continue;
}
loss += 2 * delta * delta;
fxprime[2*i] += 4 * delta * (xi - xj);
fxprime[2*i + 1] += 4 * delta * (yi - yj);
fxprime[2*j] += 4 * delta * (xj - xi);
fxprime[2*j + 1] += 4 * delta * (yj - yi);
}
}
return loss;
}
/// takes the best working variant of either constrained MDS or greedy
function bestInitialLayout(areas, params) {
var initial = greedyLayout(areas, params);
// greedylayout is sufficient for all 2/3 circle cases. try out
// constrained MDS for higher order problems, take its output
// if it outperforms. (greedy is aesthetically better on 2/3 circles
// since it axis aligns)
if (areas.length >= 8) {
var constrained = constrainedMDSLayout(areas, params),
constrainedLoss = lossFunction(constrained, areas),
greedyLoss = lossFunction(initial, areas);
if (constrainedLoss + 1e-8 < greedyLoss) {
initial = constrained;
}
}
return initial;
}
/// use the constrained MDS variant to generate an initial layout
function constrainedMDSLayout(areas, params) {
params = params || {};
var restarts = params.restarts || 10;
// bidirectionally map sets to a rowid (so we can create a matrix)
var sets = [], setids = {}, i;
for (i = 0; i < areas.length; ++i ) {
var area = areas[i];
if (area.sets.length == 1) {
setids[area.sets[0]] = sets.length;
sets.push(area);
}
}
var matrices = getDistanceMatrices(areas, sets, setids),
distances = matrices.distances,
constraints = matrices.constraints;
// keep distances bounded, things get messed up otherwise.
// TODO: proper preconditioner?
var norm = norm2(distances.map(norm2))/(distances.length);
distances = distances.map(function (row) {
return row.map(function (value) { return value / norm; });});
var obj = function(x, fxprime) {
return constrainedMDSGradient(x, fxprime, distances, constraints);
};
var best, current;
for (i = 0; i < restarts; ++i) {
var initial = zeros(distances.length*2).map(Math.random);
current = minimizeConjugateGradient(obj, initial, params);
if (!best || (current.fx < best.fx)) {
best = current;
}
}
var positions = best.x;
// translate rows back to (x,y,radius) coordinates
var circles = {};
for (i = 0; i < sets.length; ++i) {
var set = sets[i];
circles[set.sets[0]] = {
x: positions[2*i] * norm,
y: positions[2*i + 1] * norm,
radius: Math.sqrt(set.size / Math.PI)
};
}
if (params.history) {
for (i = 0; i < params.history.length; ++i) {
multiplyBy(params.history[i].x, norm);
}
}
return circles;
}
/** Lays out a Venn diagram greedily, going from most overlapped sets to
least overlapped, attempting to position each new set such that the
overlapping areas to already positioned sets are basically right */
function greedyLayout(areas) {
// define a circle for each set
var circles = {}, setOverlaps = {}, set;
for (var i = 0; i < areas.length; ++i) {
var area = areas[i];
if (area.sets.length == 1) {
set = area.sets[0];
circles[set] = {x: 1e10, y: 1e10,
rowid: circles.length,
size: area.size,
radius: Math.sqrt(area.size / Math.PI)};
setOverlaps[set] = [];
}
}
areas = areas.filter(function(a) { return a.sets.length == 2; });
// map each set to a list of all the other sets that overlap it
for (i = 0; i < areas.length; ++i) {
var current = areas[i];
var weight = current.hasOwnProperty('weight') ? current.weight : 1.0;
var left = current.sets[0], right = current.sets[1];
// completely overlapped circles shouldn't be positioned early here
if (current.size + SMALL$1 >= Math.min(circles[left].size,
circles[right].size)) {
weight = 0;
}
setOverlaps[left].push ({set:right, size:current.size, weight:weight});
setOverlaps[right].push({set:left, size:current.size, weight:weight});
}
// get list of most overlapped sets
var mostOverlapped = [];
for (set in setOverlaps) {
if (setOverlaps.hasOwnProperty(set)) {
var size = 0;
for (i = 0; i < setOverlaps[set].length; ++i) {
size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
}
mostOverlapped.push({set: set, size:size});
}
}
// sort by size desc
function sortOrder(a,b) {
return b.size - a.size;
}
mostOverlapped.sort(sortOrder);
// keep track of what sets have been laid out
var positioned = {};
function isPositioned(element) {
return element.set in positioned;
}
// adds a point to the output
function positionSet(point, index) {
circles[index].x = point.x;
circles[index].y = point.y;
positioned[index] = true;
}
// add most overlapped set at (0,0)
positionSet({x: 0, y: 0}, mostOverlapped[0].set);
// get distances between all points. TODO, necessary?
// answer: probably not
// var distances = venn.getDistanceMatrices(circles, areas).distances;
for (i = 1; i < mostOverlapped.length; ++i) {
var setIndex = mostOverlapped[i].set,
overlap = setOverlaps[setIndex].filter(isPositioned);
set = circles[setIndex];
overlap.sort(sortOrder);
if (overlap.length === 0) {
// this shouldn't happen anymore with addMissingAreas
throw "ERROR: missing pairwise overlap information";
}
var points = [];
for (var j = 0; j < overlap.length; ++j) {
// get appropriate distance from most overlapped already added set
var p1 = circles[overlap[j].set],
d1 = distanceFromIntersectArea(set.radius, p1.radius,
overlap[j].size);
// sample positions at 90 degrees for maximum aesthetics
points.push({x : p1.x + d1, y : p1.y});
points.push({x : p1.x - d1, y : p1.y});
points.push({y : p1.y + d1, x : p1.x});
points.push({y : p1.y - d1, x : p1.x});
// if we have at least 2 overlaps, then figure out where the
// set should be positioned analytically and try those too
for (var k = j + 1; k < overlap.length; ++k) {
var p2 = circles[overlap[k].set],
d2 = distanceFromIntersectArea(set.radius, p2.radius,
overlap[k].size);
var extraPoints = circleCircleIntersection(
{ x: p1.x, y: p1.y, radius: d1},
{ x: p2.x, y: p2.y, radius: d2});
for (var l = 0; l < extraPoints.length; ++l) {
points.push(extraPoints[l]);
}
}
}
// we have some candidate positions for the set, examine loss
// at each position to figure out where to put it at
var bestLoss = 1e50, bestPoint = points[0];
for (j = 0; j < points.length; ++j) {
circles[setIndex].x = points[j].x;
circles[setIndex].y = points[j].y;
var loss = lossFunction(circles, areas);
if (loss < bestLoss) {
bestLoss = loss;
bestPoint = points[j];
}
}
positionSet(bestPoint, setIndex);
}
return circles;
}
/** Given a bunch of sets, and the desired overlaps between these sets - computes
the distance from the actual overlaps to the desired overlaps. Note that
this method ignores overlaps of more than 2 circles */
function lossFunction(sets, overlaps) {
var output = 0;
function getCircles(indices) {
return indices.map(function(i) { return sets[i]; });
}
for (var i = 0; i < overlaps.length; ++i) {
var area = overlaps[i], overlap;
if (area.sets.length == 1) {
continue;
} else if (area.sets.length == 2) {
var left = sets[area.sets[0]],
right = sets[area.sets[1]];
overlap = circleOverlap(left.radius, right.radius,
distance(left, right));
} else {
overlap = intersectionArea(getCircles(area.sets));
}
var weight = area.hasOwnProperty('weight') ? area.weight : 1.0;
output += weight * (overlap - area.size) * (overlap - area.size);
}
return output;
}
// orientates a bunch of circles to point in orientation
function orientateCircles(circles, orientation, orientationOrder) {
if (orientationOrder === null) {
circles.sort(function (a, b) { return b.radius - a.radius; });
} else {
circles.sort(orientationOrder);
}
var i;
// shift circles so largest circle is at (0, 0)
if (circles.length > 0) {
var largestX = circles[0].x,
largestY = circles[0].y;
for (i = 0; i < circles.length; ++i) {
circles[i].x -= largestX;
circles[i].y -= largestY;
}
}
// rotate circles so that second largest is at an angle of 'orientation'
// from largest
if (circles.length > 1) {
var rotation = Math.atan2(circles[1].x, circles[1].y) - orientation,
c = Math.cos(rotation),
s = Math.sin(rotation), x, y;
for (i = 0; i < circles.length; ++i) {
x = circles[i].x;
y = circles[i].y;
circles[i].x = c * x - s * y;
circles[i].y = s * x + c * y;
}
}
// mirror solution if third solution is above plane specified by
// first two circles
if (circles.length > 2) {
var angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
while (angle < 0) { angle += 2* Math.PI; }
while (angle > 2*Math.PI) { angle -= 2* Math.PI; }
if (angle > Math.PI) {
var slope = circles[1].y / (1e-10 + circles[1].x);
for (i = 0; i < circles.length; ++i) {
var d = (circles[i].x + slope * circles[i].y) / (1 + slope*slope);
circles[i].x = 2 * d - circles[i].x;
circles[i].y = 2 * d * slope - circles[i].y;
}
}
}
}
function disjointCluster(circles) {
// union-find clustering to get disjoint sets
circles.map(function(circle) { circle.parent = circle; });
// path compression step in union find
function find(circle) {
if (circle.parent !== circle) {
circle.parent = find(circle.parent);
}
return circle.parent;
}
function union(x, y) {
var xRoot = find(x), yRoot = find(y);
xRoot.parent = yRoot;
}
// get the union of all overlapping sets
for (var i = 0; i < circles.length; ++i) {
for (var j = i + 1; j < circles.length; ++j) {
var maxDistance = circles[i].radius + circles[j].radius;
if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
union(circles[j], circles[i]);
}
}
}
// find all the disjoint clusters and group them together
var disjointClusters = {}, setid;
for (i = 0; i < circles.length; ++i) {
setid = find(circles[i]).parent.setid;
if (!(setid in disjointClusters)) {
disjointClusters[setid] = [];
}
disjointClusters[setid].push(circles[i]);
}
// cleanup bookkeeping
circles.map(function(circle) { delete circle.parent; });
// return in more usable form
var ret = [];
for (setid in disjointClusters) {
if (disjointClusters.hasOwnProperty(setid)) {
ret.push(disjointClusters[setid]);
}
}
return ret;
}
function getBoundingBox(circles) {
var minMax = function(d) {
var hi = Math.max.apply(null, circles.map(
function(c) { return c[d] + c.radius; } )),
lo = Math.min.apply(null, circles.map(
function(c) { return c[d] - c.radius;} ));
return {max:hi, min:lo};
};
return {xRange: minMax('x'), yRange: minMax('y')};
}
function normalizeSolution(solution, orientation, orientationOrder) {
if (orientation === null){
orientation = Math.PI/2;
}
// work with a list instead of a dictionary, and take a copy so we
// don't mutate input
var circles = [], i, setid;
for (setid in solution) {
if (solution.hasOwnProperty(setid)) {
var previous = solution[setid];
circles.push({x: previous.x,
y: previous.y,
radius: previous.radius,
setid: setid});
}
}
// get all the disjoint clusters
var clusters = disjointCluster(circles);
// orientate all disjoint sets, get sizes
for (i = 0; i < clusters.length; ++i) {
orientateCircles(clusters[i], orientation, orientationOrder);
var bounds = getBoundingBox(clusters[i]);
clusters[i].size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
clusters[i].bounds = bounds;
}
clusters.sort(function(a, b) { return b.size - a.size; });
// orientate the largest at 0,0, and get the bounds
circles = clusters[0];
var returnBounds = circles.bounds;
var spacing = (returnBounds.xRange.max - returnBounds.xRange.min)/50;
function addCluster(cluster, right, bottom) {
if (!cluster) return;
var bounds = cluster.bounds, xOffset, yOffset, centreing;
if (right) {
xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing;
} else {
xOffset = returnBounds.xRange.max - bounds.xRange.max;
centreing = (bounds.xRange.max - bounds.xRange.min) / 2 -
(returnBounds.xRange.max - returnBounds.xRange.min) / 2;
if (centreing < 0) xOffset += centreing;
}
if (bottom) {
yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing;
} else {
yOffset = returnBounds.yRange.max - bounds.yRange.max;
centreing = (bounds.yRange.max - bounds.yRange.min) / 2 -
(returnBounds.yRange.max - returnBounds.yRange.min) / 2;
if (centreing < 0) yOffset += centreing;
}
for (var j = 0; j < cluster.length; ++j) {
cluster[j].x += xOffset;
cluster[j].y += yOffset;
circles.push(cluster[j]);
}
}
var index = 1;
while (index < clusters.length) {
addCluster(clusters[index], true, false);
addCluster(clusters[index+1], false, true);
addCluster(clusters[index+2], true, true);
index += 3;
// have one cluster (in top left). lay out next three relative
// to it in a grid
returnBounds = getBoundingBox(circles);
}
// convert back to solution form
var ret = {};
for (i = 0; i < circles.length; ++i) {
ret[circles[i].setid] = circles[i];
}
return ret;
}
/** Scales a solution from venn.venn or venn.greedyLayout such that it fits in
a rectangle of width/height - with padding around the borders. also
centers the diagram in the available space at the same time */
function scaleSolution(solution, width, height, padding) {
var circles = [], setids = [];
for (var setid in solution) {
if (solution.hasOwnProperty(setid)) {
setids.push(setid);
circles.push(solution[setid]);
}
}
width -= 2*padding;
height -= 2*padding;
var bounds = getBoundingBox(circles),
xRange = bounds.xRange,
yRange = bounds.yRange,
xScaling = width / (xRange.max - xRange.min),
yScaling = height / (yRange.max - yRange.min),
scaling = Math.min(yScaling, xScaling),
// while we're at it, center the diagram too
xOffset = (width - (xRange.max - xRange.min) * scaling) / 2,
yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
var scaled = {};
for (var i = 0; i < circles.length; ++i) {
var circle = circles[i];
scaled[setids[i]] = {
radius: scaling * circle.radius,
x: padding + xOffset + (circle.x - xRange.min) * scaling,
y: padding + yOffset + (circle.y - yRange.min) * scaling,
};
}
return scaled;
}
/*global console:true*/
function VennDiagram() {
var width = 600,
height = 350,
padding = 15,
duration = 1000,
orientation = Math.PI / 2,
normalize = true,
wrap = true,
styled = true,
fontSize = null,
orientationOrder = null,
// mimic the behaviour of d3.scale.category10 from the previous
// version of d3
colourMap = {},
// so this is the same as d3.schemeCategory10, which is only defined in d3 4.0
// since we can support older versions of d3 as long as we don't force this,
// I'm hackily redefining below. TODO: remove this and change to d3.schemeCategory10
colourScheme = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"],
colourIndex = 0,
colours = function(key) {
if (key in colourMap) {
return colourMap[key];
}
var ret = colourMap[key] = colourScheme[colourIndex];
colourIndex += 1;
if (colourIndex >= colourScheme.length) {
colourIndex = 0;
}
return ret;
},
layoutFunction = venn;
function chart(selection) {
var data = selection.datum();
var solution = layoutFunction(data);
if (normalize) {
solution = normalizeSolution(solution,
orientation,
orientationOrder);
}
var circles = scaleSolution(solution, width, height, padding);
var textCentres = computeTextCentres(circles, data);
// create svg if not already existing
selection.selectAll("svg").data([circles]).enter().append("svg");
var svg = selection.select("svg")
.attr("width", width)
.attr("height", height);
// to properly transition intersection areas, we need the
// previous circles locations. load from elements
var previous = {}, hasPrevious = false;
svg.selectAll("g path").each(function (d) {
var path = d3Selection.select(this).attr("d");
if ((d.sets.length == 1) && path) {
hasPrevious = true;
previous[d.sets[0]] = circleFromPath(path);
}
});
// interpolate intersection area paths between previous and
// current paths
var pathTween = function(d) {
return function(t) {
var c = d.sets.map(function(set) {
var start = previous[set], end = circles[set];
if (!start) {
start = {x : width/2, y : height/2, radius : 1};
}
if (!end) {
end = {x : width/2, y : height/2, radius : 1};
}
return {'x' : start.x * (1 - t) + end.x * t,
'y' : start.y * (1 - t) + end.y * t,
'radius' : start.radius * (1 - t) + end.radius * t};
});
return intersectionAreaPath(c);
};
};
// update data, joining on the set ids
var nodes = svg.selectAll("g")
.data(data, function(d) { return d.sets; });
// create new nodes
var enter = nodes.enter()
.append('g')
.attr("class", function(d) {
return "venn-area venn-" +
(d.sets.length == 1 ? "circle" : "intersection");
})
.attr("data-venn-sets", function(d) {
return d.sets.join("_");
});
var enterPath = enter.append("path"),
enterText = enter.append("text")
.attr("class", "label")
.text(function (d) { return label(d); } )
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.attr("x", width/2)
.attr("y", height/2);
// apply minimal style if wanted
if (styled) {
enterPath.style("fill-opacity", "0")
.filter(function (d) { return d.sets.length == 1; } )
.style("fill", function(d) { return colours(label(d)); })
.style("fill-opacity", ".25");
enterText
.style("fill", function(d) { return d.sets.length == 1 ? colours(label(d)) : "#444"; });
}
// update existing, using pathTween if necessary
var update = selection;
if (hasPrevious) {
update = selection.transition("venn").duration(duration);
update.selectAll("path")
.attrTween("d", pathTween);
} else {
update.selectAll("path")
.attr("d", function(d) {
return intersectionAreaPath(d.sets.map(function (set) { return circles[set]; }));
});
}
var updateText = update.selectAll("text")
.filter(function (d) { return d.sets in textCentres; })
.text(function (d) { return label(d); } )
.attr("x", function(d) { return Math.floor(textCentres[d.sets].x);})
.attr("y", function(d) { return Math.floor(textCentres[d.sets].y);});
if (wrap) {
if (hasPrevious) {
updateText.on("end", wrapText(circles, label));
} else {
updateText.each(wrapText(circles, label));
}
}
// remove old
var exit = nodes.exit().transition('venn').duration(duration).remove();
exit.selectAll("path")
.attrTween("d", pathTween);
var exitText = exit.selectAll("text")
.attr("x", width/2)
.attr("y", height/2);
// if we've been passed a fontSize explicitly, use it to
// transition
if (fontSize !== null) {
enterText.style("font-size", "0px");
updateText.style("font-size", fontSize);
exitText.style("font-size", "0px");
}
return {'circles': circles,
'textCentres': textCentres,
'nodes': nodes,
'enter': enter,
'update': update,
'exit': exit};
}
function label(d) {
if (d.label) {
return d.label;
}
if (d.sets.length == 1) {
return '' + d.sets[0];
}
}
chart.wrap = function(_) {
if (!arguments.length) return wrap;
wrap = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.padding = function(_) {
if (!arguments.length) return padding;
padding = _;
return chart;
};
chart.colours = function(_) {
if (!arguments.length) return colours;
colours = _;
return chart;
};
chart.fontSize = function(_) {
if (!arguments.length) return fontSize;
fontSize = _;
return chart;
};
chart.duration = function(_) {
if (!arguments.length) return duration;
duration = _;
return chart;
};
chart.layoutFunction = function(_) {
if (!arguments.length) return layoutFunction;
layoutFunction = _;
return chart;
};
chart.normalize = function(_) {
if (!arguments.length) return normalize;
normalize = _;
return chart;
};
chart.styled = function(_) {
if (!arguments.length) return styled;
styled = _;
return chart;
};
chart.orientation = function(_) {
if (!arguments.length) return orientation;
orientation = _;
return chart;
};
chart.orientationOrder = function(_) {
if (!arguments.length) return orientationOrder;
orientationOrder = _;
return chart;
};
return chart;
}
// sometimes text doesn't fit inside the circle, if thats the case lets wrap
// the text here such that it fits
// todo: looks like this might be merged into d3 (
// https://github.com/mbostock/d3/issues/1642),
// also worth checking out is
// http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
// this seems to be one of those things that should be easy but isn't
function wrapText(circles, labeller) {
return function() {
var text = d3Selection.select(this),
data = text.datum(),
width = circles[data.sets[0]].radius || 50,
label = labeller(data) || '';
var words = label.split(/\s+/).reverse(),
maxLines = 3,
minChars = (label.length + words.length) / maxLines,
word = words.pop(),
line = [word],
joined,
lineNumber = 0,
lineHeight = 1.1, // ems
tspan = text.text(null).append("tspan").text(word);
while (true) {
word = words.pop();
if (!word) break;
line.push(word);
joined = line.join(" ");
tspan.text(joined);
if (joined.length > minChars && tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").text(word);
lineNumber++;
}
}
var initial = 0.35 - lineNumber * lineHeight / 2,
x = text.attr("x"),
y = text.attr("y");
text.selectAll("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", function(d, i) {
return (initial + i * lineHeight) + "em";
});
};
}
function circleMargin(current, interior, exterior) {
var margin = interior[0].radius - distance(interior[0], current), i, m;
for (i = 1; i < interior.length; ++i) {
m = interior[i].radius - distance(interior[i], current);
if (m <= margin) {
margin = m;
}
}
for (i = 0; i < exterior.length; ++i) {
m = distance(exterior[i], current) - exterior[i].radius;
if (m <= margin) {
margin = m;
}
}
return margin;
}
// compute the center of some circles by maximizing the margin of
// the center point relative to the circles (interior) after subtracting
// nearby circles (exterior)
function computeTextCentre(interior, exterior) {
// get an initial estimate by sampling around the interior circles
// and taking the point with the biggest margin
var points = [], i;
for (i = 0; i < interior.length; ++i) {
var c = interior[i];
points.push({x: c.x, y: c.y});
points.push({x: c.x + c.radius/2, y: c.y});
points.push({x: c.x - c.radius/2, y: c.y});
points.push({x: c.x, y: c.y + c.radius/2});
points.push({x: c.x, y: c.y - c.radius/2});
}
var initial = points[0], margin = circleMargin(points[0], interior, exterior);
for (i = 1; i < points.length; ++i) {
var m = circleMargin(points[i], interior, exterior);
if (m >= margin) {
initial = points[i];
margin = m;
}
}
// maximize the margin numerically
var solution = fmin(
function(p) { return -1 * circleMargin({x: p[0], y: p[1]}, interior, exterior); },
[initial.x, initial.y],
{maxIterations:500, minErrorDelta:1e-10}).solution;
var ret = {x: solution[0], y: solution[1]};
// check solution, fallback as needed (happens if fully overlapped
// etc)
var valid = true;
for (i = 0; i < interior.length; ++i) {
if (distance(ret, interior[i]) > interior[i].radius) {
valid = false;
break;
}
}
for (i = 0; i < exterior.length; ++i) {
if (distance(ret, exterior[i]) < exterior[i].radius) {
valid = false;
break;
}
}
if (!valid) {
if (interior.length == 1) {
ret = {x: interior[0].x, y: interior[0].y};
} else {
var areaStats = {};
intersectionArea(interior, areaStats);
if (areaStats.arcs.length === 0) {
ret = {'x': 0, 'y': -1000, disjoint:true};
} else if (areaStats.arcs.length == 1) {
ret = {'x': areaStats.arcs[0].circle.x,
'y': areaStats.arcs[0].circle.y};
} else if (exterior.length) {
// try again without other circles
ret = computeTextCentre(interior, []);
} else {
// take average of all the points in the intersection
// polygon. this should basically never happen
// and has some issues:
// https://github.com/benfred/venn.js/issues/48#issuecomment-146069777
ret = getCenter(areaStats.arcs.map(function (a) { return a.p1; }));
}
}
}
return ret;
}
// given a dictionary of {setid : circle}, returns
// a dictionary of setid to list of circles that completely overlap it
function getOverlappingCircles(circles) {
var ret = {}, circleids = [];
for (var circleid in circles) {
circleids.push(circleid);
ret[circleid] = [];
}
for (var i = 0; i < circleids.length; i++) {
var a = circles[circleids[i]];
for (var j = i + 1; j < circleids.length; ++j) {
var b = circles[circleids[j]],
d = distance(a, b);
if (d + b.radius <= a.radius + 1e-10) {
ret[circleids[j]].push(circleids[i]);
} else if (d + a.radius <= b.radius + 1e-10) {
ret[circleids[i]].push(circleids[j]);
}
}
}
return ret;
}
function computeTextCentres(circles, areas) {
var ret = {}, overlapped = getOverlappingCircles(circles);
for (var i = 0; i < areas.length; ++i) {
var area = areas[i].sets, areaids = {}, exclude = {};
for (var j = 0; j < area.length; ++j) {
areaids[area[j]] = true;
var overlaps = overlapped[area[j]];
// keep track of any circles that overlap this area,
// and don't consider for purposes of computing the text
// centre
for (var k = 0; k < overlaps.length; ++k) {
exclude[overlaps[k]] = true;
}
}
var interior = [], exterior = [];
for (var setid in circles) {
if (setid in areaids) {
interior.push(circles[setid]);
} else if (!(setid in exclude)) {
exterior.push(circles[setid]);
}
}
var centre = computeTextCentre(interior, exterior);
ret[area] = centre;
if (centre.disjoint && (areas[i].size > 0)) {
console.log("WARNING: area " + area + " not represented on screen");
}
}
return ret;
}
// sorts all areas in the venn diagram, so that
// a particular area is on top (relativeTo) - and
// all other areas are so that the smallest areas are on top
function sortAreas(div, relativeTo) {
// figure out sets that are completly overlapped by relativeTo
var overlaps = getOverlappingCircles(div.selectAll("svg").datum());
var exclude = {};
for (var i = 0; i < relativeTo.sets.length; ++i) {
var check = relativeTo.sets[i];
for (var setid in overlaps) {
var overlap = overlaps[setid];
for (var j = 0; j < overlap.length; ++j) {
if (overlap[j] == check) {
exclude[setid] = true;
break;
}
}
}
}
// checks that all sets are in exclude;
function shouldExclude(sets) {
for (var i = 0; i < sets.length; ++i) {
if (!(sets[i] in exclude)) {
return false;
}
}
return true;
}
// need to sort div's so that Z order is correct
div.selectAll("g").sort(function (a, b) {
// highest order set intersections first
if (a.sets.length != b.sets.length) {
return a.sets.length - b.sets.length;
}
if (a == relativeTo) {
return shouldExclude(b.sets) ? -1 : 1;
}
if (b == relativeTo) {
return shouldExclude(a.sets) ? 1 : -1;
}
// finally by size
return b.size - a.size;
});
}
function circlePath(x, y, r) {
var ret = [];
ret.push("\nM", x, y);
ret.push("\nm", -r, 0);
ret.push("\na", r, r, 0, 1, 0, r *2, 0);
ret.push("\na", r, r, 0, 1, 0,-r *2, 0);
return ret.join(" ");
}
// inverse of the circlePath function, returns a circle object from an svg path
function circleFromPath(path) {
var tokens = path.split(' ');
return {'x' : parseFloat(tokens[1]),
'y' : parseFloat(tokens[2]),
'radius' : -parseFloat(tokens[4])
};
}
/** returns a svg path of the intersection area of a bunch of circles */
function intersectionAreaPath(circles) {
var stats = {};
intersectionArea(circles, stats);
var arcs = stats.arcs;
if (arcs.length === 0) {
return "M 0 0";
} else if (arcs.length == 1) {
var circle = arcs[0].circle;
return circlePath(circle.x, circle.y, circle.radius);
} else {
// draw path around arcs
var ret = ["\nM", arcs[0].p2.x, arcs[0].p2.y];
for (var i = 0; i < arcs.length; ++i) {
var arc = arcs[i], r = arc.circle.radius, wide = arc.width > r;
ret.push("\nA", r, r, 0, wide ? 1 : 0, 1,
arc.p1.x, arc.p1.y);
}
return ret.join(" ");
}
}
exports.fmin = fmin;
exports.minimizeConjugateGradient = minimizeConjugateGradient;
exports.bisect = bisect;
exports.intersectionArea = intersectionArea;
exports.circleCircleIntersection = circleCircleIntersection;
exports.circleOverlap = circleOverlap;
exports.circleArea = circleArea;
exports.distance = distance;
exports.circleIntegral = circleIntegral;
exports.venn = venn;
exports.greedyLayout = greedyLayout;
exports.scaleSolution = scaleSolution;
exports.normalizeSolution = normalizeSolution;
exports.bestInitialLayout = bestInitialLayout;
exports.lossFunction = lossFunction;
exports.disjointCluster = disjointCluster;
exports.distanceFromIntersectArea = distanceFromIntersectArea;
exports.VennDiagram = VennDiagram;
exports.wrapText = wrapText;
exports.computeTextCentres = computeTextCentres;
exports.computeTextCentre = computeTextCentre;
exports.sortAreas = sortAreas;
exports.circlePath = circlePath;
exports.circleFromPath = circleFromPath;
exports.intersectionAreaPath = intersectionAreaPath;
})); | mit |
mrloop/elgincc_engine | test/dummy/config/routes.rb | 89 | Rails.application.routes.draw do
mount ElginccEngine::Engine => "/elgincc_engine"
end
| mit |
StefftheEmperor/3rei | Request/Classes/Rewrite/Params.php | 161 | <?php
/**
* Created by PhpStorm.
* User: stefan
* Date: 31.07.16
* Time: 14:45
*/
namespace Request\Classes\Rewrite;
class Params extends Attributes
{
} | mit |
laurentkempe/HipChatConnect | src/HipChatConnect/Controllers/Listeners/TeamCity/HipChatActivityCardData.cs | 2817 | using System;
namespace HipChatConnect.Controllers.Listeners.TeamCity
{
public class HipChatActivityCardData
{
public HipChatActivityCardData()
{
Id = Guid.NewGuid().ToString();
}
private string Id { get; }
public string ActivityIconUrl { get; set; }
public string ActivityHtml { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public string IconUrl { get; set; }
public string Json => $@"
{{
""style"": ""application"",
""url"": ""{Url}"",
""id"": ""{Id}"",
""title"": ""{Title}"",
""description"": ""{Description}"",
""icon"": {{
""url"": ""{IconUrl}""
}},
""attributes"": [
],
""activity"": {{
""icon"": ""{ActivityIconUrl}"",
""html"": ""{ActivityHtml}""
}}
}}";
}
public class TeamCityHipChatActivityCardData : HipChatActivityCardData
{
public TeamCityHipChatActivityCardData(string baseUrl)
{
IconUrl = $"{baseUrl}/nubot/TC_activity.png";
}
}
public class SuccessfulTeamCityHipChatBuildActivityCardData : TeamCityHipChatActivityCardData
{
public SuccessfulTeamCityHipChatBuildActivityCardData(string baseUrl) : base(baseUrl)
{
ActivityIconUrl = $"{baseUrl}/nubot/TC_activity_success.png";
}
}
public class FailedTeamCityHipChatBuildActivityCardData : TeamCityHipChatActivityCardData
{
public FailedTeamCityHipChatBuildActivityCardData(string baseUrl) : base(baseUrl)
{
ActivityIconUrl = $"{baseUrl}/nubot/TC_activity_failure.png";
}
}
public class TeamsActivityCardData
{
public string Title { get; set; }
public string Text { get; set; }
public string Color { get; set; }
public string Json => $@"
{{
""title"": ""{Title}"",
""text"": ""{Text}"",
""themeColor"": ""{Color}""
}}";
}
public class SuccessfulTeamsActivityCardData : TeamsActivityCardData
{
public SuccessfulTeamsActivityCardData()
{
Color = "00FF00";
}
}
public class FailedTeamsActivityCardData : TeamsActivityCardData
{
public FailedTeamsActivityCardData()
{
Color = "FF0000";
}
}
public class GithubPushActivityCardData : TeamsActivityCardData
{
public GithubPushActivityCardData()
{
}
}
} | mit |
adamshaylor/complex-spa-architectures | hateoas/config/routes.js | 2818 | /**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `http://localhost:1337/images/foo.jpg`
* might match an image file: `/assets/images/foo.jpg`
*
* Finally, if those don't match either, the default 404 handler is triggered.
* See `api/responses/notFound.js` to adjust your app's 404 logic.
*
* Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
* flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or
* CoffeeScript for the front-end.
*
* For more information on configuring custom routes, check out:
* http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html
*/
module.exports.routes = {
/***************************************************************************
* *
* Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
* etc. depending on your default view engine) your home page. *
* *
* (Alternatively, remove this and add an `index.html` file in your *
* `assets` directory) *
* *
***************************************************************************/
'/': {
view: 'homepage'
},
'get /shirt-state': {
controller: 'shirtState',
action: 'list'
},
'post /shirt-state': {
controller: 'shirtState',
action: 'create'
},
'get /shirt-state/:id': {
controller: 'shirtState',
action: 'retrieve'
},
'put /shirt-state/:id': {
controller: 'shirtState',
action: 'update'
},
'delete /shirt-state/:id': {
controller: 'shirtState',
action: 'delete'
}
/***************************************************************************
* *
* Custom routes here... *
* *
* If a request to a URL doesn't match any of the custom routes above, it *
* is matched against Sails route blueprints. See `config/blueprints.js` *
* for configuration options and examples. *
* *
***************************************************************************/
};
| mit |
react-skg/meetup | src/presentations/reactDay/reactRedux/index.js | 58 | export { default as ReactRedux } from './reactRedux.jsx';
| mit |
wikitree-website/wikitree-page | docs/build/app.js | 127013 | function EditPopover(containerEl, scope, node) {
var self = this;
// properties
self.containerEl = containerEl;
self.scope = scope;
self.node = node;
self.$el = undefined;
self.$name = undefined;
self.$body = undefined;
self.width = undefined;
self.height = undefined;
self.halfwidth = undefined;
self.halfheight = undefined;
self.hidden = false;
// contruction
self.makeElement();
self.addEventListeners();
}
EditPopover.prototype.makeElement = function () {
var self = this;
// create popover
self.$el = $(
'<div class="graph-popover edit popover right">' +
'<div class="arrow"></div>' +
'<div class="popover-content">' +
'<div class="upper">' +
'<div class="name">' +
'<input type="text" class="form-control input-sm" placeholder="Add title...">' +
'</div>' +
'<div class="controls">' +
'<div class="btn-group" role="group" aria-label="Editor controls">' +
'<button type="button" class="cancel-button btn btn-danger btn-xs">' +
'<i class="fa fa-fw fa-close"></i>' +
'</button>' +
'<button type="button" class="confirm-button btn btn-success btn-xs">' +
'<i class="fa fa-fw fa-check"></i>' +
'</button>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="lower">' +
'<textarea rows="5" class="form-control input-sm" placeholder="Add caption..."></textarea>' +
'</div>' +
'</div>' +
'</div>'
);
// append to container element
$(self.containerEl).append(self.$el);
// grab inputs
self.$name = self.$el.find('input');
self.$body = self.$el.find('textarea');
// measure self
self.width = self.$el.outerWidth();
self.height = self.$el.outerHeight();
self.halfwidth = self.width / 2;
self.halfheight = self.height / 2;
// hide self
self.hide();
};
EditPopover.prototype.addEventListeners = function () {
var self = this;
// cancel edit button
self.$el.find('.cancel-button').on('click', function () {
self.hide();
});
// confirm edit button
self.$el.find('.confirm-button').on('click', function () {
self.save();
self.hide();
});
// input enter press
self.$name.on('keypress', function (e) {
switch (e.which) {
case 13:
// save on enter
self.save();
self.hide();
break;
}
});
};
EditPopover.prototype.load = function () {
var self = this;
self.$name.val(self.node.name || '');
self.$body.val(self.node.body || '');
};
EditPopover.prototype.save = function () {
var self = this;
var name = self.$name.val() || '';
var body = self.$body.val() || '';
self.scope.$apply(function () {
self.scope.session.updateNoteNodeContent(
self.node.uuid,
name,
body
);
});
};
EditPopover.prototype.show = function () {
var self = this;
setTimeout(function () {
if (!self.hidden) return;
self.hidden = false;
self.load();
self.$el.show();
}, 1);
};
EditPopover.prototype.hide = function () {
var self = this;
setTimeout(function () {
if (self.hidden) return;
self.hidden = true;
self.$el.hide();
}, 1);
};
EditPopover.prototype.toggle = function () {
var self = this;
if (self.hidden) {
self.show();
} else {
self.hide();
}
};
EditPopover.prototype.position = function (x, y) {
var self = this;
self.$el.css({
top: y - 22,
left: x - 2
});
};
function ForceGraph(containerEl, scope) {
var self = this;
/**
* Properties
*/
// angular scope
self.scope = scope;
// html container
self.containerEl = containerEl;
// dimensions
var rect = self.containerEl.getBoundingClientRect();
self.width = rect.width;
self.height = rect.height;
// states
self.mousePosition = {};
self.keysPressed = {};
self.justZoomed = false;
self.isDragging = false;
self.isLinking = false;
// linking
self.linkingCursor = null;
self.linkingSource = null;
// data
self.nodes = [];
self.links = [];
// d3 selections
self.svg;
self.defs;
self.rect;
self.group;
self.node;
self.underlink;
self.link;
// d3 layouts & behaviors
self.tick = self.makeTick();
self.force = self.makeForce();
self.zoom = self.makeZoom();
self.drag = self.makeDrag();
// event handlers
self.nodeClick = self.makeNodeClick();
self.nodeMouseover = self.makeNodeMouseover();
self.nodeMouseout = self.makeNodeMouseout();
self.linkMouseover = self.makeLinkMouseover();
self.linkMouseout = self.makeLinkMouseout();
// popovers
self.nodePopoversById = {}; // nodePopover & noteNodePopover
self.linkPopoversById = {}; // linkPopover
self.editPopoversById = {}; // editPopover
/**
* Initialization
*/
self.init();
/**
* Window events
*/
d3.select(window)
// resize on window resize
.on('resize', function () {
self.updateSize();
})
// keep track of key presses
.on('keydown', function () {
self.keysPressed[d3.event.keyCode] = true;
// end linking state? (esc)
if (self.keysPressed[27] && self.isLinking) {
self.stopLinkingState();
}
})
.on('keyup', function () {
self.keysPressed[d3.event.keyCode] = false;
})
// track cursor
.on('mousemove', function () {
// update mouse position
var scale = self.zoom.scale();
var translate = self.zoom.translate();
var x = (d3.event.x - translate[0]) / scale;
var y = (d3.event.y - translate[1]) / scale;
self.mousePosition.x = x;
self.mousePosition.y = y;
// update linking cursor position?
if (!self.isLinking) return;
self.linkingCursor.px = x;
self.linkingCursor.py = y;
self.linkingCursor.x = x;
self.linkingCursor.y = y;
self.tick();
self.force.start();
})
// end linking state
.on('click', function () {
// let zoom soak a click
if (self.justZoomed) {
self.justZoomed = false;
return;
}
// end link state?
if (!self.isLinking) return;
self.stopLinkingState();
});
}
ForceGraph.prototype.init = function () {
var self = this;
self.svg = d3.select(self.containerEl)
.append('svg')
.attr('width', self.width)
.attr('height', self.height);
self.defs = self.svg
.append('svg:defs');
self.rect = self.svg
.append('svg:rect')
.attr('width', '100%')
.attr('height', '100%')
.style('fill', 'none')
.style('pointer-events', 'all')
.call(self.zoom)
.on('dblclick.zoom', null);
self.group = self.svg
.append('svg:g');
self.underlink = self.group
.append('svg:g')
.attr('class', 'underlinks')
.selectAll('line.underlink');
self.link = self.group
.append('svg:g')
.attr('class', 'links')
.selectAll('line.link');
self.node = self.group
.append('svg:g')
.attr('class', 'nodes')
.selectAll('g.node');
self.defs
.selectAll('marker')
.data([
'link-arrow',
'link-arrow-hover',
'link-arrow-note',
'link-arrow-note-hover'])
.enter()
.append('svg:marker')
.attr('id', function(d) { return d; })
.attr('viewBox', '0 -5 10 10')
.attr('refX', 21)
.attr('refY', 0)
.attr('markerWidth', 4)
.attr('markerHeight', 4)
.attr('orient', 'auto')
.append('path')
.attr('d', 'M0,-5 L10,0 L0,5');
self.defs
.selectAll('marker')
.append('svg:marker')
.attr('id', 'link-arrow-note-linking')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 7)
.attr('refY', 0)
.attr('markerWidth', 4)
.attr('markerHeight', 4)
.attr('orient', 'auto')
.append('path')
.attr('d', 'M0,-5 L10,0 L0,5');
};
ForceGraph.prototype.getViewCenter = function () {
var self = this;
var scale = self.zoom.scale();
var translate = self.zoom.translate();
var translateX = translate[0] / scale;
var translateY = translate[1] / scale;
var width = self.width / scale;
var height = self.height / scale;
var x = width / 2 - translateX;
var y = height / 2 - translateY;
return [x, y];
};
ForceGraph.prototype.updateSize = function () {
var self = this;
// get container element size
var rect = self.containerEl.getBoundingClientRect();
self.width = rect.width;
self.height = rect.height;
// protect from bad timing
if (!(self.width && self.height)) {
console.error('graph size updating with no container size');
return;
}
// update svg & force
self.svg
.attr('width', self.width)
.attr('height', self.height);
self.force
.size([self.width, self.height])
.start();
};
ForceGraph.prototype.updateCurrentNode = function (node) {
var self = this;
self.node.each(function (d) {
if (node && node.uuid && d.uuid === node.uuid) {
d3.select(this).classed('active', true);
} else {
d3.select(this).classed('active', false);
}
});
};
ForceGraph.prototype.updateNoteNodeContent = function (data) {
var self = this;
// find node group
var g = self.node.filter(function (d) { return d.uuid === data.uuid });
// scrape out children
g.selectAll('*').remove();
// rebuild
self.addNoteNode(data, g);
};
ForceGraph.prototype.updateNodesAndLinks = function (nodes, links) {
var self = this;
// protect from bad timing
if (!(self.width && self.height)) {
console.error('graph size updating with no container size');
return;
}
/**
* Prep data
*/
self.nodes = nodes.slice();
self.links = links.slice();
// add linking elements?
if (self.isLinking) {
var cursorNode = {
uuid: 'linking-cursor-node',
type: 'cursor',
x: self.mousePosition.x || undefined,
y: self.mousePosition.y || undefined,
px: self.mousePosition.x || undefined,
py: self.mousePosition.y || undefined,
fixed: true
}
var cursorLink = {
source: self.linkingSource,
target: cursorNode,
linking: true
}
nodes.push(cursorNode);
links.push(cursorLink);
self.linkingCursor = cursorNode;
}
// give nodes starting positions
var viewCenter = self.getViewCenter();
var centerX = viewCenter[0];
var centerY = viewCenter[1];
nodes.forEach(function (node) {
if (!(node.x || node.y)) {
node.x = centerX + (Math.random() * 5);
node.y = centerY + (Math.random() * 5);
}
});
// add graph properties
self.force.nodes(nodes);
self.force.links(links);
/**
* Update underlinks (needed for hearing mouse hovers)
*/
// update underlink elements
self.underlink = self.underlink.data(links, function (d) { return d.uuid; });
// remove the old
self.underlink.exit().remove();
// add the new
self.underlink
.enter()
.append('svg:line')
.attr('class', 'underlink')
.classed('linkback', function (d) { return d.linkbackId; })
.classed('linking', function (d) { return d.linking; })
.classed('note', function (d) { return d.source.type === 'note'; })
.on('mouseover', self.linkMouseover)
.on('mouseout', self.linkMouseout);
/**
* Update links
*/
// update link elements
self.link = self.link.data(links, function (d) { return d.uuid; });
// remove the old
var exitLink = self.link.exit();
exitLink.each(function (d) {
// clean out popovers
if (self.linkPopoversById[d.uuid]) {
self.linkPopoversById[d.uuid].$el.remove();
delete self.linkPopoversById[d.uuid];
}
});
exitLink.remove();
// add the new
var enterLink = self.link
.enter()
.append('svg:line')
.attr('class', 'link')
.classed('linkback', function (d) { return d.linkbackId; })
.classed('linking', function (d) { return d.linking; })
.classed('note', function (d) { return d.source.type === 'note'; });
enterLink.each(function (d) {
// add new popover
if (d.linkbackId) {
var popover = self.linkPopoversById[d.linkbackId];
if (!popover) return;
popover.addLinkback(d3.select(this));
} else {
self.linkPopoversById[d.uuid] = new LinkPopover(
self.containerEl,
self.scope,
d,
d3.select(this)
);
}
});
/**
* Update nodes
*/
self.node = self.node.data(nodes, function (d) { return d.uuid; });
// remove the old
var exitNode = self.node.exit();
exitNode.each(function (d) {
// clean out any node or note node popovers
if (self.nodePopoversById[d.uuid]) {
self.nodePopoversById[d.uuid].$el.remove();
delete self.nodePopoversById[d.uuid];
}
// clean out any edit popovers
if (self.editPopoversById[d.uuid]) {
self.editPopoversById[d.uuid].$el.remove();
delete self.editPopoversById[d.uuid];
}
});
exitNode.remove();
// add the new
var enterNode = self.node.enter()
.append('svg:g')
.attr('class', 'node')
.classed('fixed', function (d) { return d.fixed; })
.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
enterNode.each(function (d) {
var g = d3.select(this);
switch (d.type) {
case 'article':
case 'category':
case 'search':
self.addNode(d, g);
break;
case 'note':
self.addNoteNode(d, g);
break;
case 'cursor':
self.addCursorNode(d, g);
break;
}
});
/**
* Nudge graph
*/
// keep things moving
self.force.start();
};
ForceGraph.prototype.addNode = function (d, g) {
var self = this;
// disc
g.append('svg:circle')
.attr('r', 16)
.attr('class', 'disc')
.on('mouseover', self.nodeMouseover)
.on('mouseout', self.nodeMouseout)
.on('click', self.nodeClick)
.call(self.drag);
// pin
g.append('svg:circle')
.attr('r', 3)
.attr('class', 'pin');
// name
g.append('svg:text')
.attr('class', 'name')
.attr('dx', 6)
.attr('dy', -6)
.text(function (d) { return d.name })
.on('click', self.nodeClick)
.call(self.drag);
// popover
self.nodePopoversById[d.uuid] = new NodePopover(
self.containerEl,
self.scope,
d,
g
);
};
ForceGraph.prototype.addNoteNode = function (d, g) {
var self = this;
// font awesome unicodes
// http://fortawesome.github.io/Font-Awesome/cheatsheet/
// note background
g.append('svg:text')
.attr('class', 'note-icon note-icon-back')
.attr('dx', 0)
.attr('dy', -1)
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'central')
.attr('font-family', 'FontAwesome')
.text('\uf15b') // fa-file
// note foreground
g.append('svg:text')
.attr('class', 'note-icon note-icon-fore')
.attr('dx', 0)
.attr('dy', -1)
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'central')
.attr('font-family', 'FontAwesome')
.text('\uf016') // fa-file-o
.on('mouseover', self.nodeMouseover)
.on('mouseout', self.nodeMouseout)
.on('click', self.nodeClick)
.call(self.drag);
// pin
g.append('svg:circle')
.attr('r', 3)
.attr('class', 'pin');
// name
g.append('svg:text')
.attr('class', 'note')
.attr('dx', 18)
.attr('dy', 4)
.text(function (d) { return d.name })
.on('click', self.nodeClick)
.call(self.drag);
// body
g.append('foreignObject')
.attr('width', 240)
.attr('height', 120)
.attr('x', 18)
.attr('y', function (d) {
if (d.name && d.name.length) {
return 8;
} else {
return -8;
}
})
.style('overflow', 'visible')
.on('click', self.nodeClick)
.call(self.drag)
.append('xhtml:body')
.html(function (d) {
return d.body ? d.body.replace(/\n/g, '<br>') : '';
})
.each(function (d) {
var foreignObject = this.parentNode;
foreignObject.setAttribute('width', this.clientWidth);
foreignObject.setAttribute('height', this.clientHeight);
});
// note node popover
self.nodePopoversById[d.uuid] = new NoteNodePopover(
self.containerEl,
self.scope,
d,
g
);
// edit popover
self.editPopoversById[d.uuid] = new EditPopover(
self.containerEl,
self.scope,
d
);
};
ForceGraph.prototype.addCursorNode = function (d, g) {
var self = this;
// disc
g.append('svg:circle')
.attr('r', 1)
.attr('class', 'cursor');
};
ForceGraph.prototype.updatePopovers = function () {
var self = this;
var scale = self.zoom.scale();
var translate = self.zoom.translate();
var translateX = translate[0];
var translateY = translate[1];
// node popovers
Object.keys(self.nodePopoversById).forEach(function (id) {
var popover = self.nodePopoversById[id];
if (popover.hidden) return;
var x = popover.node.x * scale + translateX;
var y = popover.node.y * scale + translateY;
y += 14 * scale; // shift below center
popover.position(x, y);
});
// edit popovers
Object.keys(self.editPopoversById).forEach(function (id) {
var popover = self.editPopoversById[id];
if (popover.hidden) return;
var x = popover.node.x * scale + translateX;
var y = popover.node.y * scale + translateY;
x += 10 * scale; // shift to the right
popover.position(x, y);
});
// link popovers
Object.keys(self.linkPopoversById).forEach(function (id) {
var popover = self.linkPopoversById[id];
if (popover.hidden) return;
var node1 = popover.link.source;
var node2 = popover.link.target;
var x1 = node1.x * scale + translateX;
var y1 = node1.y * scale + translateY;
var x2 = node2.x * scale + translateX;
var y2 = node2.y * scale + translateY;
var centerX = (x1 + x2) / 2;
var centerY = (y1 + y2) / 2;
popover.position(centerX, centerY);
});
};
ForceGraph.prototype.updateNodePopover = function (popover) {
var self = this;
var scale = self.zoom.scale();
var translate = self.zoom.translate();
var translateX = translate[0];
var translateY = translate[1];
var x = popover.node.x * scale + translateX;
var y = popover.node.y * scale + translateY;
y += 14 * scale; // shift below center
popover.position(x, y);
};
ForceGraph.prototype.updateEditPopover = function (popover) {
var self = this;
var scale = self.zoom.scale();
var translate = self.zoom.translate();
var translateX = translate[0];
var translateY = translate[1];
var x = popover.node.x * scale + translateX;
var y = popover.node.y * scale + translateY;
x += 10 * scale; // shift to the right
popover.position(x, y);
};
ForceGraph.prototype.updateLinkPopover = function (popover) {
var self = this;
var scale = self.zoom.scale();
var translate = self.zoom.translate();
var translateX = translate[0];
var translateY = translate[1];
var node1 = popover.link.source;
var node2 = popover.link.target;
var x1 = node1.x * scale + translateX;
var y1 = node1.y * scale + translateY;
var x2 = node2.x * scale + translateX;
var y2 = node2.y * scale + translateY;
var centerX = (x1 + x2) / 2;
var centerY = (y1 + y2) / 2;
popover.position(centerX, centerY);
};
ForceGraph.prototype.hideAllPopovers = function (exceptId) {
var self = this;
Object.keys(self.nodePopoversById).forEach(function (id) {
if (id == exceptId) return;
var popover = self.nodePopoversById[id];
if (popover.hidden) return;
popover.hide(true);
});
Object.keys(self.linkPopoversById).forEach(function (id) {
if (id == exceptId) return;
var popover = self.linkPopoversById[id];
if (popover.hidden) return;
popover.hide(true);
});
};
ForceGraph.prototype.makeTick = function () {
var self = this;
function x1(d) { return d.source.x; }
function y1(d) { return d.source.y; }
function x2(d) { return d.target.x; }
function y2(d) { return d.target.y; }
function transform(d) {
return 'translate(' + d.x + ',' + d.y + ')';
}
return function () {
self.underlink
.attr('x1', x1)
.attr('y1', y1)
.attr('x2', x2)
.attr('y2', y2);
self.link
.attr('x1', x1)
.attr('y1', y1)
.attr('x2', x2)
.attr('y2', y2);
self.node
.attr('transform', transform);
self.updatePopovers();
};
};
ForceGraph.prototype.makeForce = function () {
var self = this;
return d3.layout.force()
.size([this.width, this.height])
.linkDistance(100)
.linkDistance(function (d) {
switch (d.source.type) {
case 'article':
case 'category':
case 'search':
return 100;
case 'note':
case 'cursor':
return 1;
}
})
.linkStrength(function (d) {
switch (d.source.type) {
case 'article':
case 'category':
case 'search':
return 0.2;
case 'note':
case 'cursor':
return 0.07;
}
})
.charge(function (d) {
switch (d.type) {
case 'article':
case 'category':
case 'search':
return -400;
case 'note':
return -800;
case 'cursor':
return 0;
}
})
.gravity(0.03)
.friction(0.8)
.theta(0.9)
.alpha(0.1)
.on('tick', this.tick);
};
ForceGraph.prototype.makeZoom = function () {
var self = this;
return d3.behavior.zoom()
.scaleExtent([0.2, 10])
.on('zoom', function () {
self.group.attr(
'transform',
'translate(' + d3.event.translate + ')' +
'scale(' + d3.event.scale + ')'
);
self.updatePopovers();
// prevent greedy click event
self.justZoomed = true;
});
};
ForceGraph.prototype.makeDrag = function () {
var self = this;
return d3.behavior.drag()
.on('dragstart', function (d, i) {
if (self.isLinking) return;
d3.event.sourceEvent.stopPropagation();
})
.on('drag', function (d, i) {
if (self.isLinking) return;
if (!self.isDragging) {
self.isDragging = true;
// hide popover on drag
self.nodePopoversById[d.uuid].$el.hide();
if (!self.keysPressed[16]) {
// only fix if user not holding shift
d3.select(this.parentNode).classed('fixed', true);
d.fixed = true;
}
}
self.force.start();
d3.event.sourceEvent.stopPropagation();
d.px += d3.event.x;
d.py += d3.event.y;
d.x += d3.event.x;
d.y += d3.event.y;
self.tick();
})
.on('dragend', function (d, i) {
if (self.isLinking) return;
d3.event.sourceEvent.stopPropagation();
if (self.isDragging) {
self.tick();
// show popover when done drag
var popover = self.nodePopoversById[d.uuid];
self.updateNodePopover(popover);
popover.$el.show();
// also prevents selecting on drag
setTimeout(function () {
self.isDragging = false;
popover.show();
}, 50);
}
});
};
ForceGraph.prototype.makeNodeClick = function () {
var self = this;
return function (d) {
d3.event.preventDefault();
d3.event.stopPropagation();
if (self.isDragging) return;
if (self.isLinking) {
// clicked link source?
if (d.uuid === self.linkingSource.uuid) {
// end linking state
self.stopLinkingState();
} else {
// add link to this node
self.scope.$apply(function () {
self.scope.addLink(
self.linkingSource.uuid,
d.uuid
);
});
}
} else if (d3.event.shiftKey) {
// toggle this node's pin state
self.toggleNodePin(d, d3.select(this.parentNode));
} else {
if (d.type === 'note') {
// toggle note edit popover
var editPopover = self.editPopoversById[d.uuid];
var nodePopover = self.nodePopoversById[d.uuid];
if (editPopover.hidden) {
// update & show edit popover
self.updateEditPopover(editPopover);
editPopover.show();
// hide node popover
nodePopover.hide(true);
} else {
// hide edit popover
editPopover.hide();
// show node popover
nodePopover.show();
}
} else {
// set this node as current
self.scope.$apply(function () {
self.scope.setCurrentNode(d.uuid);
});
}
}
};
};
ForceGraph.prototype.makeNodeMouseover = function () {
var self = this;
return function (d) {
if (self.isDragging) return;
if (self.isLinking) return;
d.hovered = true;
var popover = self.nodePopoversById[d.uuid];
self.updateNodePopover(popover);
self.hideAllPopovers(d.uuid);
popover.show();
};
};
ForceGraph.prototype.makeNodeMouseout = function () {
var self = this;
return function (d) {
if (self.isDragging) return;
if (self.isLinking) return;
d.hovered = false;
var popover = self.nodePopoversById[d.uuid];
popover.hide();
};
};
ForceGraph.prototype.makeLinkMouseover = function () {
var self = this;
return function (d) {
if (self.isDragging) return;
if (self.isLinking) return;
d.hovered = true;
d3.select(this).classed('hovered', true);
var popover = self.linkPopoversById[d.uuid];
self.updateLinkPopover(popover);
self.hideAllPopovers(d.uuid);
popover.show();
};
};
ForceGraph.prototype.makeLinkMouseout = function () {
var self = this;
return function (d) {
if (self.isDragging) return;
if (self.isLinking) return;
d.hovered = false;
d3.select(this).classed('hovered', false);
var popover = self.linkPopoversById[d.uuid];
popover.hide();
};
};
ForceGraph.prototype.toggleNodePin = function (nodeData, nodeSelection) {
var self = this;
if (!nodeSelection) {
nodeSelection = self.node
.filter(function (d) {
return d.uuid === nodeData.uuid
});
}
nodeData.fixed = !nodeData.fixed;
nodeSelection.classed('fixed', nodeData.fixed);
self.force.start();
};
ForceGraph.prototype.centerOnNode = function (node) {
var self = this;
if (!node) return;
var scale = self.zoom.scale();
var w = self.width;
var h = self.height;
var x = node.x * scale;
var y = node.y * scale;
var translateX = (w / 2) - x;
var translateY = (h / 2) - y;
self.zoom.translate([translateX, translateY]);
self.zoom.event(self.rect.transition().duration(600));
};
ForceGraph.prototype.startLinkingState = function (node) {
var self = this;
self.isLinking = true;
self.linkingSource = node;
self.updateNodesAndLinks(
self.nodes,
self.links
);
};
ForceGraph.prototype.stopLinkingState = function () {
var self = this;
self.isLinking = false;
self.linkingSource = null;
self.linkingCursor = null;
self.updateNodesAndLinks(
self.nodes,
self.links
);
};
function HomeGraph(containerEl) {
this.containerEl = containerEl;
this.width = containerEl.clientWidth;
this.height = containerEl.clientHeight;
this.svg;
this.group;
this.node;
this.link;
this.isDragging = false;
this.tick = this.makeTick();
this.force = this.makeForce();
this.zoom = this.makeZoom();
this.drag = this.makeDrag();
this.init();
var self = this;
d3.select(window).on('resize', function () {
self.updateSize();
});
}
HomeGraph.prototype.init = function () {
this.svg = d3.select(this.containerEl)
.append('svg')
.attr('width', this.width)
.attr('height', this.height);
var rect = this.svg
.append('rect')
.attr('width', '100%')
.attr('height', '100%')
.style('fill', 'none')
.style('pointer-events', 'all')
.call(this.zoom)
.on('dblclick.zoom', null);
this.group = this.svg
.append('g');
this.link = this.group
.append('svg:g')
.attr('class', 'links')
.selectAll('line.link');
this.node = this.group
.append('svg:g')
.attr('class', 'nodes')
.selectAll('g.node');
};
HomeGraph.prototype.updateSize = function () {
this.width = this.containerEl.clientWidth;
this.height = this.containerEl.clientHeight
this.svg
.attr('width', this.width)
.attr('height', this.height);
this.force
.size([this.width, this.height])
.resume();
};
HomeGraph.prototype.updateNodesAndLinks = function (nodes, links) {
nodes = nodes.slice();
links = links.slice();
this.force.nodes(nodes);
this.force.links(links);
// update link elements
this.link = this.link.data(links);
this.link.exit().remove();
var newLink = this.link
.enter()
.append('svg:line')
.attr('class', 'link');
// .style('marker-end', 'url(#arrow)');
// update node elements
this.node = this.node.data(nodes);
this.node.exit().remove();
var newNode = this.node
.enter()
.append('svg:g')
.attr('class', 'node')
.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
newNode
.append('svg:circle')
.attr('r', 18)
.attr('class', 'disc')
.call(this.drag);
// keep things moving
this.force.start();
};
HomeGraph.prototype.makeTick = function () {
var self = this;
return function () {
self.link
.attr('x1', function(d) { return d.source.x; })
.attr('y1', function(d) { return d.source.y; })
.attr('x2', function(d) { return d.target.x; })
.attr('y2', function(d) { return d.target.y; });
self.node
.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
};
};
HomeGraph.prototype.makeForce = function () {
var self = this;
return d3.layout.force()
.size([this.width, this.height])
.linkDistance(60)
.charge(-1200)
.gravity(0.2)
.friction(0.4)
.theta(0.01)
.on('tick', this.tick);
};
HomeGraph.prototype.makeZoom = function () {
var self = this;
return d3.behavior.zoom()
.scaleExtent([0.2, 10])
.on('zoom', function () {
self.group.attr(
'transform',
'translate(' + d3.event.translate + ')' +
'scale(' + d3.event.scale + ')'
);
});
};
HomeGraph.prototype.makeDrag = function () {
var self = this;
return d3.behavior.drag()
.on('dragstart', function (d, i) {
d3.event.sourceEvent.stopPropagation();
})
.on('drag', function (d, i) {
if (!self.isDragging) {
self.isDragging = true;
}
self.force.start();
d3.event.sourceEvent.stopPropagation();
d.px += d3.event.x;
d.py += d3.event.y;
d.x += d3.event.x;
d.y += d3.event.y;
self.tick();
})
.on('dragend', function (d, i) {
d3.event.sourceEvent.stopPropagation();
if (self.isDragging) {
self.tick();
self.isDragging = false;
}
});
};
function LinkPopover(containerEl, scope, link, linkSelect) {
var self = this;
// properties
self.containerEl = containerEl;
self.scope = scope;
self.link = link;
self.linkSelect = linkSelect;
self.linkbackSelect = undefined;
self.$el = undefined;
self.width = undefined;
self.height = undefined;
self.halfwidth = undefined;
self.halfheight = undefined;
self.hidden = false;
self.hovered = false;
// contruction
self.makeElement();
self.addEventListeners();
}
LinkPopover.prototype.makeElement = function () {
var self = this;
// create popover
self.$el = $(
'<div class="graph-popover link popover">' +
'<div class="popover-content">' +
'<div class="btn-group" role="group" aria-label="Link controls">' +
'<button type="button" class="del-button btn btn-default btn-xs">' +
'<i class="fa fa-fw fa-unlink"></i>' +
'</button>' +
'</div>' +
'</div>' +
'</div>'
);
// append to container element
$(self.containerEl).append(self.$el);
// measure self
self.width = self.$el.outerWidth();
self.height = self.$el.outerHeight();
self.halfwidth = self.width / 2;
self.halfheight = self.height / 2;
// hide self
self.hide();
};
LinkPopover.prototype.addEventListeners = function () {
var self = this;
// hover on
self.$el.on('mouseover', function () {
self.hovered = true;
});
// hover off
self.$el.on('mouseout', function () {
self.hovered = false;
setTimeout(function () {
if (!self.link.hovered) {
self.hide();
}
}, 1);
});
// delete button
self.$el.find('.del-button').on('click', function () {
self.scope.removeLink(self.link.uuid);
});
};
LinkPopover.prototype.addLinkback = function (linkbackSelect) {
var self = this;
self.linkbackSelect = linkbackSelect;
};
LinkPopover.prototype.show = function () {
var self = this;
setTimeout(function () {
if (!self.hidden) return;
self.hidden = false;
self.$el.show();
self.linkSelect.classed('hovered', true);
if (self.linkbackSelect) {
self.linkbackSelect.classed('hovered', true);
}
}, 1);
};
LinkPopover.prototype.hide = function (forceful) {
var self = this;
if (forceful) {
self._hide();
return;
}
setTimeout(function () {
if (self.hovered) return;
if (self.hidden) return;
self._hide();
}, 1);
};
LinkPopover.prototype._hide = function () {
var self = this;
self.hidden = true;
self.$el.hide();
self.linkSelect.classed('hovered', false);
if (self.linkbackSelect) {
self.linkbackSelect.classed('hovered', false);
}
};
LinkPopover.prototype.position = function (x, y) {
var self = this;
self.$el.css({
top: y - self.halfheight,
left: x - self.halfwidth
});
};
function NodePopover(containerEl, scope, node, nodeSelect) {
var self = this;
// properties
self.containerEl = containerEl;
self.scope = scope;
self.node = node;
self.nodeSelect = nodeSelect;
self.$el = undefined;
self.width = undefined;
self.height = undefined;
self.halfwidth = undefined;
self.halfheight = undefined;
self.hidden = false;
self.hovered = false;
// contruction
self.makeElement();
self.addEventListeners();
}
NodePopover.prototype.makeElement = function () {
var self = this;
// create popover
self.$el = $(
'<div class="graph-popover node popover bottom">' +
'<div class="arrow"></div>' +
'<div class="popover-content">' +
'<div class="btn-group" role="group" aria-label="Node controls">' +
'<button type="button" class="pin-button btn btn-default btn-xs">' +
'<i class="fa fa-fw fa-thumb-tack"></i>' +
'</button>' +
'<button type="button" class="del-button btn btn-default btn-xs">' +
'<i class="fa fa-fw fa-trash-o"></i>' +
'</button>' +
'</div>' +
'</div>' +
'</div>'
);
// append to container element
$(self.containerEl).append(self.$el);
// measure self
self.width = self.$el.outerWidth();
self.height = self.$el.outerHeight();
self.halfwidth = self.width / 2;
self.halfheight = self.height / 2;
// hide self
self.hide();
};
NodePopover.prototype.addEventListeners = function () {
var self = this;
// hover on
self.$el.on('mouseenter', function () {
self.hovered = true;
});
// hover off
self.$el.on('mouseleave', function () {
self.hovered = false;
setTimeout(function () {
self.hide();
}, 50);
});
// pin button
self.$el.find('.pin-button').on('click', function () {
self.scope.graph.toggleNodePin(self.node);
self.hide(true);
});
// delete button
self.$el.find('.del-button').on('click', function () {
self.scope.removeNode(self.node.uuid);
});
};
NodePopover.prototype.show = function () {
var self = this;
setTimeout(function () {
if (!self.hidden) return;
self.hidden = false;
self.$el.show();
self.nodeSelect.classed('hovered', true);
}, 1);
};
NodePopover.prototype.hide = function (forceful) {
var self = this;
if (forceful) {
self._hide();
return;
}
setTimeout(function () {
if (self.hidden) return;
if (self.hovered) return;
if (self.node.hovered) return;
self._hide();
}, 100);
};
NodePopover.prototype._hide = function () {
var self = this;
self.hidden = true;
self.hovered = false;
self.$el.hide();
self.nodeSelect.classed('hovered', false);
};
NodePopover.prototype.position = function (x, y) {
var self = this;
self.$el.css({
top: y - self.halfheight + 18,
left: x - self.halfwidth
});
};
function NoteNodePopover(containerEl, scope, node, nodeSelect) {
var self = this;
// properties
self.containerEl = containerEl;
self.scope = scope;
self.node = node;
self.nodeSelect = nodeSelect;
self.$el = undefined;
self.width = undefined;
self.height = undefined;
self.halfwidth = undefined;
self.halfheight = undefined;
self.hidden = false;
self.hovered = false;
// contruction
self.makeElement();
self.addEventListeners();
}
NoteNodePopover.prototype.makeElement = function () {
var self = this;
// create popover
self.$el = $(
'<div class="graph-popover note popover bottom">' +
'<div class="arrow"></div>' +
'<div class="popover-content">' +
'<div class="btn-group" role="group" aria-label="Node controls">' +
'<button type="button" class="link-button btn btn-default btn-xs">' +
'<i class="fa fa-fw fa-link"></i>' +
'</button>' +
'<button type="button" class="pin-button btn btn-default btn-xs">' +
'<i class="fa fa-fw fa-thumb-tack"></i>' +
'</button>' +
'<button type="button" class="del-button btn btn-default btn-xs">' +
'<i class="fa fa-fw fa-trash-o"></i>' +
'</button>' +
'</div>' +
'</div>' +
'</div>'
);
// append to container element
$(self.containerEl).append(self.$el);
// measure self
self.width = self.$el.outerWidth();
self.height = self.$el.outerHeight();
self.halfwidth = self.width / 2;
self.halfheight = self.height / 2;
// hide self
self.hide();
};
NoteNodePopover.prototype.addEventListeners = function () {
var self = this;
// hover on
self.$el.on('mouseenter', function () {
self.hovered = true;
});
// hover off
self.$el.on('mouseleave', function () {
self.hovered = false;
setTimeout(function () {
self.hide();
}, 50);
});
// pin button
self.$el.find('.pin-button').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
self.scope.graph.toggleNodePin(self.node);
self.hide(true);
});
// link button
self.$el.find('.link-button').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
self.scope.graph.startLinkingState(self.node, self.nodeSelect);
self.hide(true);
});
// delete button
self.$el.find('.del-button').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
self.scope.removeNode(self.node.uuid);
});
};
NoteNodePopover.prototype.show = function () {
var self = this;
setTimeout(function () {
if (!self.hidden) return;
self.hidden = false;
self.$el.show();
self.nodeSelect.classed('hovered', true);
}, 1);
};
NoteNodePopover.prototype.hide = function (forceful) {
var self = this;
if (forceful) {
self._hide();
return;
}
setTimeout(function () {
if (self.hidden) return;
if (self.hovered) return;
if (self.node.hovered) return;
self._hide();
}, 100);
};
NoteNodePopover.prototype._hide = function () {
var self = this;
self.hidden = true;
self.hovered = false;
self.$el.hide();
self.nodeSelect.classed('hovered', false);
};
NoteNodePopover.prototype.position = function (x, y) {
var self = this;
self.$el.css({
top: y - self.halfheight + 16,
left: x - self.halfwidth
});
};
(function() {
angular.module('wikitree', [
'ngRoute',
'LocalStorageModule',
'ui.bootstrap.alert',
'wikitree.home',
'wikitree.session',
'wikitree.search'
]).
config(['localStorageServiceProvider', function(localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('Wikitree');
}]);
})();
(function() {
angular.module('wikitree').
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'js/angular/home/home.template.html',
controller: 'home_controller',
resolve: {
is_new: ['Sessions', function (Sessions) {
return Sessions.is_new();
}]
}
}).
when('/welcome', {
templateUrl: 'js/angular/home/home.template.html',
controller: 'home_controller'
}).
when('/session/:uuid', {
templateUrl: 'js/angular/session/session.template.html',
controller: 'session_controller',
controllerAs: 'session',
resolve: {
init_session: ['Sessions', '$route', function (Sessions, $route) {
return Sessions.restore($route.current.params.uuid);
}]
}
}).
when('/new/:term/:search?', {
templateUrl: 'js/angular/session/session.template.html',
controller: 'session_controller',
controllerAs: 'session',
resolve: {
init_session: ['Sessions', '$route', function (Sessions, $route) {
return Sessions.new($route.current.params.term);
}]
}
}).
otherwise({ redirectTo: '/' });
}]);
})();
(function() {
angular.module('wikitree').
factory('Search', ['$http', 'Articles', 'Categories', 'Searches',
function($http, Articles, Categories, Searches) {
var search = {};
search.get_suggestions = function (term) {
return $http.jsonp('https://en.wikipedia.org/w/api.php', {
params: {
action: 'opensearch',
search: term,
callback: 'JSON_CALLBACK'
}
}).then(function(response) {
return response.data[1];
});
};
search.findOrAddArticle = function (title) {
// is this a category?
if (title.match(/^Category:/)) {
// skip to special handler
return search.findOrAddCategory(title);
}
return Articles.getByUnsafeTitle(title).
then(function (article) {
return{
type: 'article',
name: article.title,
title: article.title
};
}).
catch(function (err) {
if (err) console.error('findOrAddArticle', err);
// no result? try searching
return search.findOrAddSearch(title);
});
};
search.findOrAddCategory = function (title) {
return Categories.getByUnsafeTitle(title).
then(function (category) {
return {
type: 'category',
name: category.title,
title: category.title
};
}).
catch(function (err) {
if (err) console.error('findOrAddCategory', err);
// no result? try searching
return findOrAddSearch(title);
});
};
search.findOrAddSearch = function (query) {
return Searches.getByQuery(query).
then(function (search) {
return {
type: 'search',
name: 'Search "' + query + '"',
query: query
};
}).
catch(function (err) {
if (err) console.error('findOrAddSearch', err);
// no dice
return null;
});
};
return search;
}]);
})();
(function() {
angular.module('wikitree').
factory('Sessions', [
'$rootScope',
'$location',
'$route',
'localStorageService',
'Utilities',
function($rootScope, $location, $route, localStorageService, Utilities) {
function Session (term, is_search) {
this.new = true;
this.term = term;
this.search = is_search;
this.uuid = Utilities.makeUUID();
this.data = {
current_node_id: undefined,
prev_stack: [],
next_stack: [],
nodes: [],
links: []
}
}
function SessionIndex (session, name) {
this.uuid = session.uuid;
this.name = name;
this.rename = name;
this.date = Date.now();
}
var Sessions = {};
Sessions.index = localStorageService.get('index') || [];
Sessions.active = localStorageService.get('active') || 0;
if (Sessions.index.length > 0) {
var test_sesh = localStorageService.get(Sessions.index[0].uuid);
if (test_sesh && !test_sesh.hasOwnProperty('search')) {
localStorageService.clearAll();
Sessions.index = localStorageService.get('index') || [];
Sessions.active = localStorageService.get('active') || 0;
}
}
// a sort happened! gotta know where your active session is...
// fired in menu.controller.js
$rootScope.$on('session:sort', function (event, data) {
// moved the active session
if (data.start == Sessions.active) {
Sessions.active = data.stop;
// moved a session below active above
} else if (data.start > Sessions.active && data.stop <= Sessions.active) {
Sessions.active++;
// moved a session above active below
} else if (data.start < Sessions.active && data.stop >= Sessions.active) {
Sessions.active--;
}
});
Sessions.is_new = function () {
// any existing sessions?
if (Sessions.index.length !== 0) {
var active_session = Sessions.index[Sessions.active];
// pull up the active one
if (active_session) {
$location.path('/session/' + active_session.uuid);
}
} else {
$location.path('/welcome');
}
};
Sessions.new = function (name) {
//debugger
Sessions.active = 0;
var is_search = ($route.current.params.search === 'true');
var session = new Session(name, is_search);
Sessions.index.unshift(new SessionIndex(session, name));
localStorageService.set(session.uuid, session);
localStorageService.set('index', Sessions.index);
localStorageService.set('active', Sessions.active);
$location.path('/session/'+session.uuid).replace();
return session;
};
Sessions.save = function (uuid, data) {
var session = localStorageService.get(uuid);
if (!session) {
return;
}
session.new = false;
session.data = data;
Sessions.index[Sessions.active].date = Date.now();
localStorageService.set('index', Sessions.index);
localStorageService.set(uuid, session);
};
Sessions.restore = function (uuid) {
var session = localStorageService.get(uuid);
if (!session) $location.path('/');
// LOL
Sessions.active = Sessions.index.indexOf(Sessions.index.
filter(function (session) {
return session.uuid === uuid
})[0]);
return session;
};
Sessions.delete = function (idx) {
var deletedSessionUUID = Sessions.index[idx].uuid;
localStorageService.remove(deletedSessionUUID);
Sessions.index.splice(idx, 1);
localStorageService.set('index', Sessions.index);
// if deleted only session:
if (Sessions.index.length == 0) {
//window.location = '/welcome';
$location.path('/');
// if deleted active session that was last:
} else if (idx == Sessions.active) {
var uuid;
if (idx == Sessions.index.length) {
uuid = Sessions.index[idx-1].uuid;
} else {
uuid = Sessions.index[idx].uuid;
}
$location.path('/session/'+uuid);
// if deleted session above active
} else if (idx < Sessions.active) {
Sessions.active--;
}
};
return Sessions;
}]);
})();
(function() {
angular.module('wikitree').
factory('Utilities', [function() {
var Utilities = {};
Utilities.makeUUID = function() {
// http://stackoverflow.com/a/2117523
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
Utilities.makeJitter = function (factor) {
var jitter = factor * Math.random();
if (Math.random() < 0.5) jitter = -1 * jitter;
return jitter;
};
Utilities.shuffleArr = function (arr) {
// copy array
arr = arr.slice(0);
//
// Fisher Yates implementation by mbostock http://bost.ocks.org/mike/shuffle/
var remaining = arr.length;
var element;
var index;
// While there remain elements to shuffle…
while (remaining) {
// Pick a remaining element…
index = Math.floor(Math.random() * remaining--);
// And swap it with the current element.
element = arr[remaining];
arr[remaining] = arr[index];
arr[index] = element;
}
return arr;
};
return Utilities;
}]);
})();
(function() {
angular.module('wikitree.search', [
'ui.bootstrap.typeahead',
'ui.bootstrap.tpls'
]);
})();
(function() {
angular.module('wikitree.search').
controller('searchController', ['$scope', '$location', 'Search',
function($scope, $location, Search) {
$scope.inputText = '';
$scope.get_suggestions = function (term) {
return Search.get_suggestions(term);
};
$scope.tryEnter = function ($event) {
if ($event.keyCode === 13) {
$event.preventDefault();
$scope.start_search(true);
}
};
$scope.start_search = function (isButton) {
var term = $scope.inputText;
//if (term) {
// if ($scope.new_session) {
// $location.path('/new/' + term);
// } else {
// $scope.session.do_search(term)
// }
//}
if (term) {
if ($scope.new_session) {
if (isButton) {
$location.path('/new/' + term + '/true');
} else {
$location.path('/new/' + term);
}
} else {
if (isButton) {
$scope.session.do_search(term, null, null, true);
} else {
$scope.session.do_search(term);
}
}
}
$scope.inputText = '';
};
}]);
})();
(function() {
angular.module('wikitree.search').
directive('search', [function() {
return {
restrict: 'E',
templateUrl: 'js/angular/search/search.template.html',
controller: 'searchController',
link: function($scope, $element, $attributes) {
$scope.large = $attributes.large;
$scope.new_session = $attributes.newSession;
}
}
}]);
})();
(function() {
angular.module('wikitree.home', []);
})();
(function() {
angular.module('wikitree.home').
controller('home_controller', ['$scope', '$location', 'Utilities',
function($scope, $location, Utilities) {
var $graph = $('#home-graph');
var graph = new HomeGraph($graph[0]);
function Node(x, y) {
this.uuid = Utilities.makeUUID();
this.index = undefined; // the zero-based index of the node within the nodes array.
this.x = x; // the x-coordinate of the current node position.
this.y = y; // the y-coordinate of the current node position.
this.px = undefined; // the x-coordinate of the previous node position.
this.py = undefined; // the y-coordinate of the previous node position.
this.fixed = undefined; // a boolean indicating whether node position is locked.
this.weight = undefined; // the node weight; the number of associated links.
}
function Link(source, target) {
this.uuid = Utilities.makeUUID();
this.source = source;
this.target = target;
}
var nodes = [];
var links = [];
var nodesById = {};
var linksByNodeIds = {};
var requestID = null;
var timeoutID = null;
var limit = 200;
var count = 0;
/**
* Grow network
*/
function addRandomNode() {
if (count > limit) {
// big crunch-> linkAllNodes();
return;
}
count++;
if (!nodes.length) {
nodes.push(new Node(
window.innerWidth / 2,
window.innerHeight / 2
));
} else {
var sourceIndex = Math.floor(Math.random() * nodes.length);
var source = nodes[sourceIndex];
var node = new Node(
source.x + Utilities.makeJitter(10),
source.y + Utilities.makeJitter(10)
);
var link = new Link(source, node);
nodes.push(node);
links.push(link);
nodesById[node.uuid] = node;
linksByNodeIds[source.uuid + ',' + node.uuid] = link;
}
graph.updateNodesAndLinks(nodes, links);
timeoutID = setTimeout(function() {
requestID = window.requestAnimationFrame(addRandomNode);
}, 200 + (Math.random() * 200));
}
/**
* Bind network
*/
function linkAllNodes() {
var pairs = [];
var pairsByIds = {};
nodes.forEach(function (nodeA) {
nodes.forEach(function (nodeB) {
if (nodeA.uuid === nodeB.uuid) return;
if (pairsByIds[nodeA.uuid + ',' + nodeB.uuid]) return;
if (pairsByIds[nodeB.uuid + ',' + nodeA.uuid]) return;
if (linksByNodeIds[nodeA.uuid + ',' + nodeB.uuid]) return;
if (linksByNodeIds[nodeB.uuid + ',' + nodeA.uuid]) return;
var pair = [nodeA, nodeB];
pairsByIds[nodeA.uuid + ',' + nodeB.uuid] = pair;
pairs.push(pair);
});
});
pairs = Utilities.shuffleArr(pairs);
function linkPair() {
var pair = pairs.pop();
var nodeA = pair[0];
var nodeB = pair[1];
var link = new Link(nodeA, nodeB);
links.push(link);
linksByNodeIds[nodeA.uuid + ',' + nodeB.uuid] = link;
graph.updateNodesAndLinks(nodes, links);
}
function timeLoop() {
linkPair();
timeoutID = setTimeout(function() {
requestID = window.requestAnimationFrame(timeLoop);
}, 600 + (Math.random() * 600));
}
timeLoop();
}
/**
* Beginning
*/
timeoutID = setTimeout(function() {
requestID = window.requestAnimationFrame(addRandomNode);
}, 600);
/**
* End
*/
$scope.$on('$destroy', function () {
clearTimeout(timeoutID);
window.cancelAnimationFrame(requestID);
});
}]);
})();
(function() {
angular.module('wikitree.session', [
'wikitree.session.graph',
'wikitree.session.menu',
'wikitree.session.reader',
'wikitree.session.resizer'
]);
})();
(function() {
angular.module('wikitree.session').
controller('session_controller',
[ '$scope'
, 'Search'
, 'Sessions'
, 'Utilities'
, 'init_session'
, function ($scope, Search, Sessions, Utilities, init_session) {
var session = this;
/**
* Session state
*/
var id = init_session.uuid;
// history
var current_node_id = init_session.data.current_node_id;
var prev_stack = init_session.data.prev_stack;
var next_stack = init_session.data.next_stack;
// nodes
var nodes = init_session.data.nodes;
var nodes_by_id = {};
var nodes_by_name = {};
// links
var links = init_session.data.links;
var links_by_id = {};
var links_by_node_ids = {};
// wait for load to broadcast update events
setTimeout(function () {
$scope.$apply(function () {
$scope.$broadcast('update:nodes+links');
$scope.$broadcast('update:currentnode');
});
}, 1);
// handle scope destroy
$scope.$on('$destroy', function () {
save();
});
// handle route change
$scope.$on('$routeChangeEnd', function () {
save();
});
// handle graph update
//$scope.$on('update:nodes+links', function () {
// save();
//});
// handle window close
$(window).on('beforeunload', function () {
save();
});
/**
* Create a node object
* @param {Object} args constructor argumentts
* @param {String} args.uuid unique id. Default: generate a new one
* @param {String} args.type node type (article | search | category)
* @param {String} args.title used if type is article | category
* @param {String} args.query used if type is search
* @constructor
*/
function Node (args) {
this.uuid = args.uuid || Utilities.makeUUID();
this.type = args.type; // article, category, search, note
this.name = args.name;
this.title = args.title;
this.query = args.query;
this.body = args.body;
// d3 force graph attributes
// https://github.com/mbostock/d3/wiki/Force-Layout#nodes
this.index = undefined; // the zero-based index of the node within the nodes array.
this.x = undefined; // the x-coordinate of the current node position.
this.y = undefined; // the y-coordinate of the current node position.
this.px = undefined; // the x-coordinate of the previous node position.
this.py = undefined; // the y-coordinate of the previous node position.
this.fixed = undefined; // a boolean indicating whether node position is locked.
this.weight = undefined; // the node weight; the number of associated links.
}
/**
* Add a node to the session
* @param {Object} args see Node class for more information
* @returns {Node} new Node object
*/
function add_node (args) {
var node = new Node({
type: args.type,
name: args.name,
title: args.title,
query: args.query
});
nodes.push(node);
nodes_by_id[node.uuid] = node;
if (node.type !== 'note') {
nodes_by_name[node.name] = node;
}
return node;
}
/**
* Create a link object
* @param {Object} args
* @param {String} args.uuid unique id. Default: generate a new one
* @param {Number} args.sourceId id of source node
* @param {Number} args.targetId id of target node
* @param {Boolean} args.linkback if link is cyclical
* @constructor
*/
function Link (args) {
this.uuid = args.uuid || Utilities.makeUUID();
this.sourceId = args.sourceId;
this.targetId = args.targetId;
this.linkbackId = args.linkbackId;
// d3 force graph attributes
// https://github.com/mbostock/d3/wiki/Force-Layout#links
this.source = nodes_by_id[this.sourceId];
this.target = nodes_by_id[this.targetId];
}
/**
* Create a link between two nodes
* @param {Number} tgt_node_id id of target node
* @param {Number} src_node_id id of source node
*/
function link (src_node_id, tgt_node_id) {
var tgt_node = nodes_by_id[tgt_node_id];
var src_node = nodes_by_id[src_node_id];
// no self-referencing nodes
if (tgt_node_id === src_node_id) return;
if ((src_node.x || src_node.y) && !(tgt_node.x || tgt_node.y)) {
tgt_node.x = src_node.x + Utilities.makeJitter(10);
tgt_node.y = src_node.y + Utilities.makeJitter(10);
}
if (links_by_node_ids[src_node_id] &&
links_by_node_ids[src_node_id][tgt_node_id]) {
// it exists, we're done
} else if (links_by_node_ids[tgt_node_id] &&
links_by_node_ids[tgt_node_id][src_node_id]) {
// add node with linkback
add_link(
src_node_id,
tgt_node_id,
links_by_node_ids[tgt_node_id][src_node_id].uuid
);
} else {
// add node WITHOUT linkback
add_link(
src_node_id,
tgt_node_id,
null
);
}
}
function removeLink (sourceId, targetId) {
if (!links_by_node_ids[sourceId]) return null;
var link = links_by_node_ids[sourceId][targetId];
if (!link) return null;
links = links.filter(function (l) {
return l.uuid !== link.uuid
});
delete links_by_node_ids[sourceId][targetId];
delete links_by_id[link.uuid];
}
/**
* Add a link to the session
* @param {Number} source_id ID of source node
* @param {Number} target_id ID of target node
* @param linkback
*/
function add_link (source_id, target_id, linkbackId) {
var link = new Link({
sourceId: source_id,
targetId: target_id,
linkbackId: linkbackId
});
links.push(link);
if (!links_by_node_ids[source_id]) links_by_node_ids[source_id] = {};
links_by_node_ids[source_id][target_id] = link;
links_by_id[link.uuid] = link;
}
/**
* Scope interface
*/
/**
* Get the current node
* @returns {Node}
*/
session.get_current_node = function () {
return nodes_by_id[current_node_id];
};
/**
* Set the currently selected graph node
* @param {String} nodeId
*/
session.set_current_node_id = function (nodeId) {
// make sure we're not already here
if (current_node_id === nodeId) return null;
// as with browser history,
// when jumping to new page
// add current to prev stack
// and flush out next stack
if (current_node_id) {
prev_stack.push(current_node_id);
}
next_stack = [];
current_node_id = nodeId;
$scope.$broadcast('update:currentnode');
};
/**
* Update a note node
*/
session.updateNoteNodeContent = function (nodeId, name, body) {
var node = nodes_by_id[nodeId];
if (!node) return;
node.name = name;
node.body = body;
$scope.$broadcast('update:note-node-content', node);
};
/**
* Get session nodes
* @returns {Array} Copy of nodes array
*/
session.get_nodes = function () {
return nodes.slice();
};
/**
* Get session links
* @returns {Array} Copy of links array
*/
session.get_links = function () {
return links.slice();
};
session.getNode = function (node_id) {
return nodes_by_id[node_id];
};
session.getLink = function (link_id) {
return links_by_id[link_id]
}
/**
* Whether session history can be advanced
* @returns {Boolean}
*/
session.has_forward = function () {
return !!next_stack.length;
};
/**
* Whether session history can be moved backwards
* @returns {boolean}
*/
session.has_backward = function () {
return !!prev_stack.length;
};
/**
* Select the session node as current
* @returns {Number} id of new current node
*/
session.go_backward = function () {
if (!prev_stack.length) return null;
next_stack.push(current_node_id);
current_node_id = prev_stack.pop();
$scope.$broadcast('update:currentnode');
};
/**
* Select the next session node as current
* @returns {Number} id of new current node
*/
session.go_forward = function () {
if (!next_stack.length) return null;
prev_stack.push(current_node_id);
current_node_id = next_stack.pop();
$scope.$broadcast('update:currentnode');
};
/**
* Remove a node
* @param {Number} nodeId
*/
session.removeNode = function (nodeId) {
// validate existence
var node = nodes_by_id[nodeId];
if (!node) return;
// remove from history ////////////////////////////////////////
prev_stack = prev_stack
.filter(function (id) {
return id !== nodeId
});
next_stack = next_stack
.filter(function (id) {
return id !== nodeId
});
// find a new current node?
if (current_node_id === nodeId) {
if (prev_stack.length) {
// try previous first
current_node_id = prev_stack.pop();
} else if (next_stack.length) {
// how about next
current_node_id = next_stack.pop();
} else {
// uh oh
current_node_id = null;
}
}
// remove from nodes //////////////////////////////////////////
nodes = nodes.filter(function (n) {
return n.uuid !== node.uuid
});
delete nodes_by_id[node.uuid];
if (node.type !== 'note') {
delete nodes_by_name[node.name];
}
// remove from links //////////////////////////////////////////
// remove any links with node from array
links = links.filter(function (link) {
return link.sourceId !== nodeId && link.targetId !== nodeId
});
// remove any references by node id
delete links_by_node_ids[nodeId];
Object.keys(links_by_node_ids).forEach(function (sourceId) {
delete links_by_node_ids[sourceId][nodeId];
});
// alert the media
$scope.$broadcast('update:nodes+links');
$scope.$broadcast('update:currentnode');
};
/**
* Remove a pair of links
* @param {Number} linkId
*/
session.removeLinkPair = function (linkId) {
var link = links_by_id[linkId];
if (!link) return;
var nodeA = link.source;
var nodeB = link.target;
// remove both directions
removeLink(nodeA.uuid, nodeB.uuid);
removeLink(nodeB.uuid, nodeA.uuid);
$scope.$broadcast('update:nodes+links');
};
// the big one
/**
* Process a search, adding nodes and links as needed
* @param {String} term search term
* @param {Number} src_node_id ID of source node
* @param {Boolean} no_set_current whether to set new node as current
* @param {Boolean} isSearch whether this should go straight to search results
*/
session.do_search = function (term, src_node_id, no_set_current, isSearch) {
var start_time = Date.now();
if (!(term && term.length)) return;
var search;
if (isSearch) {
search = Search.findOrAddSearch(term);
} else {
search = Search.findOrAddArticle(term);
}
search.then(function (result) {
// no result?
if (!result) {
alert('Sorry, something went wrong for "' + term + '"');
return;
}
// should we make a new node or get an existing one?
var node = (nodes_by_name[result.name])
? nodes_by_name[result.name]
: add_node(result);
// does our node need to be linked?
if (src_node_id) {
link(src_node_id, node.uuid);
}
$scope.$broadcast('update:nodes+links');
if (!no_set_current) {
session.set_current_node_id(node.uuid);
$scope.$broadcast('update:currentnode');
}
var end_time = Date.now();
}).
catch(function (err) {
});
};
session.addNewNoteNode = function () {
var node = add_node({ type: 'note' });
$scope.$broadcast('update:nodes+links');
return node;
};
session.addLink = function (sourceId, targetId) {
link(sourceId, targetId);
$scope.$broadcast('update:nodes+links');
};
/**
* Begin a session
*/
(function activate() {
if (init_session.new) {
session.do_search(init_session.term, null, null, init_session.search);
session.new = false;
}
nodes.forEach(function (node) {
nodes_by_id[node.uuid] = node;
if (node.type !== 'note') {
nodes_by_name[node.name] = node;
}
});
links.forEach(function (link) {
var sourceId = link.sourceId;
var targetId = link.targetId;
link.source = nodes_by_id[sourceId];
link.target = nodes_by_id[targetId];
links_by_id[link.uuid] = link;
if (!links_by_node_ids[sourceId]) links_by_node_ids[sourceId] = {};
links_by_node_ids[sourceId][targetId] = link;
});
})()
/**
* Save a session
*/
function save () {
Sessions.save(id, {
current_node_id: current_node_id,
prev_stack: prev_stack,
next_stack: next_stack,
nodes: nodes,
links: links
});
}
}]);
})();
(function() {
angular.module('wikitree.session.menu', [
'wikitree.session.menu.session_tile'
]);
})();
(function() {
angular.module('wikitree.session.menu').
controller('menuController', [
'$rootScope',
'$scope',
'$location',
'Search',
'Sessions',
function($rootScope, $scope, $location, Search, Sessions) {
$scope.sessions = Sessions.index;
$scope.active = Sessions.active;
$scope.$watch(function () {
return Sessions.active;
}, function (value) {
$scope.active = value;
});
$scope.open = false;
$scope.goHome = function() {
$location.path('/welcome');
};
$scope.toggleMenu = function () {
$scope.open = !$scope.open;
if ($scope.open) {
$rootScope.$broadcast('menu:open');
} else {
$rootScope.$broadcast('menu:close');
}
};
$scope.sortableOptions = {
update: function(e, ui) {
$scope.$broadcast('session:cancel_edit');
$rootScope.$broadcast('session:sort', {
start: ui.item.sortable.index,
stop: ui.item.sortable.dropindex
});
}
};
$scope.addNoteNode = function () {
$rootScope.$broadcast('request:graph:add_note_node');
};
$scope.locateCurrentNode = function () {
$rootScope.$broadcast('request:graph:locate_current_node');
};
}]);
})();
(function() {
angular.module('wikitree.session.menu').
directive('menu', [function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'js/angular/session/menu/menu.template.html',
controller: 'menuController'
}
}]);
})();
(function() {
angular.module('wikitree.session.menu.session_tile', [
'angularMoment',
'ui.sortable'
]);
})();
(function() {
angular.module('wikitree.session.menu.session_tile').
directive('enterpress', function () {
return {
link: function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.enterpress);
});
event.preventDefault();
}
});
}
}
});
})();
(function() {
angular.module('wikitree.session.menu.session_tile').
directive('escpress', [function () {
return {
link: function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 27) {
scope.$apply(function () {
scope.$eval(attrs.escpress);
});
event.preventDefault();
}
});
}
}
}]);
})();
(function() {
angular.module('wikitree.session.menu.session_tile').
directive('focus', ['$timeout', function($timeout) {
return {
scope : {
trigger : '@focus'
},
link : function(scope, element) {
scope.$watch('trigger', function(value) {
if (value === "true") {
$timeout(function() {
element[0].focus();
});
}
});
}
};
}]);
})();
(function() {
angular.module('wikitree.session.menu.session_tile').
controller('sessionController', ['$scope', '$location', 'Sessions', function($scope, $location, Sessions) {
$scope.editing = false;
$scope.edit = function() {
if (!$scope.editing) {
$scope.$parent.$broadcast('session:cancel_edit');
}
$scope.editing = !$scope.editing;
$scope.$parent.$broadcast('focus');
};
$scope.cancel_edit = function () {
$scope.$parent.$broadcast('session:cancel_edit');
};
$scope.$on('session:cancel_edit', function() {
$scope.session.rename = $scope.session.name;
$scope.editing = false;
});
$scope.select = function(idx) {
//Sessions.restore(idx);
$scope.$parent.$broadcast('session:cancel_edit');
$location.path('/session/'+$scope.session.uuid);
};
$scope.delete = function(idx) {
Sessions.delete(idx);
$scope.$parent.$broadcast('session:cancel_edit');
};
$scope.rename = function() {
$scope.session.name = $scope.session.rename;
$scope.session.rename = $scope.session.name;
$scope.editing = false;
};
}]);
})();
(function() {
angular.module('wikitree.session.menu.session_tile').
directive('session', [function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'js/angular/session/menu/session_tile/session_tile.template.html',
controller: 'sessionController'
}
}]);
})();
(function() {
angular.module('wikitree.session.reader', []);
})();
(function() {
angular.module('wikitree.session.reader').
controller('readerController', [
'$rootScope',
'$scope',
'Resizer',
'Loading',
'Sessions',
'Articles',
'Searches',
'Categories',
function($rootScope, $scope, Resizer, Loading, Sessions, Articles, Searches, Categories) {
// for reader width
$scope.readerWidth = Resizer.size + 'px';
// for frame node load
$scope.currentNodeName = null;
$scope.missedFrameUpdate = false;
$scope.hasReferences = false;
// for loading indicator
$scope.loadingCount = Loading.count;
// for prev/next buttons
$scope.hasBackward = $scope.session.has_backward();
$scope.hasForward = $scope.session.has_forward();
// keep history buttons updated
$scope.$on('update:currentnode', function () {
$scope.hasBackward = $scope.session.has_backward();
$scope.hasForward = $scope.session.has_forward();
});
// keep loading indicator updated
$scope.$on('mediawikiapi:loadstart', function () {
$scope.loadingCount = Loading.count;
});
$scope.$on('mediawikiapi:loadend', function () {
$scope.loadingCount = Loading.count;
});
// keep iframe content updated
$scope.$on('update:currentnode', function () {
$scope.updateFrameNode();
});
// keep reader width updated
$scope.$on('split:resize', function (e, data) {
$scope.readerWidth = Resizer.size + 'px';
});
/**
* Reader controls
*/
$scope.historyBackward = function () {
$scope.session.go_backward();
};
$scope.historyForward = function () {
$scope.session.go_forward();
};
$scope.openSourceArticle = function () {
var node = $scope.session.get_current_node();
if (!(node && node.name)) return;
var url = '';
switch (node.type) {
case 'article':
url = 'https://en.wikipedia.org/wiki/';
url += encodeURIComponent(node.title);
break;
case 'search':
url = 'http://en.wikipedia.org/w/index.php?fulltext=1&search=';
url += encodeURIComponent(node.query);
break;
}
var link = document.createElement('a');
link.target = '_blank';
link.href = url;
link.click();
};
$scope.scrollToReferences = function () {
if (!$scope.frameWindow) return;
$scope.frameWindow.scrollToReferences();
};
/**
* Reader node content
*/
$scope.updateFrameNode = function () {
// make sure we got iframe
if (!$scope.frameWindow) {
$scope.missedFrameUpdate = true;
return;
}
// grab current node
//var node = CurrentSession.getCurrentNode();
var node = $scope.session.get_current_node();
// make sure we got node
if (!node) {
// TEMP TODO FIXME NOTE WARN DANGER
// taking this out for capstone presentation
// $scope.currentNodeName = null;
// $scope.frameWindow.loadError(
// 'System error: could not find a current node'
// );
return;
}
// check if node already displayed
if ($scope.currentNodeName) {
if ($scope.currentNodeName === node.name) {
return;
}
}
/**
* Passed, load content
*/
// update current name
$scope.currentNodeName = node.name;
// save update
//Sessions.save();
// on iframe node load
function onLoad() {
// update reference check
$scope.hasReferences = $scope.frameWindow.checkForReferences();
}
// load node into iframe
switch (node.type) {
case 'category': loadCategory(node, onLoad); break;
case 'article': loadArticle(node, onLoad); break;
case 'search': loadSearch(node, onLoad); break;
}
};
function loadCategory(node, callback) {
Categories.getByTitle(node.title).
then(function (category) {
$scope.frameWindow.loadCategory(
category,
makeTitleCallback(node)
);
if (callback) callback(category);
}).
catch(function () {
$scope.frameWindow.loadError(
'System error: unable to load "' + node.title + '"'
);
});
}
function loadArticle(node, callback) {
Articles.getByTitle(node.title).
then(function (article) {
$scope.frameWindow.loadArticle(
article,
makeTitleCallback(node)
);
if (callback) callback(article);
}).
catch(function () {
$scope.frameWindow.loadError(
'System error: unable to load article "' + node.title + '"'
);
});
}
function loadSearch(node, callback) {
Searches.getByQuery(node.query).
then(function (search) {
$scope.frameWindow.loadSearch(
search,
makeTitleCallback(node)
);
if (callback) callback(search);
}).
catch(function () {
$scope.frameWindow.loadError(
'System error: unable to load search "' + node.query + '"'
);
});
}
function makeTitleCallback(node) {
return function (title, noSetCurrent, isSearch) {
$scope.$apply(function () {
// user clicked an iframe title!
title = decodeURIComponent(title);
$scope.session.do_search(title, node.uuid, noSetCurrent, isSearch);
});
};
}
/**
* Load article if there is one
*/
if ($scope.session.get_current_node()) {
$scope.updateFrameNode();
}
}
]);
})();
(function() {
angular.module('wikitree.session.reader').
directive('reader', [function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'js/angular/session/reader/reader.template.html',
controller: 'readerController',
link: function(scope, element, attrs) {
// grab reference to iFrame's window object
// (gives us access to its global JS scope)
scope.frameWindow = null;
// be wary of race conditions...
element.find('iframe').
// ...add iframe load event
on('load', function () {
scope.frameWindow = this.contentWindow;
// check if frame called before existence
if (scope.missedFrameUpdate) {
scope.updateFrameNode();
}
}).
// ...THEN give it src url
attr('src', 'article-frame.html');
}
};
}]);
})();
(function() {
angular.module('wikitree.session.graph', []);
})();
(function () {
angular.module('wikitree.session.graph').
controller('graphController', [
'$scope',
'Resizer',
function ($scope, Resizer) {
// for graph position
$scope.positionRight = Resizer.size + 'px';
/**
* Global events
*/
// handle "locate current node" button
$scope.$on('request:graph:locate_current_node', function () {
var node = $scope.session.get_current_node();
$scope.graph.centerOnNode(node);
});
// handle "locate node" button
$scope.$on('request:graph:locate_node', function (e, node) {
$scope.graph.centerOnNode(node);
});
// handle "add note node" button
$scope.$on('request:graph:add_note_node', function () {
$scope.session.addNewNoteNode();
});
// handle map/reader split resize
$scope.$on('split:resize', function (e, data) {
$scope.positionRight = Resizer.size + 'px';
setTimeout(function () {
$scope.graph.updateSize();
}, 1);
});
// handle model update (nodes + links)
$scope.$on('update:nodes+links', function () {
var nodes = $scope.session.get_nodes();
var links = $scope.session.get_links();
$scope.graph.updateNodesAndLinks(nodes, links);
});
// handle model update (current node)
$scope.$on('update:currentnode', function () {
var node = $scope.session.get_current_node();
$scope.graph.updateCurrentNode(node);
});
// handle model update (note node content)
$scope.$on('update:note-node-content', function (e, node) {
$scope.graph.updateNoteNodeContent(node);
});
/**
* Scope methods
*/
$scope.setCurrentNode = function (nodeId) {
$scope.session.set_current_node_id(nodeId);
};
$scope.setCurrentNoteNode = function (nodeId) {
$scope.session.setCurrentNoteNodeId(nodeId);
};
$scope.removeNode = function (nodeId) {
var node = $scope.session.getNode(nodeId);
if (!node) return;
if (window.confirm('Remove the node "' + node.name + '" from your session?')) {
$scope.session.removeNode(node.uuid);
}
};
$scope.removeLink = function (linkId) {
var link = $scope.session.getLink(linkId);
if (!link) return;
var nodeA = link.source;
var nodeB = link.target;
if (window.confirm('Remove the link between "' + nodeA.name + '" and "' + nodeB.name + '" from your session?')) {
$scope.session.removeLinkPair(link.uuid);
}
};
$scope.addLink = function (sourceId, targetId) {
$scope.session.addLink(sourceId, targetId);
};
}
]);
})();
(function() {
angular.module('wikitree.session.graph').
directive('graph', [function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'js/angular/session/graph/graph.template.html',
controller: 'graphController',
link: function(scope, element) {
scope.graph = new ForceGraph(
element[0],
scope
);
scope.$broadcast('update:nodes+links');
scope.$broadcast('update:currentnode');
}
}
}]);
})();
(function() {
angular.module('wikitree.session.resizer', []);
})();
(function() {
angular.module('wikitree.session.resizer').
directive('resizer', [
'$rootScope',
'Resizer',
function($rootScope, Resizer) {
var link = function(scope, element, attrs) {
var $window = $(window);
var $resizer = $('#resizer');
var resizerWidth = $resizer.width();
function setRightSize(size) {
var winWidth = window.innerWidth;
// make sure size is reasonable
if (winWidth - size < Resizer.MIN_REMAINDER) return;
if (size < Resizer.MIN_SIZE) return;
// update measurements
Resizer.size = size;
Resizer.ratio = size / winWidth;
// tell the world
$rootScope.$broadcast('split:resize');
}
function fillElement() {
$resizer.css({
width: '100%',
left: 0,
right: 0
});
}
function restoreElement() {
$resizer.css({
width: '', // reset
left: '', // reset
right: Resizer.size - resizerWidth + 5
});
}
/**
* Initialize
*/
setRightSize(Resizer.ratio * window.innerWidth);
restoreElement();
/**
* Handle dragging
*/
// start drag
$resizer.on('mousedown', function (e) {
// fill screen to prevent iframe steal
scope.$apply(function () {
fillElement();
});
// handle drag on any movement
$window.on('mousemove', dragHandler);
// release drag handler on next mouseup
$window.one('mouseup', function (e) {
// put resizer back in place
scope.$apply(function () {
restoreElement();
});
// unbind drag event for now
$window.unbind('mousemove', dragHandler);
});
});
// during drag
function dragHandler(e) {
e.preventDefault();
scope.$apply(function () {
setRightSize(window.innerWidth - e.pageX);
});
}
/**
* Handle window resize
*/
$window.on('resize', function () {
scope.$apply(function () {
setRightSize(Resizer.ratio * window.innerWidth);
restoreElement();
});
});
};
return {
restrict: 'E',
replace: true,
templateUrl: 'js/angular/session/resizer/resizer.template.html',
link: link
}
}
]
);
})();
(function() {
angular.module('wikitree').
factory('Resizer', [
function () {
var Resizer = {};
Resizer.MIN_REMAINDER = 120;
Resizer.MIN_SIZE = 300;
Resizer.ratio = 3/5;
Resizer.size = Resizer.ratio * window.innerWidth;
return Resizer;
}
]
);
})();
(function() {
angular.module('wikitree').
factory('Articles', ['$q', '$http', '$rootScope', function($q, $http, $rootScope) {
/**
* Private
*/
var byTitle = {};
var byUnsafeTitle = {};
function Article(args) {
this.title = args.title;
this.content = args.content;
this.categories = args.categories;
}
//function getFromAPI(title) {
// var timestamp = Date.now();
// $rootScope.$broadcast('mediawikiapi:loadstart', timestamp);
//
// return $http.jsonp('https://en.wikipedia.org/w/api.php', {
// params: {
// action: 'parse',
// prop: 'text|categorieshtml|displaytitle',
// redirects: 'true',
// page: title,
// format: 'json',
// callback: 'JSON_CALLBACK'
// }
//
// }).then(function (data) {
// $rootScope.$broadcast('mediawikiapi:loadend', timestamp);
// if (data && data.parse && data.parse.title) {
// return data.parse;
// } else {
// throw "Article API error";
// }
//
// }).catch(function (err) {
// console.error(err);
// });
//
//
//}
function getFromAPI(title) {
var timestamp = Date.now();
return $q(function (resolve, reject) {
$rootScope.$broadcast('mediawikiapi:loadstart', timestamp);
$http.jsonp('https://en.wikipedia.org/w/api.php', {
params: {
action: 'parse',
prop: 'text|categorieshtml|displaytitle',
redirects: 'true',
page: title,
format: 'json',
callback: 'JSON_CALLBACK'
}
}).
success(function (data) {
$rootScope.$broadcast('mediawikiapi:loadend', timestamp);
if (data && data.parse && data.parse.title) {
resolve(data.parse);
} else {
console.error('Article API error', arguments);
reject(null);
}
}).
error(function () {
$rootScope.$broadcast('mediawikiapi:loadend', timestamp);
console.error('Article API error', arguments);
reject(null);
});
});
}
/**
* Public
*/
var Articles = {};
Articles.getByTitle = function (title) {
return $q(function (resolve, reject) {
if (byTitle[title]) {
resolve(byTitle[title]);
} else {
getFromAPI(title).
then(function (result) {
if (result) {
var article = new Article({
title: result.title,
content: result.text['*'],
categories: result.categorieshtml['*'],
displaytitle: result.displaytitle
});
byTitle[article.title] = article;
resolve(article);
} else {
// sucks
console.error('Article not found', title);
reject(null);
}
}).
catch(function () {
// sucks
console.error('Article API error', title, arguments);
reject(null);
});
}
});
};
// JUST for user input
Articles.getByUnsafeTitle = function (unsafeTitle) {
return $q(function (resolve, reject) {
if (byUnsafeTitle[unsafeTitle]) {
resolve(byUnsafeTitle[unsafeTitle]);
} else {
getFromAPI(unsafeTitle).
then(function (result) {
if (result) {
var article = new Article({
title: result.title,
content: result.text['*'],
categories: result.categorieshtml['*'],
displaytitle: result.displaytitle
});
byUnsafeTitle[unsafeTitle] = article;
byTitle[article.title] = article;
resolve(article);
} else {
// sucks
console.error('Article not found!', unsafeTitle);
reject(null);
}
}).
catch(function () {
// sucks
console.error('Article API error', unsafeTitle, arguments);
reject(null);
});
}
});
};
return Articles;
}]);
})();
(function() {
angular.module('wikitree').
factory('Categories', ['$q', '$http', '$rootScope', function($q, $http, $rootScope) {
/**
* Private
*/
var byTitle = {};
var byUnsafeTitle = {};
function Category(args) {
this.name = args.name;
this.title = args.title;
this.content = args.content;
this.categories = args.categories;
this.displaytitle = args.displaytitle;
this.subcategories = args.subcategories;
this.memberpages = args.memberpages;
}
function getFromAPI(title) {
var timestamp = Date.now();
return $q(function (resolve, reject) {
// fetch parsed content
var getPageContent = $http.jsonp('https://en.wikipedia.org/w/api.php', {
params: {
action: 'parse',
prop: 'text|categorieshtml|displaytitle',
redirects: 'true',
page: title,
format: 'json',
callback: 'JSON_CALLBACK'
}
});
// fetch subcategories
var getSubcategories = $http.jsonp('https://en.wikipedia.org/w/api.php', {
params: {
action: 'query',
list: 'categorymembers',
cmtype: 'subcat',
cmtitle: title,
cmlimit: 500,
format: 'json',
callback: 'JSON_CALLBACK'
}
});
// fetch member pages
var getMemberpages = $http.jsonp('https://en.wikipedia.org/w/api.php', {
params: {
action: 'query',
list: 'categorymembers',
cmtype: 'page',
cmtitle: title,
cmlimit: 500,
format: 'json',
callback: 'JSON_CALLBACK'
}
});
// wait for all calls to complete
$q.all([getPageContent, getSubcategories, getMemberpages]).
then(function (values) {
$rootScope.$broadcast('mediawikiapi:loadend', timestamp);
var page = values[0];
var subcategories = values[1];
var memberpages = values[2];
var result = {};
if (page &&
page.data &&
page.data.parse &&
page.data.parse.title) {
result.title = page.data.parse.title;
result.content = page.data.parse.text['*'];
result.categories = page.data.parse.categorieshtml['*'];
result.displaytitle = page.data.parse.displaytitle;
}
if (subcategories &&
subcategories.data &&
subcategories.data.query &&
subcategories.data.query.categorymembers &&
subcategories.data.query.categorymembers.length) {
result.subcategories = subcategories.data.query.categorymembers;
}
if (memberpages &&
memberpages.data &&
memberpages.data.query &&
memberpages.data.query.categorymembers &&
memberpages.data.query.categorymembers.length) {
result.memberpages = memberpages.data.query.categorymembers;
}
if (result.title) {
result.name = result.title.slice('Category:'.length);
resolve(result);
} else {
console.error('Category API error', arguments);
reject(null);
}
}).
catch(function () {
$rootScope.$broadcast('mediawikiapi:loadend', timestamp);
console.error('Category API error', arguments);
reject(null);
});
});
}
/**
* Public
*/
var Categories = {};
Categories.getByTitle = function (title) {
return $q(function (resolve, reject) {
if (byTitle[title]) {
resolve(byTitle[title]);
} else {
getFromAPI(title).
then(function (result) {
if (result) {
var category = new Category({
name: result.name,
title: result.title,
content: result.content,
categories: result.categories,
displaytitle: result.displaytitle,
subcategories: result.subcategories,
memberpages: result.memberpages
});
byTitle[category.title] = category;
resolve(category);
} else {
// sucks
console.error('Category not found', title);
reject(null);
}
}).
catch(function () {
// sucks
console.error('Category API error', title, arguments);
reject(null);
});
}
});
};
// JUST for user input
Categories.getByUnsafeTitle = function (unsafeTitle) {
return $q(function (resolve, reject) {
if (byUnsafeTitle[unsafeTitle]) {
resolve(byUnsafeTitle[unsafeTitle]);
} else {
getFromAPI(unsafeTitle).
then(function (result) {
if (result) {
var category = new Category({
name: result.name,
title: result.title,
content: result.content,
categories: result.categories,
displaytitle: result.displaytitle,
subcategories: result.subcategories,
memberpages: result.memberpages
});
byUnsafeTitle[unsafeTitle] = category;
byTitle[category.title] = category;
resolve(category);
} else {
// sucks
console.error('Category not found!', unsafeTitle);
reject(null);
}
}).
catch(function () {
// sucks
console.error('Category API error', unsafeTitle, arguments);
reject(null);
});
}
});
};
return Categories;
}]);
})();
(function() {
angular.module('wikitree').
factory('Loading', [
'$rootScope',
function ($rootScope) {
var Loading = {};
Loading.count = 0;
$rootScope.$on('mediawikiapi:loadstart', function () {
Loading.count++;
});
$rootScope.$on('mediawikiapi:loadend', function () {
Loading.count--;
// protect from bad timing
if (Loading.count < 0) {
Loading.count = 0;
}
});
return Loading;
}
]
);
})();
(function() {
angular.module('wikitree').
factory('Searches', ['$q', '$http', '$rootScope', function($q, $http, $rootScope) {
/**
* Private
*/
var byQuery = {};
function Search(args) {
this.query = args.query;
this.suggestion = args.suggestion;
this.totalhits = args.totalhits;
this.results = args.results;
}
function getFromAPI(query) {
var timestamp = Date.now();
return $q(function (resolve, reject) {
$rootScope.$broadcast('mediawikiapi:loadstart', timestamp);
$http.jsonp('https://en.wikipedia.org/w/api.php', {
params: {
action: 'query',
list: 'search',
srprop: 'titlesnippet|snippet|size|wordcount|timestamp',
srsearch: query,
srlimit: 50,
format: 'json',
callback: 'JSON_CALLBACK'
}
}).
success(function (data) {
$rootScope.$broadcast('mediawikiapi:loadend', timestamp);
if (data && data.query && data.query.searchinfo) {
resolve(data.query);
} else {
console.error('Search API error', arguments);
reject(null);
}
}).
error(function () {
$rootScope.$broadcast('mediawikiapi:loadend', timestamp);
console.error('Search API error', arguments);
reject(null);
});
});
}
/**
* Public
*/
var Searches = {};
Searches.getByQuery = function (query) {
return $q(function (resolve, reject) {
if (byQuery[query]) {
resolve(byQuery[query]);
} else {
getFromAPI(query).
then(function (result) {
if (result) {
var search = new Search({
query: query,
suggestion: {
text: result.searchinfo.suggestion,
html: result.searchinfo.suggestionsnippet
},
totalhits: result.totalhits,
results: result.search
});
byQuery[search.query] = search;
resolve(search);
} else {
// sucks
console.error('Search failed', query);
reject(null);
}
}).
catch(function () {
// sucks
console.error('Search API error', query, arguments);
reject(null);
});
}
});
};
return Searches;
}]);
})();
| mit |
wktk/rpxem | lib/rpxem/stack.rb | 869 | module RPxem
class Stack < Array
def initialize(*args, &block)
super(*args, &block)
simple_check(*self)
end
def push(*args, &block)
simple_check(*args)
super(*args, &block)
end
def unshift(*args, &block)
simple_check(*args)
super(*args, &block)
end
def <<(*args, &block)
simple_check(*args)
super(*args, &block)
end
def []=(*args, &block)
super(*args, &block)
simple_check(*self)
end
def insert(*args, &block)
super(*args, &block)
simple_check(*self)
end
def map!(*args, &block)
super(*args, &block)
simple_check(*self)
end
private
def simple_check(*args)
args.each do |arg|
if (!arg.is_a? Integer)
raise ArgumentError.new 'Argument must be Integer'
end
end
end
end
end
| mit |
eltonjuan/eureka-js-client | test/eureka-client.test.js | 7859 | import sinon from 'sinon';
import {expect} from 'chai';
import {Eureka} from '../src/eureka-client';
describe('Eureka client', () => {
describe('Eureka()', () => {
it('should throw an error if no config is found', () => {
function fn() {
return new Eureka();
}
expect(fn).to.throw();
});
it('should construct with the correct configuration values', () => {
function shouldThrow() {
return new Eureka();
}
function noApp() {
return new Eureka({
instance: {
vipAddress: true,
port: true,
dataCenterInfo: {
name: 'MyOwn'
}
},
eureka: {
host: true,
port: true
}
});
}
function shouldWork() {
return new Eureka({
instance: {
app: true,
vipAddress: true,
port: true,
dataCenterInfo: {
name: 'MyOwn'
}
},
eureka: {
host: true,
port: true
}
});
}
expect(shouldThrow).to.throw();
expect(noApp).to.throw(/app/);
expect(shouldWork).to.not.throw();
});
});
describe('validateConfig()', () => {
let config;
beforeEach(() => {
config = {
instance: {app: 'app', vipAddress: '1.2.2.3', port: 9999, dataCenterInfo: 'Amazon'},
eureka: {host: '127.0.0.1', port: 9999}
};
});
it('should throw an exception with a missing instance.app', () => {
function badConfig() {
delete config.instance.app;
return new Eureka(config);
}
expect(badConfig).to.throw(TypeError);
});
it('should throw an exception with a missing instance.vipAddress', () => {
function badConfig() {
delete config.instance.vipAddress;
return new Eureka(config);
}
expect(badConfig).to.throw(TypeError);
});
it('should throw an exception with a missing instance.port', () => {
function badConfig() {
delete config.instance.port;
return new Eureka(config);
}
expect(badConfig).to.throw(TypeError);
});
it('should throw an exception with a missing instance.dataCenterInfo', () => {
function badConfig() {
delete config.instance.dataCenterInfo;
return new Eureka(config);
}
expect(badConfig).to.throw(TypeError);
});
it('should throw an exception with a missing eureka.host', () => {
function badConfig() {
delete config.eureka.host;
return new Eureka(config);
}
expect(badConfig).to.throw(TypeError);
});
it('should throw an exception with a missing eureka.port', () => {
function badConfig() {
delete config.eureka.port;
return new Eureka(config);
}
expect(badConfig).to.throw(TypeError);
});
});
describe('getInstancesByAppId()', () => {
let client, config;
beforeEach(() => {
config = {
instance: {app: 'app', vipAddress: '1.2.2.3', port: 9999, dataCenterInfo: 'Amazon'},
eureka: {host: '127.0.0.1', port: 9999}
};
client = new Eureka(config);
});
it('should throw an exception if no appId is provided', () => {
function noAppId() {
client.getInstancesByAppId();
}
expect(noAppId).to.throw(Error);
});
it('should return a list of instances if appId is registered', () => {
let appId = 'theservicename'.toUpperCase();
let expectedInstances = [{host: '127.0.0.1'}];
client.cache.app[appId] = expectedInstances;
let actualInstances = client.getInstancesByAppId(appId);
expect(actualInstances).to.equal(expectedInstances);
});
it('should throw an error if no instances were found for given appId', () => {
let appId = 'theservicename'.toUpperCase();
client.cache.app[appId] = null;
function shouldThrow() {
client.getInstancesByAppId(appId)
}
expect(shouldThrow).to.throw();
});
});
describe('getInstancesByVipAddress()', () => {
let client, config;
beforeEach(() => {
config = {
instance: {app: 'app', vipAddress: '1.2.3.4', port: 9999, dataCenterInfo: 'Amazon'},
eureka: {host: '127.0.0.1', port: 9999}
};
client = new Eureka(config);
});
it('should throw an exception if no vipAddress is provided', () => {
function noVipAddress() {
client.getInstancesByVipAddress();
}
expect(noVipAddress).to.throw(Error);
});
it('should return a list of instances if vipAddress is registered', () => {
let vipAddress = 'the.vip.address';
let expectedInstances = [{host: '127.0.0.1'}];
client.cache.vip[vipAddress] = expectedInstances;
let actualInstances = client.getInstancesByVipAddress(vipAddress);
expect(actualInstances).to.equal(expectedInstances);
});
it('should throw an error if no instances were found for given vipAddress', () => {
let vipAddress = 'the.vip.address';
client.cache.vip[vipAddress] = null;
function shouldThrow() {
client.getInstancesByVipAddress(vipAddress)
}
expect(shouldThrow).to.throw();
});
});
describe('transformRegistry()', () => {
let client, config, registry, app1, app2, transformSpy;
beforeEach(() => {
config = {
instance: {app: 'app', vipAddress: '1.2.3.4', port: 9999, dataCenterInfo: 'Amazon'},
eureka: {host: '127.0.0.1', port: 9999}
};
registry = {
applications: {application: {}}
};
app1 = {};
app2 = {};
client = new Eureka(config);
transformSpy = sinon.stub(client, 'transformApp');
});
afterEach(() => {
transformSpy.restore();
});
it('should throw an error if no registry is provided', () => {
function noRegistry() {
client.transformRegistry();
}
expect(noRegistry).to.throw();
});
it('should return clear the cache if no applications exist', () => {
registry.applications.application = null;
client.transformRegistry(registry);
expect(client.cache.vip).to.be.empty;
expect(client.cache.app).to.be.empty;
});
it('should transform a registry with one app', () => {
registry.applications.application = app1;
client.transformRegistry(registry);
expect(transformSpy.callCount).to.equal(1);
});
it('should transform a registry with two or more apps', () => {
registry.applications.application = [app1, app2];
client.transformRegistry(registry);
expect(transformSpy.callCount).to.equal(2);
});
});
describe('transformApp()', () => {
let client, config, app, instance1, instance2, theVip;
beforeEach(() => {
config = {
instance: {app: 'app', vipAddress: '1.2.3.4', port: 9999, dataCenterInfo: 'Amazon'},
eureka: {host: '127.0.0.1', port: 9999}
};
client = new Eureka(config);
theVip = 'theVip';
instance1 = {host: '127.0.0.1', port: 1000, vipAddress: theVip};
instance2 = {host: '127.0.0.2', port: 2000, vipAddress: theVip};
app = {name: 'theapp'};
});
it('should transform an app with one instance', () => {
app.instance = instance1;
client.transformApp(app);
expect(client.cache.app[app.name.toUpperCase()].length).to.equal(1);
expect(client.cache.vip[theVip].length).to.equal(1);
});
it('should transform an app with two or more instances', () => {
app.instance = [instance1, instance2];
client.transformApp(app);
expect(client.cache.app[app.name.toUpperCase()].length).to.equal(2);
expect(client.cache.vip[theVip].length).to.equal(2);
});
});
});
| mit |
bkahlert/seqan-research | raw/pmsb13/pmsb13-data-20130530/sources/fjt74l9mlcqisdus/2013-05-06T11-56-23.922+0200/sandbox/my_sandbox/apps/blastX/test_file.cpp | 8222 | // BLASTX IMPLEMENTIERUNG VON ANNKATRIN BRESSIN UND MARJAN FAIZI
// SOFTWAREPROJEKT VOM 2.4. - 29.5.2012
// VERSION VOM 04.MAI.2013
#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include "own_functions.h"
// TEST HASH FUNKTION --------------------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_hash)
{
// normaler Eingabewert fuer hash funktion
int result = hash(1,0,3);
SEQAN_ASSERT(result>=0 && result<=63);
// zu hoher Eingabewert in hash funktion
result = hash(4,7,900);
SEQAN_ASSERT_EQ(result,-1);
// zu niedriger Eingabewert in hash funktion
result = hash(4,-7,-900);
SEQAN_ASSERT_EQ(result,-1);
// Eingabewert N
result = hash(4,0,1);
SEQAN_ASSERT_EQ(result,-1);
// cast von normalen char
result = hash((int)'G',(int)'K',(int)'J');
SEQAN_ASSERT_EQ(result,-1);
}
// TEST HASH FUNKTION --------------------------------------------------------------------------------------------------
// TEST GET AMINOACID POS FUNKTION -------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_get_amino_acid_pos)
{
int result;
// alle Moeglichen Eingabewerte fuer get_amino_acid_pos
for (int i=0;i<=63;++i){
result = get_Amino_Acid_Pos(i);
SEQAN_ASSERT(result>=0 && result<=21);
}
// alle Moegliche und nicht Moegliche Eingabewerte
for (int i=-100;i<=100;++i){
result = get_Amino_Acid_Pos(i);
SEQAN_ASSERT(result>=0 && result<=21 || result==-1);
}
// Punktprobe
result = get_Amino_Acid_Pos(7); // Threonin Eingabe
SEQAN_ASSERT_EQ(result,16);
}
// TEST GET AMINOACID POS FUNKTION -------------------------------------------------------------------------------------
// TEST GET AMINOACID POS UND HASH FUNKTION ----------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_apps_get_amino_acid_pos_and_hash)
{
// Punkttest hash funktion und get_amino_acid_pos
int hash_value = hash(0,0,0); // Lysin
int result = get_Amino_Acid_Pos(hash_value);
SEQAN_ASSERT(result==11);
hash_value = hash(3,3,3); // Phenylalanin
result = get_Amino_Acid_Pos(hash_value);
SEQAN_ASSERT(result==13);
hash_value = hash(1,0,3); // Histidin
result = get_Amino_Acid_Pos(hash_value);
SEQAN_ASSERT(result==8);
hash_value = hash(0,2,3); // Serin
result = get_Amino_Acid_Pos(hash_value);
SEQAN_ASSERT(result==15);
hash_value = hash(3,2,0); // stop
result = get_Amino_Acid_Pos(hash_value);
SEQAN_ASSERT(result==20);
}
// TEST GET AMINOACID POS UND HASH FUNKTION ----------------------------------------------------------------------------
// TEST GET_TRANSLATE_FROM_CODON ---------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_get_translate_from_codon)
{
// Punkttest für gültige Eingabeparameter
int x = 0;
StrSetSA alphabet = GET_ALPHABET(x,x);
String<Dna> triplet = "GCT";
int result = get_translate_from_codon(triplet,alphabet[0]); // Alanin
SEQAN_ASSERT(result==4);
triplet = "CTA";
result = get_translate_from_codon(triplet,alphabet[0]); // Leucin
SEQAN_ASSERT(result==4);
triplet = "GTT";
result = get_translate_from_codon(triplet,alphabet[0]); // Valin
SEQAN_ASSERT(result==4);
triplet = "TGG";
result = get_translate_from_codon(triplet,alphabet[0]); // Tryptophan
SEQAN_ASSERT(result==5);
triplet = "GAA";
result = get_translate_from_codon(triplet,alphabet[0]); // Glutaminsäure
SEQAN_ASSERT(result==2);
}
// TEST GET_TRANSLATE_FROM_CODON ---------------------------------------------------------------------------------------
// TEST TRANSLATE ------------------------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_translate)
{
StrSetSA trans_reads;
int x = 0;
StrSetSA alphabet = GET_ALPHABET(x,x);
String<Dna> read = "ACGATGACGATCAGTACGATACAGTAC";
for (int frame=0;frame<6;++frame){
int result = translate(trans_reads,read,alphabet[0],frame);
SEQAN_ASSERT_EQ(result,0);
SEQAN_ASSERT_EQ(length(trans_reads),frame+1);
}
clear(trans_reads);
read = "";
for (int frame=0;frame<6;++frame){
int result = translate(trans_reads,read,alphabet[0],frame);
SEQAN_ASSERT_EQ(result,0);
SEQAN_ASSERT_EQ(length(trans_reads),frame+1);
}
}
// TEST TRANSLATE ------------------------------------------------------------------------------------------------------
// TEST TRANSLATE_READS ------------------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_translate_reads)
{
StrSetSA trans_reads;
int x = 0;
StrSetSA alphabet = GET_ALPHABET(x,x);
StringSet<String<Dna>> read;
appendValue(read,"ACGATGCAGTCAGTGTCA");
appendValue(read,"GTGATCGTACGTCAGGTA");
int result = translate_reads(read,trans_reads,alphabet[0]);
SEQAN_ASSERT_EQ(length(trans_reads),12);
SEQAN_ASSERT_EQ(trans_reads[0],"QRQQCQ");
SEQAN_ASSERT_EQ(trans_reads[1],"DRQQR");
SEQAN_ASSERT_EQ(trans_reads[2],"NCCQC");
SEQAN_ASSERT_EQ(trans_reads[3],"EDECDD");
SEQAN_ASSERT_EQ(trans_reads[4],"NQNRC");
SEQAN_ASSERT_EQ(trans_reads[5],"QCQCQ");
SEQAN_ASSERT_EQ(trans_reads[6],"CCCDQC");
SEQAN_ASSERT_EQ(trans_reads[7],"EQQCD");
SEQAN_ASSERT_EQ(trans_reads[8],"NDQQC");
SEQAN_ASSERT_EQ(trans_reads[9],"QCQQND");
SEQAN_ASSERT_EQ(trans_reads[10],"QEDQC");
SEQAN_ASSERT_EQ(trans_reads[11],"CNCDQ");
}
// TEST TRANSLATE_READS ------------------------------------------------------------------------------------------------
// TEST TRANSLATE_DATABASE ---------------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_translate_database)
{
StrSetSA trans_proteine;
int x = 0;
StrSetSA alphabet = GET_ALPHABET(x,x);
StrSetSA proteine;
appendValue(proteine,"QNEVGNATILNVWPF");
appendValue(proteine,"ARNDCQEGHILKMFPSTWYV");
int result = translate_database(trans_proteine,proteine,alphabet[0]);
SEQAN_ASSERT_EQ(length(trans_proteine),2);
SEQAN_ASSERT_EQ(trans_proteine[0],"QQNCCQCQCCQCQCC");
SEQAN_ASSERT_EQ(trans_proteine[1],"CDQNRQNCDCCDRCCQQQQC");
}
// TEST TRANSLATE_DATABASE ---------------------------------------------------------------------------------------------
// TEST APPEND_TO_MATCH_FOUND ------------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_append_to_match_found)
{
Match_found test;
Pair<unsigned int,unsigned int> x (4,5);
Pair<unsigned int,unsigned int> y (0,6);
append_to_match_found(test,1,2,3,x,y);
SEQAN_ASSERT_EQ(test.position_read,1);
SEQAN_ASSERT_EQ(test.begin_read,2);
SEQAN_ASSERT_EQ(test.end_read,3);
SEQAN_ASSERT_EQ(test.position_protein,4);
SEQAN_ASSERT_EQ(test.begin_protein,5);
SEQAN_ASSERT_EQ(test.end_protein,6);
}
// TEST APPEND_TO_MATCH_FOUND ------------------------------------------------------------------------------------------
// TEST APPEND_TO_MATCH_FOUND ------------------------------------------------------------------------------------------
SEQAN_DEFINE_TEST(test_my_app_find_matches)
{
}
// TEST APPEND_TO_MATCH_FOUND ------------------------------------------------------------------------------------------
// TEST DURCHLAUF ------------------------------------------------------------------------------------------------------
// Normale eingabe
SEQAN_BEGIN_TESTSUITE(test_my_app_funcs)
{
SEQAN_CALL_TEST(test_my_app_hash);
SEQAN_CALL_TEST(test_my_app_get_amino_acid_pos);
SEQAN_CALL_TEST(test_my_apps_get_amino_acid_pos_and_hash);
SEQAN_CALL_TEST(test_my_app_get_translate_from_codon);
SEQAN_CALL_TEST(test_my_app_translate);
SEQAN_CALL_TEST(test_my_app_translate_reads);
SEQAN_CALL_TEST(test_my_app_translate_database);
SEQAN_CALL_TEST(test_my_app_append_to_match_found);
SEQAN_CALL_TEST(test_my_app_find_matches);
}
SEQAN_END_TESTSUITE
// TEST DURCHLAUF ------------------------------------------------------------------------------------------------------
| mit |
true7/oleg_diatlenko_test_pj | src/notes/forms.py | 571 | from django import forms
from django.forms import ModelForm
from .models import Note
class NoteForm(ModelForm):
title = forms.CharField(
label='',
widget=forms.TextInput(
attrs={'class': "form-control", 'placeholder': 'Title...'}
)
)
content = forms.CharField(
label='',
min_length=10,
widget=forms.Textarea(
attrs={'class': "form-control", 'placeholder': 'Content...'}
)
)
class Meta:
model = Note
fields = ['title', 'content','image']
| mit |
isudox/leetcode-solution | python-algorithm/leetcode/problem_70.py | 776 | """70. Climbing Stairs
https://leetcode.com/problems/climbing-stairs/
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps.
In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
"""
class Solution:
def climb_stairs(self, n: int) -> int:
dp = [1] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
| mit |
ThanhKhoaIT/ants_admin | lib/ants_admin/smart_model.rb | 215 | module AntsAdmin
module SmartModel
# def self.initialize(model_string)
# @model_string = model_string
# end
#
# def apply_admin?
# defined?(@model_string::APPLY_ADMIN)
# end
end
end
| mit |
szszss/MigoCraft | net/hakugyokurou/migocraft/block/BlockRasa.java | 1286 | package net.hakugyokurou.migocraft.block;
import java.util.Random;
import net.hakugyokurou.migocraft.Migocraft;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
//TODO:写一个好的Javadoc
/**
* Ellen said hello to you.</br>
* -<i>Phantasmagoria of Dim. Dream</i>
* </br></br>
* BlockRasa是个啥啊.
* @author szszss
*/
public class BlockRasa extends Block{
private int renderType = Migocraft.blockRasaRenderType;
public BlockRasa(int par1, Material par2Material) {
super(par1, par2Material);
disableStats();
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4)
{
return null;
}
@Override
public boolean isCollidable()
{
return false;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public int getRenderType()
{
return renderType;
}
@Override
public int quantityDropped(Random par1Random)
{
return 0;
}
}
| mit |
vladislav-karamfilov/TelerikAcademy | C# II Projects/Homework-TextFiles/2. ConcatenatingTwoTextFiles/Properties/AssemblyInfo.cs | 1432 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("2. ConcatenatingTwoTextFiles")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("2. ConcatenatingTwoTextFiles")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5a74c6dd-3e85-4485-836f-e8600bdb23ff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
hypnoglow/helm-s3 | internal/helmutil/helm_v2.go | 852 | package helmutil
// This file contains helpers for helm v2.
import (
"os"
"k8s.io/helm/pkg/helm/environment"
"k8s.io/helm/pkg/helm/helmpath"
"k8s.io/helm/pkg/repo"
)
// setupHelm2 sets up environment and function bindings for helm v2.
func setupHelm2() {
helm2Home = resolveHome()
helm2LoadRepoFile = repo.LoadRepositoriesFile
}
var (
helm2Home helmpath.Home
// func that loads helm repo file.
// Defined for testing purposes.
helm2LoadRepoFile func(path string) (*repo.RepoFile, error)
)
const (
envHelmHome = "HELM_HOME"
)
func resolveHome() helmpath.Home {
h := helmpath.Home(environment.DefaultHelmHome)
if os.Getenv(envHelmHome) != "" {
h = helmpath.Home(os.Getenv(envHelmHome))
}
return h
}
func repoFilePathV2() string {
return helm2Home.RepositoryFile()
}
func cacheDirPathV2() string {
return helm2Home.Cache()
}
| mit |
ArkEcosystem/ark-desktop | src/renderer/services/synchronizer.js | 7542 | import { pullAll } from 'lodash'
import { flatten } from '@/utils'
import { announcements, fees, ledger, market, peer, wallets } from './synchronizer/'
/**
* This class adds the possibility to define actions (not to confuse with Vuex actions)
* that could be dispatched using 2 modes: `default` and `focus`.
*
* Each mode has an interval configuration that establishes the delay until the
* next update:
* - `focus` should be used on sections that display that kind of data to users
* - `default` should be used to check if new data is available
*
* There is also a way to pause and unpause the synchronization that is useful
* for not executing actions when the users do not need fresh data.
*/
export default class Synchronizer {
get intervals () {
// ARK block production time
const block = 8000
const intervals = {
longest: block * 300,
longer: block * 100,
medium: block * 25,
shorter: block * 10,
shortest: block * 3,
block,
// Number of milliseconds to wait to evaluate which actions should be run
loop: 2000
}
return intervals
}
get config () {
const { loop, shortest, shorter, medium, longer, longest } = this.intervals
const config = {
announcements: {
default: { interval: longest, delay: loop * 6 },
focus: { interval: medium }
},
delegates: {
default: { interval: longer, delay: loop * 3 },
focus: { interval: longer }
},
fees: {
default: { interval: null },
focus: { interval: shorter }
},
ledgerWallets: {
default: { interval: shorter },
focus: { interval: shortest }
},
market: {
default: { interval: medium },
focus: { interval: shorter }
},
peer: {
default: { interval: longer },
focus: { interval: shorter }
},
wallets: {
default: { interval: shorter },
focus: { interval: shortest }
}
}
config.contacts = config.wallets
return config
}
get $client () {
return this.scope.$client
}
get $store () {
return this.scope.$store
}
/**
* @param {Object} config
* @param {Vue} config.scope - Vue instance that would be synchronized
*/
constructor ({ scope }) {
this.scope = scope
this.actions = {}
this.focused = []
this.paused = []
}
/**
* Define an action that would be called later periodically
* @param {String} actionId
* @param {Object} config
* @param {Function} actionFn
*/
define (actionId, config, actionFn) {
if (typeof actionFn !== 'function') {
throw new Error('[$synchronizer] action is not a function')
}
;['default', 'focus'].forEach(mode => {
const { interval } = config[mode]
if (!interval && interval !== null) {
throw new Error(`[$synchronizer] \`interval\` for \`${mode}\` mode should be a Number bigger than 0 (or \`null\` to ignore it)`)
}
})
this.actions[actionId] = {
calledAt: 0,
isCalling: false,
fn: actionFn,
...config
}
}
/**
* Focus on these actions: instead of refreshing their data on the normal pace,
* change to the `focus` frequency.
*
* Focusing on 1 or several actions, unfocused the rest
* @params {(...String|Array)} actions - ID of the actions to focus on
*/
focus (...actions) {
this.focused = flatten(actions)
this.unpause(this.focused)
}
/**
* Add 1 or more actions to additionally focus
* @params {(...String|Array)} actions - ID of the actions to focus on
*/
appendFocus (...actions) {
this.focused = flatten([actions, this.focused])
this.unpause(actions)
}
/**
* Remove action from focus
* @params {(...String|Array)} actions - ID of the actions to focus on
*/
removeFocus (...actions) {
pullAll(this.focused, flatten(actions))
}
/**
* Pause these actions. They would not be dispatched until they are unpaused
* or focused
* @params {(...String|Array)} actions - ID of the actions to pause
*/
pause (...actions) {
this.paused = flatten(actions)
}
/**
* Enable these paused actions again
* @params {(...String|Array)} actions - ID of the actions to unpause
*/
unpause (...actions) {
pullAll(this.paused, flatten(actions))
}
/**
* Trigger these actions 1 time.
* As a consequence the interval of those actions is updated.
* @params {(...String|Array)} actions - ID of the actions to unpause
*/
trigger (...actions) {
flatten(actions).forEach(actionId => this.call(actionId))
}
/**
* Invoke the action and update the last time it has been called, when
* it has finished its sync or async execution
* @param {String} actionId
*/
async call (actionId) {
const action = this.actions[actionId]
if (!action) {
return
}
action.isCalling = true
await action.fn()
action.calledAt = (new Date()).getTime()
action.isCalling = false
}
/*
* Starts to dispatch the actions periodically
*/
ready () {
/**
* Run all the actions
*/
const run = (options = {}) => {
Object.keys(this.actions).forEach(actionId => {
if (!this.paused.includes(actionId)) {
const action = this.actions[actionId]
if (!action.isCalling) {
if (options.immediate) {
this.call(actionId)
} else {
const mode = this.focused.includes(actionId) ? 'focus' : 'default'
const { interval } = action[mode]
// A `null` interval means no interval, so the action does not run
if (interval !== null) {
// Delay the beginning of the periodic action run
if (!action.calledAt && action[mode].delay) {
action.calledAt += action.delay
}
const nextCallAt = action.calledAt + interval
const now = (new Date()).getTime()
if (nextCallAt <= now) {
this.call(actionId)
}
}
}
}
}
})
}
const runLoop = () => {
// Using `setTimeout` instead of `setInterval` allows waiting to the
// completion of async functions
setTimeout(() => {
run()
runLoop()
}, this.intervals.loop)
}
// Run the first time
run({ immediate: true })
runLoop()
}
defineAll () {
this.define('announcements', this.config.announcements, async () => {
await announcements(this)
})
// TODO focus on contacts only (currently wallets and contacts are the same)
// this.define('contacts', this.config.contacts, async () => {
// console.log('defined CONTACTS')
// })
// NOTE: not used currently
// this.define('delegates', this.config.delegates, async () => {
// await delegates(this)
// })
this.define('fees', this.config.fees, async () => {
await fees(this)
})
this.define('market', this.config.market, async () => {
await market(this)
})
this.define('peer', this.config.peer, async () => {
await peer(this)
})
// TODO allow focusing on 1 wallet alone, while using the normal mode for the rest
this.define('wallets', this.config.wallets, async () => {
await wallets(this)
})
this.define('wallets:ledger', this.config.ledgerWallets, async () => {
await ledger(this)
})
}
}
| mit |
archimatetool/archi | org.eclipse.gef/src/org/eclipse/gef/CompoundSnapToHelper.java | 2109 | /*******************************************************************************
* Copyright (c) 2003, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.gef;
import org.eclipse.core.runtime.Assert;
import org.eclipse.draw2d.geometry.PrecisionRectangle;
/**
* Combines multiple SnapToHelpers into one compound helper. The compound helper
* deletages to multiple other helpers.
*
* @author Pratik Shah
*/
public class CompoundSnapToHelper extends SnapToHelper {
private SnapToHelper[] delegates;
/**
* Constructs a compound snap to helper which will delegate to the provided
* array of helpers. The first helper in the array has highest priority and
* will be given the first opportunity to perform snapping.
*
* @since 3.0
* @param delegates
* an array of helpers
*/
public CompoundSnapToHelper(SnapToHelper delegates[]) {
Assert.isTrue(delegates.length != 0);
this.delegates = delegates;
}
/**
* Gets the array of helpers.
*
* @return the array of helpers.
* @since 3.4
*/
protected SnapToHelper[] getDelegates() {
return delegates;
}
/**
* @see SnapToHelper#snapRectangle(Request, int, PrecisionRectangle,
* PrecisionRectangle)
*/
@Override
public int snapRectangle(Request request, int snapOrientation,
PrecisionRectangle baseRect, PrecisionRectangle result) {
for (int i = 0; i < getDelegates().length && snapOrientation != NONE; i++)
snapOrientation = getDelegates()[i].snapRectangle(request,
snapOrientation, baseRect, result);
return snapOrientation;
}
}
| mit |
k-takam/simple-text-translator | src/scripts/containers/menu-container.js | 504 | import React from 'react';
import { connect } from 'react-redux';
import Menu from '../components/menu';
import { openModal } from '../actions';
const mapStateToProps = (state) => {
return {
outputText: state.text.outputText
};
};
const mapDispatchToProps = (dispatch) => {
return {
openModal: (type, modalText) => {
dispatch(openModal(type, modalText));
}
};
};
const MenuContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Menu);
export default MenuContainer;
| mit |
francois/family | src/main/scala/teksol/mybank/domain/events/InterestPosted.scala | 668 | package teksol.mybank.domain.events
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import teksol.domain.FamilyId
import teksol.infrastructure.{Event, ToJson}
import teksol.mybank.domain.models.{AccountId, Amount, EntryId}
import scala.language.implicitConversions
case class InterestPosted(familyId: FamilyId, accountId: AccountId, entryId: EntryId, postedOn: LocalDate, amount: Amount) extends Event {
import teksol.infrastructure.Helpers._
override def toJson: String = s"""{"family_id":${familyId.toJson},"account_id":${accountId.toJson},"entry_id":${entryId.toJson},"posted_on":${postedOn.toJson},"amount":${amount.toJson}}"""
}
| mit |
pkgodara/Rocket.Chat | packages/rocketchat-livechat/server/methods/removeRoom.js | 961 | import { Meteor } from 'meteor/meteor';
Meteor.methods({
'livechat:removeRoom'(rid) {
if (!Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'remove-closed-livechat-rooms')) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'livechat:removeRoom' });
}
const room = RocketChat.models.Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'livechat:removeRoom',
});
}
if (room.t !== 'l') {
throw new Meteor.Error('error-this-is-not-a-livechat-room', 'This is not a Livechat room', {
method: 'livechat:removeRoom',
});
}
if (room.open) {
throw new Meteor.Error('error-room-is-not-closed', 'Room is not closed', {
method: 'livechat:removeRoom',
});
}
RocketChat.models.Messages.removeByRoomId(rid);
RocketChat.models.Subscriptions.removeByRoomId(rid);
return RocketChat.models.Rooms.removeById(rid);
},
});
| mit |
maicoin/maicoin-java | src/main/java/com/maicoin/api/entity/Checkouts.java | 1086 | package com.maicoin.api.entity;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.maicoin.api.converter.CheckoutConverter;
import java.util.List;
/**
* Created by yutelin on 1/12/15.
*/
public class Checkouts extends Entity {
private int _count;
private int _currentPage;
private int _numOfPages;
private List<Checkout> _checkouts;
public int getCount() {
return _count;
}
public void setCount(int _count) {
this._count = _count;
}
public int getCurrentPage() {
return _currentPage;
}
public void setCurrentPage(int _currentPage) {
this._currentPage = _currentPage;
}
public int getNumOfPages() {
return _numOfPages;
}
public void setNumOfPages(int _numOfPages) {
this._numOfPages = _numOfPages;
}
public List<Checkout> getCheckouts() {
return _checkouts;
}
@JsonDeserialize(converter=CheckoutConverter.class)
public void setCheckouts(List<Checkout> _checkouts) {
this._checkouts = _checkouts;
}
}
| mit |
casual-web/autodom | src/AppBundle/Form/QuotationRequestType.php | 1840 | <?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use AppBundle\Entity\QuotationRequest;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class QuotationRequestType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$entityManager = $options['em'];
$bsRepo = $entityManager->getRepository('AppBundle:BusinessService');
$builder
->add('baseqr', new BaseQuotationRequestType(), array(
'data_class' => 'AppBundle\Entity\QuotationRequest'))
->add('status', null, ['label' => 'Etat de la demande'])
->add(
'quotationRequestServiceRelations',
'collection', [
'label' => 'Référence du service',
'type' => new QuotationRequestServiceRelationType($bsRepo->getChoices(false)),
'allow_add' => true,
'by_reference' => false,
]
);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\QuotationRequest',
));
$resolver->setRequired(array(
'em'
));
$resolver->setAllowedTypes(array(
'em' => 'Doctrine\Common\Persistence\ObjectManager'
));
}
/**
* @return string
*/
public function getName()
{
return 'appbundle_quotationrequest';
}
}
| mit |
tamouse/wp_conversion | spec/wp_conversion/xml_to_hash_spec.rb | 1090 | module WpConversion
describe "#xml_to_hash method" do
it {WpConversion.should respond_to :xml_to_hash}
context "converting xml" do
let(:xml){'<?xml version="1.0"?><catalog><book id="bk001"><author>Gaiman, Neil</author><title>The Graveyard Book</title><genre>Fantasy</genre></book><book id="bk002"><author>Pratchett, Terry</author><title>The Colour of Magic</title><genre>fantasy</genre></book></catalog> '}
let(:hash){WpConversion.xml_to_hash(xml)}
it {hash.should be_a(Hash)}
it {hash.keys.count.should == 1}
it {hash.keys.should include("catalog")}
context "catalog" do
let(:books){hash['catalog']['book']}
it {books.should be_a(Array)}
it {books.size.should == 2}
context "books.first" do
let(:first_book){books.first}
it {first_book.should be_a(Hash)}
%w{id author title genre}.each do |attr|
it "first_book should have #{attr}" do
first_book.has_key?(attr).should be_true
end
end
end
end
end
end
end
| mit |
veratulips/OMOOC2py | _src/om2py3w/3wex0/diaryServer.py | 1040 | # -*- coding:utf8 -*-
import socket
import os
# 建立协议,当client发送退出信号,返回日记历史信息
quitwd = 'q'
def response(s,data,addr):
if data == 'q':
f = open('diary.txt')
msg = f.read()
f.close()
print msg
s.sendto(msg,addr)
print 'send back to',addr,'and quit'
else:
f = open('diary.txt', 'a')
f.write(data + '\n')
print data
f.close()
def main():
if not os.path.exists('diary.txt'):
f=open('diary.txt','w')
f.close()
port = 10000 # 数字是默认的吗?
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #从指定的端口,从任何发送者,接收UDP数据
s.bind(('localhost',port))
print('正在等待接入...')
while True:
#接收一个数据
print "\n已接入,正在等待信息"
data,addr=s.recvfrom(1024)
print 'Received:',data,'from',addr
response(s,data,addr)
s.close()
if __name__ == '__main__':
main() | mit |
GDGJihlava/gdg-coding-dojo-jihlava | 009-refactoring/solution-oop/src/main/java/cz/unittest/exercises/ItemFactory.java | 594 | package cz.unittest.exercises;
public class ItemFactory {
public static ItemAbstract createItem(String name, int sellIn, int quality) {
if (name.equals("Sulfuras, Hand of Ragnaros")) {
return new ItemImmutable(name, sellIn, quality);
} else if (name.equals("Aged Brie")) {
return new ItemAged(name, sellIn, quality);
} else if (name.equals("Backstage passes to a TAFKAL80ETC concert")) {
return new ItemPasses(name, sellIn, quality);
} else {
return new ItemStandard(name, sellIn, quality);
}
}
}
| mit |
lonelyplanet/backpack-ui | src/utils/time.js | 470 | export default function duration(ms) {
ms = ms || 0;
let remainingSeconds = ms / 1000;
const h = Math.floor(remainingSeconds / (60 * 60));
remainingSeconds -= h * 60 * 60;
const m = Math.floor(remainingSeconds / 60);
remainingSeconds -= m * 60;
const s = Math.floor(remainingSeconds % 60);
let formatted = "";
formatted += h ? `${h}:` : "";
formatted += m < 10 && h ? `0${m}` : m;
formatted += s < 10 ? `:0${s}` : `:${s}`;
return formatted;
}
| mit |
nmapx/inidister | src/Nmapx/Inidister/Domain/Writer/Writer.php | 161 | <?php declare(strict_types=1);
namespace Nmapx\Inidister\Domain\Writer;
interface Writer
{
function writeToFile(string $filepath, string $data): Writer;
}
| mit |
robustly/robust-log | examples/basic-logging.js | 221 | var log = require('../lib')('elk')
log('starting process 1.')
log('initiating feeds')
log.warn('detected anomoly.')
try {
test.this.throws
} catch (err) {
log(err)
}
log.error('Error occurred during process 1.')
| mit |
gauravparashar29/exambazaar | app/emails.js | 170746 | //var nodemailer = require('nodemailer');
var express = require('express');
var router = express.Router();
var email = require('../app/models/email');
var exam = require('../app/models/exam');
var eqad = require('../app/models/eqad');
var eqadsubscription = require('../app/models/eqadsubscription');
var user = require('../app/models/user');
var view = require('../app/models/view');
var review = require('../app/models/review');
var question = require('../app/models/question');
var blogpost = require('../app/models/blogpost');
var college = require('../app/models/college');
var coaching = require('../app/models/coaching');
var school = require('../app/models/school');
var subscriber = require('../app/models/subscriber');
var sendGridCredential = require('../app/models/sendGridCredential');
var moment = require('moment-timezone');
var fs = require('fs');
const sgMail = require('@sendgrid/mail');
const client = require('@sendgrid/client');
var helper = require('sendgrid').mail;
var apiKey = null;
router.post('/sendgridListener', function(req, res) {
var events = req.body;
//console.log("*************** NEW REQUEST ***************");
if(events && events.length > 0){
events.forEach(function(thisEvent){
if(thisEvent._id){
if(thisEvent.timestamp){
thisEvent.timestamp = moment.unix(thisEvent.timestamp).toDate();
}
var thisEmail = email.findOne({ _id: thisEvent._id },function (err, thisEmail){
if (!err && thisEmail){
var thisEvents = thisEmail.events;
var eventIds = [];
if(thisEvents && thisEvents.length > 0){
eventIds = thisEvents.map(function(a) {return a.sg_event_id;});
}
var eIndex = eventIds.indexOf(thisEvent.sg_event_id);
if(eIndex == -1){
thisEmail.events.push(thisEvent);
thisEmail.save(function(err, thisEmail) {
if (err) return console.error(err);
});
}
}
});
/*email.update({_id: thisEvent._id},
{$push: {events: thisEvent}}
, function(err, response){
if (err) throw err;
else {
console.log("\tPushed Event: " + thisEvent.event , response);
}
});*/
}else{
//console.log("No Event Id");
}
});
}
});
function validateEmail(email){
if(!email || email.length < 5){
return false;
}else{
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
};
function initiate(){
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (!err){
if(existingSendGridCredential){
var api_key = existingSendGridCredential.apiKey;
sgMail.setApiKey(api_key);
client.setApiKey(api_key);
apiKey = existingSendGridCredential.apiKey;
//send_email(emailForm);
console.log('Email sg initiate complete!');
}
}else{
console.log('Something went very wrong!!');
}
});
};
initiate();
function verify_email(emailForm){
var valid = true;
if(emailForm){
if(emailForm.toEmail && emailForm.toEmail.email){
if(!validateEmail(emailForm.toEmail.email)){
//console.log("To: " + emailForm.toEmail.email);
valid = false;
}
}else{
valid = false;
}
if(emailForm.fromEmail && emailForm.fromEmail.email){
if(!validateEmail(emailForm.fromEmail.email)){
//console.log("To: " + emailForm.fromEmail.email);
valid = false;
}
}else{
valid = false;
}
}else{
valid = false;
}
return valid;
};
var emailForm = {
toEmail: {
email: "gaurav@exambazaar.com",
name: "Gaurav Parashar",
},
fromEmail:{
email: "always@exambazaar.com",
name: "Always Exambazaar",
},
templateId: "15a2603a-9de4-4cd3-ae45-4b9ae2eebafc",
personalizations: {
'-userName-': "Gaurav"
},
html: "Hello world!",
subject: "Hello there!",
_requested: '1531305172',
user: '5a1831f0bd2adb260055e352',
};
function send_email(emailForm, multiAllowed){
if(!verify_email(emailForm)){
console.log("Email incorrect: " + emailForm.toEmail.email);
}else{
var from_email = new helper.Email(emailForm.fromEmail);
var to_email = new helper.Email(emailForm.toEmail);
var html = ' ';
var subject = ' ';
if(emailForm.html){
html = emailForm.html;
}
if(emailForm.subject){
subject = emailForm.subject;
}
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(from_email.email, subject, to_email.email, content);
if(!emailForm.to && to_email.email && to_email.email.email){
emailForm.to = to_email.email.email;
}
if(emailForm.templateId){
mail.setTemplateId(emailForm.templateId);
}
if(emailForm.personalizations){
for (var property in emailForm.personalizations) {
var toReplace = property;
var replaceWith = emailForm.personalizations[property];
mail.personalizations[0].addSubstitution(new helper.Substitution(toReplace, replaceWith.toString()));
}
}
emailForm.body = mail.toJSON();
if(emailForm._requested){
emailForm._requested = moment(emailForm._requested).toDate();
}
// to the same person "to" within the last 1 day with the same templateId
var _date = moment();
var _dateStart = moment(_date).startOf('day').toDate();
var _dateEnd = moment(_date).endOf('day').toDate();
var existingEmail = email.findOne({ 'to': emailForm.to, templateId: emailForm.templateId, _date: {$gte: _dateStart, $lte: _dateEnd}}, {to: 1, _date: 1, templateId: 1},function (err, existingEmail) {
if(existingEmail && !multiAllowed){
console.log("Email to " + emailForm.to + " already requested at: " + existingEmail._date);
}else{
var this_email = new email(emailForm);
this_email.save(function(err, this_email) {
if (err) return console.error(err);
//console.log('Email obj created with id: ' + this_email._id);
var custom_arg = new helper.CustomArgs("_id", this_email._id);
mail.addCustomArg(custom_arg);
//mail.personalizations[0].addCustomArg("_id", this_email._id);
//mail.customArgs("_id", this_email._id);
var sg = require("sendgrid")(apiKey);
//console.log(emailForm);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
console.log("~~~~~~~~~~~~~~~~~~~~~~~");
console.log('EMAIL NOT SENT');
console.log(error.response.body.errors);
console.log("~~~~~~~~~~~~~~~~~~~~~~~");
}else{
console.log("Email request for: " + emailForm.to + " sent");
/*console.log("Code is: " + response.statusCode);
console.log("Body is: " + response.body);
console.log("Headers are: " + JSON.stringify(response.headers));
console.log(JSON.stringify(response));*/
}
});
});
}
});
}
};
router.get('/sampleEmail', function(req, res) {
res.json(true);
send_email(emailForm, false);
});
router.post('/publications', function(req, res) {
var thisEmail = req.body;
var templateName = thisEmail.templateName;
var from = thisEmail.from;
var sender = thisEmail.sender;
var senderId = thisEmail.senderId;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
var to = thisEmail.to;
var subject = thisEmail.subject;
if(!subject || subject == ''){
subject = 'Press release & story coverage of Exambazaar (IIT-IIM alumni Jaipur based startup)';
}
var html = thisEmail.html;
if(!html){
html = ' ';
}
console.log("To: " + to + " Subject: " + subject + " from: " + from);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
console.log(templateId);
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
console.log('This email is: ' + JSON.stringify(this_email));
this_email.save(function(err, this_email) {
if (err) return console.error(err);
console.log('Email sent with id: ' + this_email._id);
});
res.json(response);
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/sendGrid', function(req, res) {
var thisEmail = req.body;
var templateName = thisEmail.templateName;
console.log(templateName);
var from = thisEmail.from;
var sender = thisEmail.sender;
var senderId = thisEmail.senderId;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
var to = thisEmail.to;
var subject = thisEmail.subject;
var name = thisEmail.name;
var instituteName = thisEmail.instituteName;
var instituteNameCaps = instituteName.toUpperCase();
var instituteAddress = thisEmail.instituteAddress;
var institutePhoneMobile = thisEmail.institutePhoneMobile;
var instituteId = thisEmail.instituteId;
var logo = thisEmail.logo;
if(!logo){
logo='https://s3.ap-south-1.amazonaws.com/exambazaar/logo/bg.png';
}
var prefix = "https://s3.ap-south-1.amazonaws.com/exambazaar/listingSnapshot/";
var fileName = thisEmail.instituteId+'.png';
var listingSnapshot = prefix + fileName;
console.log(listingSnapshot);
var html = thisEmail.html;
if(!html){
html = ' ';
}
console.log("To: " + to + " Subject: " + subject + " from: " + from);
//var apiKey = sendGridCredential.getOneSendGridCredential
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
console.log(emailTemplate);
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
console.log(templateId);
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
console.log('Template id is: ' + JSON.stringify(templateId));
/*console.log('API Key: ' + apiKey);
console.log('From Email: ' + JSON.stringify(from_email));
console.log('To Email: ' + JSON.stringify(to_email));
console.log('Subject: ' + JSON.stringify(subject));
console.log('Content: ' + JSON.stringify(content));*/
//mail.Substitution('-name-', name);
//mail.personalizations = [];
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteName-', instituteName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteNameCaps-', instituteNameCaps));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteAddress-', instituteAddress));
mail.personalizations[0].addSubstitution(new helper.Substitution('-institutePhoneMobile-', institutePhoneMobile));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteId-', instituteId));
console.log('Setting image as: ' + listingSnapshot);
mail.personalizations[0].addSubstitution(new helper.Substitution('-listingSnapshot-', listingSnapshot));
mail.personalizations[0].addSubstitution(new helper.Substitution('-logo-', logo));
//console.log('Logo is: ' + logo);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
console.log("Code is: " + response.statusCode);
console.log("Body is: " + response.body);
console.log("Headers are: " + JSON.stringify(response.headers));
console.log(JSON.stringify(response));
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
console.log('This email is: ' + JSON.stringify(this_email));
this_email.save(function(err, this_email) {
if (err) return console.error(err);
console.log('Email sent with id: ' + this_email._id);
});
res.json(response);
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/claimInvite', function(req, res) {
var templateName = 'CI Email - Claim Your Listing - 2018';
var from = 'always@exambazaar.com';
var sender = 'Always Exambazaar';
var senderId = '59a7eb973d71f10170dbb468';
var eCounter = 0;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
//var coachingIds = ['58821266fe400914343a5074'];
//'_id': { $in : coachingIds},
var allCoachings = coaching
.find({ email: {$exists: true}, disabled: false, $where: "this.email.length > 0" }, { name: 1, email:1 })
.limit(1)
.exec(function (err, allCoachings) {
if (!err){
if(allCoachings){
res.json(true);
console.log('There are: ' + allCoachings.length + ' coachings!');
allCoachings.forEach(function(thisCoaching, pindex){
var thisEmails = thisCoaching.email;
var instituteName = thisCoaching.name;
var instituteId = thisCoaching._id;
//console.log(instituteName + " | " + thisEmails);
thisEmails.forEach(function(thisEmail, eindex){
var emailSent = false;
//console.log(thisEmail);
var to = thisEmail;
//to = 'ayush@exambazaar.com';
var subject = instituteName + ", students are asking us about you.";
var html = ' ';
if(!html){
html = ' ';
}
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
//console.log("Template has been found!");
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteName-', instituteName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteId-', instituteId));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
var existingEmail = email.findOne({ to: to, _date: {$gte: new Date('2018-05-30T00:00:00.000Z')}}, {templateId: 1, _date: 1, to: 1},function (err, existingEmail) {
if (err) return handleError(err);
if(existingEmail){
console.log("Email to " + to + " already sent at: " + existingEmail._date);
}else{
//console.log("Will send to " + to);
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
if (err) return console.error(err);
eCounter += 1;
console.log(eCounter + '. Email sent to ' + instituteName + ' at ' + this_email.to);
});
//res.json(response);
}
});
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
});
}
} else {throw err;}
});
});
router.post('/descriptionInvite', function(req, res) {
var templateName = 'CI Email - Write a Blog - 2018';
var from = 'always@exambazaar.com';
var sender = 'Always Exambazaar';
var senderId = '59a7eb973d71f10170dbb468';
var eCounter = 0;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
//var coachingIds = ['58821266fe400914343a5074'];
//'_id': { $in : coachingIds},
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var limit = 1000;
var skip = 10000;
var allCoachings = coaching
.find({ email: {$exists: true}, nameslug: {$exists: true}, areaslug: {$exists: true}, city: {$exists: true}, disabled: false, $where: "this.email.length > 0" }, { name: 1, email:1, nameslug: 1, areaslug: 1, city: 1, seo: 1 })
.limit(limit).skip(skip)
.exec(function (err, allCoachings) {
if (!err){
if(allCoachings){
res.json(true);
console.log('There are: ' + allCoachings.length + ' coachings!');
console.log('Skip: ' + skip + ' limit: ' + limit);
allCoachings.forEach(function(thisCoaching, pindex){
var thisEmails = thisCoaching.email;
var instituteName = thisCoaching.name;
var instituteCity = thisCoaching.city;
var instituteCityCaps = thisCoaching.city.toUpperCase();
var instituteId = thisCoaching._id;
thisEmails.forEach(function(thisEmail, eindex){
var emailSent = false;
var to = thisEmail;
//to = 'saloni@exambazaar.com';
var subject = instituteName + ", students are asking us about you.";
var html = ' ';
if(!html){
html = ' ';
}
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteName-', instituteName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteId-', instituteId));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteCity-', instituteCity));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteCityCaps-', instituteCityCaps));
if(thisCoaching.nameslug && thisCoaching.areaslug){
var n5url = "https://www.exambazaar.com/c/" + thisCoaching.nameslug + '/' + thisCoaching.areaslug;
mail.personalizations[0].addSubstitution(new helper.Substitution('-n5url-', n5url));
}
var n5title = "EB Coaching Page";
if(thisCoaching.seo && thisCoaching.seo.title){
n5title = thisCoaching.seo.title;
}
mail.personalizations[0].addSubstitution(new helper.Substitution('-n5title-', n5title));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
var existingEmail = email.findOne({ to: to, _date: {$gte: new Date('2018-05-30T00:00:00.000Z')}}, {templateId: 1, _date: 1, to: 1},function (err, existingEmail) {
if (err) return handleError(err);
if(existingEmail){
console.log("Email to " + to + " already sent at: " + existingEmail._date);
}else{
//console.log("Will send to " + to);
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
if (err) return console.error(err);
eCounter += 1;
console.log(eCounter + '. Email sent to ' + instituteName + ' at ' + this_email.to);
});
//res.json(response);
}
});
}
});
});
});
}
} else {throw err;}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/blogInvite', function(req, res) {
console.log("Sending Blog Invite");
//var templateName = 'Claim CI Email - 28thNov2017';
var templateName = 'CI Email - Write a Blog - 2018';
var from = 'always@exambazaar.com';
var sender = 'Always Exambazaar';
var senderId = '59a7eb973d71f10170dbb468';
var eCounter = 0;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
//var coachingIds = ['59a79c63ceb4f62a7023617d'];
//'_id': { $in : coachingIds},
//, '_id': { $in : coachingIds}
var allCoachings = coaching
.find({ email: {$exists: true}, disabled: false, $where: "this.email.length > 0" }, { name: 1, email:1 })
.limit(0).skip(9000)
.exec(function (err, allCoachings) {
if (!err){
if(allCoachings){
res.json(true);
console.log('There are: ' + allCoachings.length + ' coachings!');
allCoachings.forEach(function(thisCoaching, pindex){
var thisEmails = thisCoaching.email;
var instituteName = thisCoaching.name;
var instituteId = thisCoaching._id;
thisEmails.forEach(function(thisEmail, eindex){
var emailSent = false;
var to = thisEmail;
//to = 'gaurav@exambazaar.com';
//var subject = instituteName + " - You are the expert! Would you write with us?";
var subject = " ";
var html = ' ';
if(!html){
html = ' ';
}
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteName-', instituteName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteId-', instituteId));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
var existingEmail = email.findOne({ to: to, _date: {$gte: new Date('2018-06-29T00:00:00.000Z')}}, {templateId: 1, _date: 1, to: 1},function (err, existingEmail) {
if (err) return handleError(err);
if(existingEmail){
console.log("Email to " + to + " already sent at: " + existingEmail._date);
}else{
//console.log("Will send to " + to);
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
if (err) return console.error(err);
eCounter += 1;
console.log(eCounter + '. Email sent to ' + instituteName + ' at ' + this_email.to);
});
//res.json(response);
}
});
}
});
/**/
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
});
}
} else {throw err;}
});
});
function uniqueEmails(emailArray){
var newArray = [];
emailArray.forEach(function(thisEmail, eindex){
var nindex = newArray.indexOf(thisEmail);
if(nindex == -1){
if(validateEmail(thisEmail)){
newArray.push(thisEmail);
}
}
});
return(newArray);
};
router.post('/mockTestInvite', function(req, res) {
console.log("Sending Mock Test Blog Invite");
//var templateName = 'Claim CI Email - 28thNov2017';
var templateName = 'CI Email - Write a Blog - 2018';
var from = 'always@exambazaar.com';
var sender = 'Always Exambazaar';
var senderId = '59a7eb973d71f10170dbb468';
var eCounter = 0;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
var limit = 500;
var skip = 10000;
//var coachingIds = ['59a79c63ceb4f62a7023617d'];
//'_id': { $in : coachingIds},
//, '_id': { $in : coachingIds}
var allCoachings = coaching
.find({ email: {$exists: true}, disabled: false, $where: "this.email.length > 0" }, { name: 1, email:1 })
.limit(limit).skip(skip)
.exec(function (err, allCoachings) {
console.log("LIMIT: " + limit + " | SKIP: " + skip);
if (!err && allCoachings){
res.json(true);
console.log('There are: ' + allCoachings.length + ' coachings!');
allCoachings.forEach(function(thisCoaching, pindex){
//thisCoaching.email = ["gaurav@exambazaar.com", "gaurav@exambazaar.com", "gaurav@exambazaar"];
var thisEmails = uniqueEmails(thisCoaching.email);
//console.log(thisEmails);
var instituteName = thisCoaching.name;
var instituteId = thisCoaching._id;
thisEmails.forEach(function(thisEmail, eindex){
var emailForm = {
toEmail: {
email: thisEmail,
/*name: "Always Exambazaar",*/
},
fromEmail:{
email: "tests@exambazaar.com",
name: "Tests at Exambazaar",
},
templateId: "57fe541e-652f-4210-aedd-716c1aecda1b",
personalizations: {
'-instituteName-': instituteName,
'-instituteId-': instituteId,
},
html: " ",
subject: " ",
_requested: moment().toDate(),
};
send_email(emailForm, false);
});
});
} else {throw err;}
});
});
router.post('/ntaInvite', function(req, res) {
console.log("Sending NTA Invite");
//var templateName = 'Claim CI Email - 28thNov2017';
var templateName = 'NTA Announcement';
var from = 'always@exambazaar.com';
var sender = 'Always Exambazaar';
var senderId = '59a7eb973d71f10170dbb468';
var eCounter = 0;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
var limit = 500;
var skip = 2500;
//var coachingIds = ['59a79c63ceb4f62a7023617d'];
var examIds = ['58cedb079eef5e0011c17e91', '58ac27997d227b1fa8208ff1'];
//'_id': { $in : coachingIds},
//, '_id': { $in : coachingIds}
var allCoachings = coaching
.find({ email: {$exists: true}, exams: {$in: examIds}, disabled: false, $where: "this.email.length > 0" }, { name: 1, email:1 })
.limit(limit).skip(skip)
.exec(function (err, allCoachings) {
if (!err){
if(allCoachings){
res.json(true);
//console.log('There are: ' + allCoachings.length + ' coachings!');
console.log("Limit: " + limit + " | Skip: " + skip);
if(allCoachings.length == 0){
console.log('No more coachings left!');
}
allCoachings.forEach(function(thisCoaching, pindex){
var thisEmails = thisCoaching.email;
var instituteName = thisCoaching.name;
var instituteId = thisCoaching._id;
thisEmails.forEach(function(thisEmail, eindex){
var emailSent = false;
var to = thisEmail;
//to = 'ayush@exambazaar.com';
//var subject = instituteName + " - You are the expert! Would you write with us?";
var subject = " ";
var html = ' ';
if(!html){
html = ' ';
}
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteName-', instituteName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteId-', instituteId));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
var existingEmail = email.findOne({ to: to, _date: {$gte: new Date('2018-07-10T00:00:00.000Z')}}, {templateId: 1, _date: 1, to: 1},function (err, existingEmail) {
if (err) return handleError(err);
if(existingEmail){
console.log("Email to " + to + " already sent at: " + existingEmail._date);
}else{
//console.log("Will send to " + to);
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
if (err) return console.error(err);
eCounter += 1;
console.log(eCounter + '. Email sent to ' + instituteName + ' at ' + this_email.to);
});
//res.json(response);
}
});
}
});
/**/
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
});
}
} else {throw err;}
});
});
router.post('/officialPapersInvite', function(req, res) {
var templateName = 'Official Question Papers';
var from = 'always@exambazaar.com';
var sender = 'Always Exambazaar';
var senderId = '59a7eb973d71f10170dbb468';
var eCounter = 0;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
var coachingIds = ['58821266fe400914343a5074'];
var allCoachings = coaching
.find({ '_id': { $in : coachingIds}, email: {$exists: true}, disabled: false }, { name: 1, email:1 })
//.limit(1)
.exec(function (err, allCoachings) {
if (!err){
if(allCoachings){
res.json(true);
console.log('There are: ' + allCoachings.length + ' coachings!');
allCoachings.forEach(function(thisCoaching, pindex){
var thisEmails = thisCoaching.email;
var instituteName = thisCoaching.name;
var instituteId = thisCoaching._id;
thisEmails.forEach(function(thisEmail, eindex){
var emailSent = false;
var to = thisEmail;
//to = 'ayush@exambazaar.com';
var subject = instituteName + " - Increase Revenue with FREE Previous Papers for Students";
var html = ' ';
if(!html){
html = ' ';
}
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
//var to = 'saloni@exambazaar.com';
var to_email = new helper.Email(to);
//var subject = subject;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteName-', instituteName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteId-', instituteId));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
var existingEmail = email.findOne({ to: to, _date: {$gte: new Date('2018-02-28T00:00:00.000Z')}}, {templateId: 1, _date: 1, to: 1},function (err, existingEmail) {
if (err) return handleError(err);
if(existingEmail){
console.log("Email to " + to + " already sent at: " + existingEmail._date);
}else{
//console.log("Will send to " + to);
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: {
email: from,
name: sender
},
to: to,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
if (err) return console.error(err);
eCounter += 1;
console.log(eCounter + '. Email sent to ' + instituteName + ' at ' + this_email.to);
});
//res.json(response);
}
});
}
});
/**/
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
});
}
} else {throw err;}
});
});
/*fs.readFile('public_html/img/Report.pdf', function(err, data) {*/
function titleCase(str) {
str = str.toLowerCase();
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
return str.join(' ');
};
router.post('/officialPapersInvitetoSchool', function(req, res) {
var templateName = 'Official Question Papers';
var from = 'always@exambazaar.com';
var sender = 'Always Exambazaar';
var senderId = '5a9f7b184b1ece1f48a88d5e';
var eCounter = 0;
//sender = 'Always Exambazaar';
var fromEmail = {
email: from,
name: sender
};
//var schoolIds = ["5a9f7b1d4b1ece1f48a88d6a","5a9f7c43ff178410c0ccd53f","5a9f7c3cff178410c0ccd53e","5a9f7b184b1ece1f48a88d5e","5a9f7c27ff178410c0ccd4ed","5a9f7b164b1ece1f48a88d5b","5a9f7b194b1ece1f48a88d61","5a9f7b244b1ece1f48a88d85","5a9f7b264b1ece1f48a88d91","5a9f7b3d4b1ece1f48a88dba","5a9f7b2a4b1ece1f48a88db3","5a9f7c33ff178410c0ccd522","5a9f7c25ff178410c0ccd4ea","5a9f7c30ff178410c0ccd510","5a9f7c33ff178410c0ccd520","5a9f7b1e4b1ece1f48a88d6d","5a9f7c36ff178410c0ccd53b","5a9f7b174b1ece1f48a88d5c","5a9f7c2eff178410c0ccd502","5a9f7c2eff178410c0ccd505"];
//, '_id': { $in : schoolIds}
var limit = 500;
var skip = 12500;
var allSchools = school
.find({ "data.email": {$exists: true}, "data.email": {$ne: ""}}, { data: 1 })
//.limit(1)
.limit(limit).skip(skip)
.exec(function (err, allSchools) {
if (!err){
if(allSchools){
res.json(true);
var nSchools = allSchools.length;
var scounter = 0;
var eCounter = 0;
var asCounter = 0;
console.log('There are: ' + allSchools.length + ' schools!');
allSchools.forEach(function(thisSchool, sindex){
var thisEmail = thisSchool.data.email;
var schoolName = thisSchool.data["name-of-institution"];
var schoolId = thisSchool._id;
if(!schoolName){
schoolName = "School";
}
schoolName = schoolName.replace(".", ". ");
schoolName = titleCase(schoolName);
var principalName = thisSchool.data["name-of-principal-head-of-institution"];
var attnName = "";
if(principalName && principalName.length > 1){
principalName = principalName.replace(".", ". ");
principalName = titleCase(principalName);
attnName = principalName + ", " + schoolName;
}else{
attnName = "Principal, " + schoolName;
}
//console.log("Attn: " + attnName + " | Email: " + thisEmail);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to = thisEmail;
//to = "gaurav@exambazaar.com";
var to_email = new helper.Email(to);
//var subject = subject;
var html = ' ';
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-schoolName-', schoolName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-attnName-', attnName));
var existingEmail = email.findOne({ to: to, _date: {$gte: new Date('2018-03-15T00:00:00.000Z')}}, {templateId: 1, _date: 1, to: 1},function (err, existingEmail) {
if (err) return handleError(err);
if(existingEmail){
console.log("Email to " + to + " already sent at: " + existingEmail._date);
scounter += 1;
asCounter += 1;
if(scounter == nSchools){
console.log('Total Emails sent: ' + eCounter + " out of " + nSchools + " schools! | " + asCounter + " already sent");
}
}else{
fs.readFile('Previous.pdf', function(err, data) {
fs.readFile('Previous.png', function(err, imgdata) {
//console.log(data);
//console.log(imgdata);
var dataBuffer = new Buffer(data).toString('base64');
var dataBuffer2 = new Buffer(imgdata).toString('base64');
var attachment = new helper.Attachment();
attachment.setType("application/pdf");
attachment.setFilename("Previous-year-question-papers-for-competitive-exams.pdf");
attachment.setDisposition("attachment");;
attachment.setContent(dataBuffer);
mail.addAttachment(attachment);
var attachment2 = new helper.Attachment();
attachment2.setType("image/png");
attachment2.setFilename("Previous-year-question-papers-for-competitive-exams.png");
attachment2.setDisposition("attachment");
attachment2.setContent(dataBuffer2);
mail.addAttachment(attachment2);
//console.log(data);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
console.log(' ---- Could not send email! ' + error + " " + response.statusCode);
console.log(sindex + "." + " Email to " + attnName + " | " + thisEmail + " NOT SENT | Id: " + thisSchool._id + " ---- ");
scounter += 1;
if(scounter == nSchools){
console.log('Total Emails sent: ' + eCounter + " out of " + nSchools + " schools! | " + asCounter + " already sent");
}
}else{
var this_email = new email({
school: schoolId,
templateId: templateId,
fromEmail: fromEmail,
to: thisEmail,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
console.log(sindex + "." +" Email to " + attnName + " | " + thisEmail + " sent | Id: " + thisSchool._id);
scounter += 1;
eCounter += 1;
if(scounter == nSchools){
console.log('Total Emails sent: ' + eCounter + " out of " + nSchools + " schools! | " + asCounter + " already sent");
}
});
}
});
});
});
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
}
} else {throw err;}
});
});
router.post('/coachingDiscountToSchool', function(req, res) {
var templateName = 'Coaching Discount';
console.log('Starting Coaching Discount Email');
var from = 'ayush@exambazaar.com';
var sender = 'Ayush Jain';
var senderId = '5a1831f0bd2adb260055e352';
var eCounter = 0;
var fromEmail = {
email: from,
name: sender
};
var limit = 1;
var skip = 0;
var allSchools = school
.find({ "data.email": {$exists: true}, "data.email": {$ne: ""}, "data.district": "JAIPUR"}, { data: 1 })
//.limit(1)
.limit(limit).skip(skip)
.exec(function (err, allSchools) {
if (!err){
if(allSchools){
res.json(true);
var nSchools = allSchools.length;
var scounter = 0;
var eCounter = 0;
var asCounter = 0;
console.log('There are: ' + allSchools.length + ' schools!');
allSchools.forEach(function(thisSchool, sindex){
var thisEmail = thisSchool.data.email;
thisEmail = "gaurav@exambazaar.com";
var schoolName = thisSchool.data["name-of-institution"];
var schoolId = thisSchool._id;
if(!schoolName){
schoolName = "School";
}
schoolName = schoolName.replace(".", ". ");
schoolName = titleCase(schoolName);
var principalName = thisSchool.data["name-of-principal-head-of-institution"];
var attnName = "";
if(principalName && principalName.length > 1){
principalName = principalName.replace(".", ". ");
principalName = titleCase(principalName);
attnName = principalName;
}else{
attnName = "Principal";
}
//console.log("Attn: " + attnName + " | Email: " + thisEmail);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to = thisEmail;
//to = "gaurav@exambazaar.com";
var to_email = new helper.Email(to);
//var subject = subject;
var html = ' ';
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-schoolName-', schoolName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-attnName-', attnName));
var existingEmail = email.findOne({ to: to, _date: {$gte: new Date('2018-04-05T00:00:00.000Z')}}, {templateId: 1, _date: 1, to: 1},function (err, existingEmail) {
if (err) return handleError(err);
if(existingEmail){
console.log("Email to " + to + " already sent at: " + existingEmail._date);
scounter += 1;
asCounter += 1;
if(scounter == nSchools){
console.log('Total Emails sent: ' + eCounter + " out of " + nSchools + " schools! | " + asCounter + " already sent");
}
}else{
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
console.log(' ---- Could not send email! ' + error + " " + response.statusCode);
console.log(sindex + "." + " Email to " + attnName + " | " + thisEmail + " NOT SENT | Id: " + thisSchool._id + " ---- ");
scounter += 1;
if(scounter == nSchools){
console.log('Total Emails sent: ' + eCounter + " out of " + nSchools + " schools! | " + asCounter + " already sent");
}
}else{
var this_email = new email({
school: schoolId,
templateId: templateId,
fromEmail: fromEmail,
to: thisEmail,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
console.log(sindex + "." +" Email to " + attnName + " | " + thisEmail + " sent | Id: " + thisSchool._id);
scounter += 1;
eCounter += 1;
if(scounter == nSchools){
console.log('Total Emails sent: ' + eCounter + " out of " + nSchools + " schools! | " + asCounter + " already sent");
}
});
}
});
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
}
} else {throw err;}
});
});
router.post('/introductionofEB', function(req, res) {
console.log('Starting introduction Email');
var thisEmail = req.body;
var templateName = 'Claim CI Email - 28thNov2017';
var from = thisEmail.from;
//var sender = thisEmail.sender;
var senderId = '59a7eb973d71f10170dbb468';
//sender = 'Always Exambazaar';
var fromEmail = {
email: 'always@exambazaar.com',
name: 'Always Exambazaar'
};
var html = ' ';
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var allCoachings = coaching.find({ disabled: false, email: {$exists: true}, $where:'this.email.length>0'}, {email:1, name: 1},function (err, allCoachings){
if (err) return handleError(err);
var nCoachings = allCoachings.length;
console.log('There are ' + nCoachings + ' coachings!');
var pCounter = 0;
var sentCounter = 0;
var totalCounter = 0;
allCoachings.forEach(function(thisCoaching, pindex){
var eCounter = 0;
var emailArray = thisCoaching.email;
var instituteName = thisCoaching.name;
//var subject = instituteName + " - Get started with Exambazaar!";
var subject = instituteName + " - You are the expert! Would you write for us?";
var instituteId = thisCoaching._id;
var content = new helper.Content('text/html', html);
//console.log('Coaching id is: ' + instituteId);
emailArray.forEach(function(thisEmail, eindex){
//console.log(thisEmail);
//thisEmail = "gaurav@exambazaar.com";
var to_email = new helper.Email(thisEmail);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteName-', instituteName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-instituteId-', instituteId));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
eCounter += 1;
totalCounter += 1;
console.log('Could not send email to: ' + thisEmail);
if(eCounter == emailArray.length){
pCounter += 1;
if(pCounter == allCoachings.length){
console.log('---------All Done---------');
console.log('Emails sent: ' + sentCounter + ' out of ' + eCounter);
res.json(true);
}
}
}else{
var this_email = new email({
institute: instituteId,
user: senderId,
templateId: templateId,
fromEmail: fromEmail,
to: thisEmail,
response: {
status: response.statusCode,
_date: response.headers.date,
xMessageId: response.headers["x-message-id"]
}
});
this_email.save(function(err, this_email) {
if (err) return console.error(err);
//console.log('Email sent with id: ' + this_email._id);
eCounter += 1;
sentCounter += 1;
totalCounter += 1;
console.log('Email sent to: ' + instituteName + ' at ' + this_email.to);
if(eCounter == emailArray.length){
pCounter += 1;
if(pCounter == allCoachings.length){
console.log('---------All Done---------');
console.log('Emails sent: ' + sentCounter + ' out of ' + totalCounter);
res.json(true);
}
}
});
//res.json(response);
}
});
});
});
}).limit(500).skip(3000); //.skip(5)
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/welcomeEmail', function(req, res) {
var thisEmail = req.body;
var templateName = thisEmail.templateName;
var fromEmail = {
email: 'always@exambazaar.com',
name: 'Always Exambazaar'
};
var to = thisEmail.to;
var username = thisEmail.username;
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
console.log(templateId);
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
var html = ' ';
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
res.json(response);
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/verifyEmail', function(req, res) {
var thisEmail = req.body;
var templateName = thisEmail.templateName;
var fromEmail = {
email: 'always@exambazaar.com',
name: 'Always Exambazaar'
};
var to = thisEmail.to;
var username = thisEmail.username;
var userid = thisEmail.userid.toString();
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
console.log(templateId);
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
var html = ' ';
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
mail.personalizations[0].addSubstitution(new helper.Substitution('-userid-', userid));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
res.json(response);
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/contactEmail', function(req, res) {
var thisEmail = req.body;
var templateName = thisEmail.templateName;
var fromEmail = {
email: 'always@exambazaar.com',
name: 'Always Exambazaar'
};
var to = thisEmail.to;
var contactName = thisEmail.contactName;
var contactMobile = thisEmail.contactMobile;
var contactAbout = thisEmail.contactAbout;
var contactMessage = thisEmail.contactMessage;
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
var to_email2 = new helper.Email('team@exambazaar.com');
var html = ' ';
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
var mail2 = new helper.Mail(fromEmail, subject, to_email2, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-contactName-', contactName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-contactEmail-', to));
mail.personalizations[0].addSubstitution(new helper.Substitution('-contactMobile-', contactMobile));
mail.personalizations[0].addSubstitution(new helper.Substitution('-contactAbout-', contactAbout));
mail.personalizations[0].addSubstitution(new helper.Substitution('-contactMessage-', contactMessage));
mail2.setTemplateId(templateId);
mail2.personalizations[0].addSubstitution(new helper.Substitution('-contactName-', contactName));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-contactEmail-', to));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-contactMobile-', contactMobile));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-contactAbout-', contactAbout));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-contactMessage-', contactMessage));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail2.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
res.json(response);
}
});
//res.json(response);
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/bookAppointmentEmail', function(req, res) {
var thisEmail = req.body;
var templateName = thisEmail.templateName;
var fromEmail = {
email: 'team@exambazaar.com',
name: 'Team Exambazaar'
};
var student = thisEmail.student;
var thisCoaching = thisEmail.coaching;
var thisAppointment = thisEmail.appointment;
var coachingId = thisCoaching.institute;
var course = thisEmail.course;
var to = student.email;
var mobile = student.mobile;
console.log(coachingId);
var existingCoaching = coaching.findOne({_id: coachingId}, {address: 1, city:1, state: 1, pincode: 1, mobile:1, phone: 1},function (err, existingCoaching) {
var coachingAddress = existingCoaching.address;
var coachingPhone = '';
var coachingMobile = '';
if(existingCoaching.city){
coachingAddress += ", " + existingCoaching.city;
}
if(existingCoaching.state){
coachingAddress += ", " + existingCoaching.state;
}
if(existingCoaching.pincode){
coachingAddress += ", " + existingCoaching.pincode;
}
if(existingCoaching.phone){
existingCoaching.phone.forEach(function(thisPhone, index){
coachingPhone += thisPhone;
if(index != existingCoaching.phone.length - 1){
coachingPhone += ", ";
}
});
}
if(existingCoaching.mobile){
existingCoaching.mobile.forEach(function(thisMobile, index){
coachingMobile += thisMobile;
if(index != existingCoaching.mobile.length - 1){
coachingMobile += ", ";
}
});
}
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
var to_email2 = new helper.Email('team@exambazaar.com');
var html = ' ';
var subject = student.name + ', you are booking an appointment at ' + thisCoaching.name;
var subject2 = student.name + ' (' + student.mobile + ') '+' is booking an appoitment at ' + thisCoaching.name;
var requestDateTime = moment(thisAppointment._requestDate);
var requestDateTimeFormat = requestDateTime.format('DD-MMM-YYYY HH:mm');
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
var mail2 = new helper.Mail(fromEmail, subject2, to_email2, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-student.name-', student.name));
mail.personalizations[0].addSubstitution(new helper.Substitution('-student.email-', to));
mail.personalizations[0].addSubstitution(new helper.Substitution('-student.mobile-', mobile));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.name-', thisCoaching.name));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.address-', coachingAddress));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.phone-', coachingPhone));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.mobile-', coachingMobile));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.exam-', thisCoaching.exam));
mail.personalizations[0].addSubstitution(new helper.Substitution('-course.name-', course.name));
mail.personalizations[0].addSubstitution(new helper.Substitution('-course.duration-', course.duration));
mail.personalizations[0].addSubstitution(new helper.Substitution('-appointment.dateTime-', requestDateTimeFormat));
mail2.setTemplateId(templateId);
mail2.personalizations[0].addSubstitution(new helper.Substitution('-student.name-', student.name));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-student.email-', to));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-student.mobile-', mobile));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.name-', thisCoaching.name));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.address-', coachingAddress));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.phone-', coachingPhone));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.mobile-', coachingMobile));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.exam-', thisCoaching.exam));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-course.name-', course.name));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-course.duration-', course.duration));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-appointment.dateTime-', requestDateTimeFormat));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail2.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
res.json(response);
}
});
//res.json(response);
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
});
router.post('/availDiscountEmail', function(req, res) {
var thisEmail = req.body;
var templateName = thisEmail.templateName;
var fromEmail = {
email: 'team@exambazaar.com',
name: 'Team Exambazaar'
};
var student = thisEmail.student;
var coaching = thisEmail.coaching;
var course = thisEmail.course;
var to = student.email;
var mobile = student.mobile;
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
var to_email2 = new helper.Email('team@exambazaar.com');
var html = ' ';
var subject = student.name + ', you have applied for discount at ' + coaching.name;
var subject2 = student.name + ' (' + student.mobile + ') '+'has applied for discount at ' + coaching.name;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
var mail2 = new helper.Mail(fromEmail, subject2, to_email2, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-student.name-', student.name));
mail.personalizations[0].addSubstitution(new helper.Substitution('-student.email-', to));
mail.personalizations[0].addSubstitution(new helper.Substitution('-student.mobile-', mobile));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.name-', coaching.name));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.city-', coaching.city));
mail.personalizations[0].addSubstitution(new helper.Substitution('-coaching.exam-', coaching.exam));
mail.personalizations[0].addSubstitution(new helper.Substitution('-course.name-', course.name));
mail.personalizations[0].addSubstitution(new helper.Substitution('-course.duration-', course.duration));
mail2.setTemplateId(templateId);
mail2.personalizations[0].addSubstitution(new helper.Substitution('-student.name-', student.name));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-student.email-', to));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-student.mobile-', mobile));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.name-', coaching.name));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.city-', coaching.city));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-coaching.exam-', coaching.exam));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-course.name-', course.name));
mail2.personalizations[0].addSubstitution(new helper.Substitution('-course.duration-', course.duration));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail2.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
res.json(response);
}
});
//res.json(response);
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/recruitmentEmail', function(req, res) {
var thisEmail = req.body;
var fromEmail = {
email: 'team@exambazaar.com',
name: 'Team Exambazaar'
};
var templateName = thisEmail.templateName;
var to = thisEmail.to;
var collegename = thisEmail.collegename;
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(to);
var to_email2 = new helper.Email('team@exambazaar.com');
var html = ' ';
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
var mail2 = new helper.Mail(fromEmail, subject, to_email2, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-collegename-', collegename));
mail2.setTemplateId(templateId);
mail2.personalizations[0].addSubstitution(new helper.Substitution('-collegename-', collegename));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail2.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
res.json(response);
}
});
}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/hundredblogEmail', function(req, res) {
//var thisEmail = req.body;
console.log('Starting 100 blogs Email');
var fromEmail = {
email: 'team@exambazaar.com',
name: 'Team Exambazaar'
};
var templateName = '100 Blogs';
//var to = thisEmail.to;
//var username = thisEmail.username;
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var allUsers = user.find({email: {$exists: true}}, {basic: 1, email: 1, _id: 1}, function(err, allUsers) {
if (!err){
var emailcounter = 0;
var counter = 0;
var nUsers = allUsers.length;
console.log("Total " + nUsers + " users!");
allUsers.forEach(function(thisUser, index){
var to = thisUser.email;
var username = "User";
if(thisUser.basic && thisUser.basic.name){
username = thisUser.basic.name;
}
var to_email = new helper.Email(to);
var html = ' ';
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
//console.log("Sending Email to: " + username + " at " + to);
if(thisUser.email && thisUser.email != ''){
/*sg.API(request, function(error, response) {
if(error){
counter += 1;
console.log('Could not send email! to: ' + thisUser.email);
}else{
counter += 1;
emailcounter += 1;
console.log(counter + " Email sent to: " + username + " at " + to);
if(counter == nUsers){
console.log("Total emails sent are: " + emailcounter);
res.json(true);
}
//res.json(response);
}
});*/
}else{
counter += 1;
if(counter == nUsers){
res.json(true);
}
}
/**/
});
} else {throw err;}
});
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/internshipEmail', function(req, res) {
var thisEmail = req.body;
var html = ' ';
if(thisEmail.body){
html = thisEmail.body;
}
var emailList = thisEmail.emailList;
var templateName = thisEmail.templateName;
var nEmails = emailList.length;
var counter = 0;
var emailcounter = 0;
console.log('Starting Internship Email');
var fromEmail = {
email: 'team@exambazaar.com',
name: 'Team Exambazaar'
};
//var templateName = 'Internship at Exambazaar';
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
emailList.forEach(function(thisEmail, index){
var to = thisEmail;
var to_email = new helper.Email(to);
var subject = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
counter += 1;
console.log('Could not send email! to: ' + to);
if(counter == nEmails){
console.log("Total emails sent are: " + emailcounter);
res.json(true);
}
}else{
counter += 1;
emailcounter += 1;
console.log(counter + " Email sent to: " + to);
if(counter == nEmails){
console.log("Total emails sent are: " + emailcounter);
res.json(true);
}
}
});
});
}
});
if(nLength == 0){
res.json(false);
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
router.post('/CATEmail', function(req, res) {
console.log('Starting CAT 2017 Email');
//var thisUser = req.body._id.toString();
//console.log(thisUser);
var fromEmail = {
email: 'always@exambazaar.com',
name: 'Always Exambazaar'
};
var templateName = 'CAT 2017';
res.json(true);
/*var groupNames = college.aggregate(
[
{$match: {} },
{"$group": { "_id": { state: "$Institute.Correspondence Details.State", district: "$Institute.Correspondence Details.District" }, count:{$sum:1} } },
{$sort:{"count":-1}}
],function(err, groupNames) {
if (!err){
//groupNames = groupNames.slice(0, 20);
//console.log(groupNames);
var queryGroups = [];
groupNames.forEach(function(thisGroup, index){
var qGroup = {
state: thisGroup._id.state,
district: thisGroup._id.district,
centers: thisGroup.count,
};
console.log(thisGroup._id.state + "|" + thisGroup._id.district + "|" + thisGroup.count);
//queryGroups.push(qGroup);
});
//console.log(queryGroups);
//res.json(queryGroups);
} else {throw err;}
});*/
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
/*var allUsers = user.find({email: {$exists: true}}, {basic: 1, email: 1, _id: 1}, function(err, allUsers) {
if (!err){
var emailcounter = 0;
var counter = 0;
var nUsers = allUsers.length;
console.log("Total " + nUsers + " users!");
allUsers.forEach(function(thisUser, index){
var to = thisUser.email;
var username = "Student";
var subject = "Hola! Ready for CAT 2017? We've got some goodies for you!";
if(thisUser.basic && thisUser.basic.name){
username = thisUser.basic.name;
subject = username + ", ready for CAT 2017? We've got some goodies for you!";
}
var to_email = new helper.Email(to);
var html = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
if(thisUser.email && thisUser.email != ''){
console.log('Sending email to ' + username + ' at ' + to);
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
counter += 1;
console.log(counter + "/" + nUsers + " done!");
if(counter == nUsers){
console.log('All Done');
}
}
});
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
});
} else {throw err;}
});*/
//email: {$exists: true}
var allSubscribers = subscriber.find({_created: {$gte: new Date('2017-11-15T00:00:00.000Z')}}, {name: 1, email: 1, _id: 1, mobile:1}, function(err, allSubscribers) {
if (!err){
var emailcounter = 0;
var counter = 0;
var nUsers = allSubscribers.length;
console.log("Total " + allSubscribers + " users!");
allSubscribers.forEach(function(thisUser, index){
var to = thisUser.email;
var username = "Student";
var subject = "Hola! Ready for CAT 2017? We've got some goodies for you!";
if(thisUser.name){
username = thisUser.name;
subject = username + ", ready for CAT 2017? We've got some goodies for you!";
}
var to_email = new helper.Email(to);
var html = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
if(thisUser.email && thisUser.email != ''){
console.log('Sending email to ' + username + ' at ' + to);
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
counter += 1;
console.log(counter + "/" + nUsers + " done!");
if(counter == nUsers){
console.log('All Done');
}
}
});
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
});
} else {throw err;}
});
/*var allColleges = college.find({}, {Institute: 1, inst_name: 1}, function(err, allColleges){
if (!err){
var emailcounter = 0;
var counter = 0;
var nUsers = allColleges.length;
console.log("Total " + allColleges.length + " colleges!");
//console.log(collegename);
allColleges.forEach(function(thisCollege, index){
var contactEmails = [];
var facultyEmails = [];
var collegename = thisCollege.inst_name;//.toProperCase();
if(thisCollege['Institute'] && thisCollege['Institute']['Contact Person'] && thisCollege['Institute']['Contact Person']['Email']){
contactEmails.push(thisCollege['Institute']['Contact Person']['Email']);
}
if(thisCollege['Institute'] && thisCollege['Institute']['Correspondence Details'] && thisCollege['Institute']['Correspondence Details']['District']){
console.log(collegename + " | " + thisCollege['Institute']['Correspondence Details']['District'] + " | " + contactEmails.length + " emails!");
}
//console.log("http://www.knowyourcollege-gov.in/InstituteDetails.php?insti_id=" + thisCollege.insti_id );
//console.log(contactEmails);
//contactEmails = ['gaurav@exambazaar.com'];
var username = "Student";
var subject = "Ready for CAT 2017? We've got some goodies!";
contactEmails.forEach(function(thisEmail, index){
if(thisEmail && thisEmail != ''){
var to = thisEmail;
var to_email = new helper.Email(to);
var html = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
mail.personalizations[0].addSubstitution(new helper.Substitution('-collegename-', collegename));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
if(to && to != ''){
//console.log();
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
//console.log(response);
counter += 1;
console.log('Sending email to ' + username + ' at ' + to + " | " + counter + "/" + nUsers + " done!");
if(counter == nUsers){
console.log('All Done');
}
}
});
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
});
});
} else {throw err;}
}).skip(10000).limit(1000);*/
}
if(counter == nLength){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
});
if(nLength == 0){
if(!templateFound){
res.json('Could not send email as there is no template with name: ' + templateName);
}
}
}else{
res.json('No Active SendGrid API Key');
}
});
});
router.post('/EventsEmail', function(req, res) {
console.log('Starting Events Email');
var fromEmail = {
email: 'team@exambazaar.com',
name: 'Team Exambazaar'
};
var templateName = 'Events';
res.json(true);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
//email: {$exists: true}, mobile: "9829685919"
var limit = 200;
var skip = 3200;
var allUsers = user.find({email: {$exists: true}}, {basic: 1, email: 1, _id: 1}, function(err, allUsers) {
if (!err){
var emailcounter = 0;
var counter = 0;
var nUsers = allUsers.length;
console.log("Total " + nUsers + " users!");
allUsers.forEach(function(thisUser, index){
var to = thisUser.email;
var username = "Student";
var subject = " ";
if(thisUser.basic && thisUser.basic.name){
username = thisUser.basic.name;
}
var to_email = new helper.Email(to);
var html = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
if(thisUser.email && thisUser.email != ''){
sg.API(request, function(error, response) {
if(error){
counter += 1;
console.log(index + '. Could not send email! ' + error);
}else{
counter += 1;
emailcounter += 1;
console.log(index + '. Email sent to ' + username + ' at ' + to);
//console.log(counter + "/" + nUsers + " done!");
if(counter == nUsers){
console.log("Total " + emailcounter + " emails delivered " + " out of " + counter + " attempts!" );
//console.log('All Done');
}
}
});
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
});
} else {throw err;}
}).limit(limit).skip(skip);
}
if(counter == nLength){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
});
if(nLength == 0){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
}else{
console.log('No Active SendGrid API Key');
res.json(false);
}
});
});
router.post('/coachingDiscountEmail', function(req, res) {
console.log('Starting Coaching Discount Email');
var fromEmail = {
email: 'team@exambazaar.com',
name: 'Team Exambazaar'
};
var templateName = 'Coaching Discount';
res.json(true);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
//email: {$exists: true}, mobile: "9829685919"
var limit = 500;
var skip = 3000;
var allUsers = user.find({email: {$exists: true}}, {basic: 1, email: 1, _id: 1}, function(err, allUsers) {
if (!err){
var emailcounter = 0;
var counter = 0;
var nUsers = allUsers.length;
console.log("Total " + nUsers + " users!");
allUsers.forEach(function(thisUser, index){
var to = thisUser.email;
var username = "Student";
var subject = " ";
if(thisUser.basic && thisUser.basic.name){
username = thisUser.basic.name;
}
var to_email = new helper.Email(to);
var html = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
if(thisUser.email && thisUser.email != ''){
sg.API(request, function(error, response) {
if(error){
counter += 1;
console.log(index + '. Could not send email! ' + error);
}else{
counter += 1;
emailcounter += 1;
console.log(index + '. Email sent to ' + username + ' at ' + to);
//console.log(counter + "/" + nUsers + " done!");
if(counter == nUsers){
console.log("Total " + emailcounter + " emails delivered " + " out of " + counter + " attempts!" );
//console.log('All Done');
}
}
});
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
});
} else {throw err;}
}).limit(limit).skip(skip);
}
if(counter == nLength){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
});
if(nLength == 0){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
}else{
console.log('No Active SendGrid API Key');
res.json(false);
}
});
});
router.post('/OfficialPapersEmail', function(req, res) {
console.log('Starting Official Papers Email');
var fromEmail = {
email: 'always@exambazaar.com',
name: 'Always Exambazaar'
};
var templateName = 'Official Question Papers';
res.json(true);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var limit = 200;
var skip = 0;
//email: {$exists: true}, mobile: "9829685919"
var allUsers = user.find({email: {$exists: true}, mobile: "9829685919"}, {basic: 1, email: 1, _id: 1}, function(err, allUsers) {
if (!err){
var emailcounter = 0;
var counter = 0;
var nUsers = allUsers.length;
console.log("Total " + nUsers + " users!");
allUsers.forEach(function(thisUser, index){
var to = thisUser.email;
var username = "Student";
var subject = " ";
if(thisUser.basic && thisUser.basic.name){
username = thisUser.basic.name;
}
var to_email = new helper.Email(to);
var html = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-username-', username));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
if(thisUser.email && thisUser.email != ''){
sg.API(request, function(error, response) {
if(error){
counter += 1;
console.log(index + '. Could not send email! ' + error);
console.log(response);
if(counter == nUsers){
console.log("Total " + emailcounter + " emails delivered " + " out of " + counter + " attempts!" );
//console.log('All Done');
}
}else{
counter += 1;
emailcounter += 1;
console.log(index + '. Email sent to ' + username + ' at ' + to);
//console.log(counter + "/" + nUsers + " done!");
if(counter == nUsers){
console.log("Total " + emailcounter + " emails delivered " + " out of " + counter + " attempts!" );
//console.log('All Done');
}
}
});
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
});
} else {throw err;}
}).limit(limit).skip(skip);
}
if(counter == nLength){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
});
if(nLength == 0){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
}else{
console.log('No Active SendGrid API Key');
res.json(false);
}
});
});
router.post('/OfficialPapersEmailUnsolicited', function(req, res) {
console.log('Starting Official Papers Email Unsolicited');
var fromEmail = {
email: 'always@exambazaar.com',
name: 'Always Exambazaar'
};
var templateName = 'Official Question Papers';
res.json(true);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var allUsers = [];
var emailcounter = 0;
var counter = 0;
var skip = 0;
var limit = 200;
var nUsers = allUsers.length;
if(limit < nUsers){
nUsers = limit;
}
console.log("Total " + nUsers + " users!");
allUsers.forEach(function(thisUser, index){
if(index >= skip && index < skip + limit){
var to = thisUser;
var username = "Student";
var subject = " ";
var to_email = new helper.Email(to);
var html = ' ';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
if(thisUser && thisUser != ''){
sg.API(request, function(error, response) {
if(error){
counter += 1;
console.log(index + '. Could not send email! ' + error);
if(counter == nUsers){
console.log("Total " + emailcounter + " emails delivered " + " out of " + counter + " attempts!" );
}
}else{
counter += 1;
emailcounter += 1;
console.log(index + '. Email sent at ' + to);
if(counter == nUsers){
console.log("Total " + emailcounter + " emails delivered " + " out of " + counter + " attempts!" );
//console.log('All Done');
}
}
});
}else{
counter += 1;
if(counter == nUsers){
console.log('All Done');
}
}
}
});
}
if(counter == nLength){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
});
if(nLength == 0){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
}else{
console.log('No Active SendGrid API Key');
res.json(false);
}
});
});
router.get('/', function(req, res) {
email
.find({ })
//.deepPopulate('stream')
.exec(function (err, docs) {
if (!err){
//var examNames = docs.map(function(a) {return a.name;});
//console.log(examNames);
res.json(docs);
} else {throw err;}
});
});
router.post('/internshipOffer', function(req, res) {
var thisEmail = req.body;
console.log(thisEmail);
var templateName = thisEmail.templateName;
var userName = thisEmail.userName;
var internship_title = thisEmail.internship_title;
var internship_description = thisEmail.internship_description;
var stipend = thisEmail.stipend;
var start_date = thisEmail.start_date;
var requestDateTime = moment(start_date);
var requestDateTimeFormat = requestDateTime.format('DD-MMM-YYYY');
start_date = requestDateTimeFormat;
var senderId = thisEmail.senderId;
var fromEmail = {
email: thisEmail.from,
name: thisEmail.sender
};
//res.json(true);
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential){
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
var emailTemplate = existingSendGridCredential.emailTemplate;
var templateFound = false;
var nLength = emailTemplate.length;
var counter = 0;
var templateId;
emailTemplate.forEach(function(thisEmailTemplate, index){
if(thisEmailTemplate.name == templateName){
templateFound = true;
templateId = thisEmailTemplate.templateKey;
var from_email = new helper.Email(fromEmail);
var to = thisEmail.to;
var cc = thisEmail.cc;
var username = thisEmail.userName;
var subject = thisEmail.subject;
var to_email = new helper.Email(to);
var cc_email = new helper.Email(cc);
var html = thisEmail.html;
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(fromEmail, subject, to_email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-userName-', userName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-internshipTitle-', internship_title));
mail.personalizations[0].addSubstitution(new helper.Substitution('-internshipDescription-', internship_description));
mail.personalizations[0].addSubstitution(new helper.Substitution('-stipend-', stipend));
mail.personalizations[0].addSubstitution(new helper.Substitution('-startingDate-', start_date));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + thisEmail.to + " " + error);
console.log(response);
res.json(false);
}else{
console.log('Email sent to ' + username + ' at ' + to);
var ccSubject = "COPY: " + subject;
var ccmail = new helper.Mail(fromEmail, ccSubject, cc_email, content);
ccmail.setTemplateId(templateId);
ccmail.personalizations[0].addSubstitution(new helper.Substitution('-userName-', userName));
ccmail.personalizations[0].addSubstitution(new helper.Substitution('-internshipTitle-', internship_title));
ccmail.personalizations[0].addSubstitution(new helper.Substitution('-internshipDescription-', internship_description));
ccmail.personalizations[0].addSubstitution(new helper.Substitution('-stipend-', stipend));
ccmail.personalizations[0].addSubstitution(new helper.Substitution('-startingDate-', start_date));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: ccmail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + thisEmail.to + " " + error);
res.json(false);
}else{
console.log('Email sent to ' + username + ' at ' + cc);
res.json(true);
}
});
}
});
}
if(counter == nLength){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
});
if(nLength == 0){
if(!templateFound){
console.log('Could not send email as there is no template with name: ' + templateName);
res.json(false);
}
}
}else{
console.log('No Active SendGrid API Key');
res.json(false);
}
});
});
function generateEQADString(eqad){
question = eqad.question;
var nQuestions = question.questions.length;
var nImages = 0;
if(question.images){
nImages = question.images.length;
}
var miniseparator = "<br/>";
var separator = "<br/><br/>";
var boldStart = "<b>";
var boldEnd = "</b>";
var sectionseparator = "";//separator + "---" + separator;
var pstext = "";//separator + "_______________" + separator;
var ebprefix = "https://www.exambazaar.com/";
var preQText = "";//eqad.exam.exam_page_name + " EQAD " + " " + moment(eqad._scheduled).format("DD-MMM-YY") + miniseparator;
var eqadQType = "";
if(question.questions[0].type == 'mcq'){
if(question.questions[0].mcqma){
eqadQType = "MCQ with multiple correct";
}else{
eqadQType = "MCQ";
}
}else if(question.questions[0].type == 'numerical'){
eqadQType = "Numerical";
}
eqadQType = " " + eqadQType + " ";
preQText = preQText + eqadQType + " Question, as appeared in " + question.test.name + miniseparator;
preQText = boldStart + preQText + boldEnd + miniseparator;
var eqadSectionHashTag = "#" + eqad.examsection.name.replace(" ", "");
var examYearHashTag = "#" + eqad.exam.exam_page_name.replace(" ", "") + question.test.year;
var paperQText = "";
if(question.questions.length > 1){
paperQText = "Question Group: " + question._startnumber + " - " + question._endnumber + " ";
}else{
paperQText = "Question " + question._startnumber + " ";
}
var totalQtexts = [];
if(question.context && question.context.length > 10){
totalQtexts.push(question.context + separator);
}
if(question.images && question.images.length > 0){
question.images.forEach(function(thisImage, iIndex){
var thisImageTag = "<img style='max-width: 500px;' src='" + thisImage + "'/>";
totalQtexts.push(thisImageTag + separator);
});
}
question.questions.forEach(function(thisQuestion, index){
var qno = index + 1;
var Qtext = "Q" + qno + ". " + thisQuestion.question + separator;
var Otext = "";
if(thisQuestion.type == "mcq"){
var optionPrefixes = ["A. ", "B. ", "C. ", "D. ", "E. ", "F. ", "G. "];
var optionString = [];
var options = thisQuestion.options;
options.forEach(function(thisOption, index){
var nextOption = optionPrefixes[index] + thisOption.option + miniseparator;
Otext += nextOption;
});
if(thisQuestion.mcqma){
Otext = Otext + miniseparator + "(multiple correct answers)";
}
Otext = Otext + miniseparator;
}else{
Otext = "Answer is numerical & needs to be typed in the Exam Interface" + separator;
}
var totalQtext = Qtext + Otext;
totalQtexts.push(totalQtext);
});
var allQText = '';
totalQtexts.forEach(function(thisQuestionPart, index){
allQText += thisQuestionPart;
});
var eqadLink = ebprefix + eqad.urlslug;
var postOText = "Did you get it right? Attempt and find solution at " + eqadLink;
var testLink = "https://www.exambazaar.com/assessment/" + question.test.urlslug;
var testLink = "Want to crack " + eqad.exam.exam_page_name + "? Attempt " + question.test.name + " for free at " + testLink;
var thisPageHashTags = [];
/*if(page && page.hashtags){
page.hashtags.forEach(function(thisHashTag, index){
thisPageHashTags.push(thisHashTag);
});
}*/
thisPageHashTags.push(eqadSectionHashTag);
thisPageHashTags.push(examYearHashTag);
var hashTagsList = ['#eqad', '#exambazaar'];
thisPageHashTags = thisPageHashTags.concat(hashTagsList);
var hashTags = "";
thisPageHashTags.forEach(function(thisHashTag, index){
hashTags = hashTags + thisHashTag;
if(index != thisPageHashTags.length - 1){
hashTags = hashTags + " ";
}
});
var divStart = "<div style='padding: 20px;border: 1px solid #dcdcdc;margin-bottom:40px;'>"; //background-color: #f1f1f1;
var divEnd = "</div>";
var postQText = sectionseparator + postOText + pstext + testLink + separator + hashTags;
var postString = divStart + preQText + allQText + divEnd;
return(postString);
};
router.post('/eqadIntroduction', function(req, res){
res.json(true);
console.log('Starting EQAD Introduction Email');
var userInfo = req.body;
var userId = userInfo.user;
var limit = 0;
var skip = 0;
var eCounter = 0;
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
if(existingSendGridCredential && existingSendGridCredential.emailTemplate && existingSendGridCredential.emailTemplate.length > 0){
var templateNames = existingSendGridCredential.emailTemplate.map(function(a) {return a.name;});
var tIndex = templateNames.indexOf("EQAD Introduction");
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
if(tIndex != -1){
var templateId = existingSendGridCredential.emailTemplate[tIndex].templateKey;
var allUsers = user.find({email: {$exists: true}}, {"basic.name": 1, email: 1, _id: 1}, function(err, allUsers){
allUsers.forEach(function(thisUser, uindex){
if(thisUser && thisUser.email){
var userName = thisUser.basic.name;
var toEmail = {
email: thisUser.email,
name: userName,
};
var fromEmail = {
email: "always@exambazaar.com",
name: "Always Exambazaar",
};
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(toEmail);
var htmlCode = " ";
var subject = " ";
var content = new helper.Content('text/html', htmlCode);
//console.log(htmlCode);
var mail = new helper.Mail(from_email.email, subject, to_email.email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-userName-', userName));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
console.log('Could not send email! ' + error);
}else{
/*console.log("Code is: " + response.statusCode);
console.log("Body is: " + response.body);
console.log("Headers are: " + JSON.stringify(response.headers));
console.log(JSON.stringify(response));*/
eCounter += 1;
console.log(eCounter + ". Email sent to " + userName + " at " + thisUser.email);
}
});
}
});
}).limit(limit).skip(skip);
}
}
});
});
router.post('/coachingReview', function(req, res){
res.json(true);
console.log('Starting Coaching Review Email');
var userInfo = req.body;
var userId = userInfo.user;
var limit = 500;
var skip = 7000;
var eCounter = 0;
var errorCounter = 0;
var oCounter = 0;
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
console.log("Limit: " + limit + " | Skip: " + skip);
if(existingSendGridCredential && existingSendGridCredential.emailTemplate && existingSendGridCredential.emailTemplate.length > 0){
var templateNames = existingSendGridCredential.emailTemplate.map(function(a) {return a.name;});
var tIndex = templateNames.indexOf("Review Promotional Email");
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
if(tIndex != -1){
var templateId = existingSendGridCredential.emailTemplate[tIndex].templateKey;
var allUsers = user.find({email: {$exists: true}}, {"basic.name": 1, email: 1, _id: 1}, function(err, allUsers){
var nUsers = allUsers.length;
if(nUsers == 0){
console.log("No more users!");
}
allUsers.forEach(function(thisUser, uindex){
if(thisUser && thisUser.email){
var userName = thisUser.basic.name;
var toEmail = {
email: thisUser.email,
name: userName,
};
var fromEmail = {
email: "always@exambazaar.com",
name: "Always Exambazaar",
};
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(toEmail);
var htmlCode = " ";
var subject = " ";
var content = new helper.Content('text/html', htmlCode);
//console.log(htmlCode);
var mail = new helper.Mail(from_email.email, subject, to_email.email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-userName-', userName));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
errorCounter += 1;
oCounter += 1;
console.log("#" + errorCounter + '. Could not send email! ' + error);
}else{
/*console.log("Code is: " + response.statusCode);
console.log("Body is: " + response.body);
console.log("Headers are: " + JSON.stringify(response.headers));
console.log(JSON.stringify(response));*/
eCounter += 1;
oCounter += 1;
var sentCounter = skip + eCounter;
console.log(sentCounter + ". Email sent to " + userName + " at " + thisUser.email);
if(oCounter == nUsers){
console.log("-------------- All Done --------------");
}
}
});
}
});
}).limit(limit).skip(skip);
}
}
});
});
function totalUserCount(){
user.count({}, function(err, docs){
if (!err){
var res = {
users:{
all: docs,
},
};
prevDayUserCount(res);
} else {throw err;}
});
};
function prevDayUserCount(res){
var start = moment().subtract(1, 'day').startOf('day');
var end = moment().subtract(1, 'day').endOf('day');
user.count({_created: { $gte : start, $lte : end}}, function(err, docs){
if (!err){
res.users.prevDay = docs;
totalViewCount(res);
} else {throw err;}
});
};
function totalViewCount(res){
view.count({}, function(err, docs){
if (!err){
res.views = {
all: docs
};
prevDayViewCount(res);
} else {throw err;}
});
};
function prevDayViewCount(res){
var start = moment().subtract(1, 'day').startOf('day');
var end = moment().subtract(1, 'day').endOf('day');
view.count({_date: { $gte : start, $lte : end}}, function(err, docs){
if (!err){
res.views.prevDay = docs;
totalProviderCount(res);
} else {throw err;}
});
};
function totalProviderCount(res){
coaching.count({}, function(err, docs){
if (!err){
res.providers = {
all: docs,
};
prevDayProviderCount(res);
} else {throw err;}
});
};
function prevDayProviderCount(res){
var start = moment().subtract(1, 'day').startOf('day');
var end = moment().subtract(1, 'day').endOf('day');
coaching.count({_created: { $gte : start, $lte : end}}, function(err, docs){
if (!err){
res.providers.prevDay= docs;
totalReviewCount(res);
} else {throw err;}
});
};
function totalReviewCount(res){
review.count({}, function(err, docs){
if (!err){
res.reviews = {
all: docs
};
prevDayReviewCount(res);
} else {throw err;}
});
};
function prevDayReviewCount(res){
var start = moment().subtract(1, 'day').startOf('day');
var end = moment().subtract(1, 'day').endOf('day');
review.count({_date: { $gte : start, $lte : end}}, function(err, docs){
if (!err){
res.reviews.prevDay = docs;
totalQuestionCount(res);
} else {throw err;}
});
};
function totalQuestionCount(res){
question.count({}, function(err, docs){
if (!err){
res.questions = {
all: docs
};
prevDayQuestionCount(res);
} else {throw err;}
});
};
function prevDayQuestionCount(res){
var start = moment().subtract(1, 'day').startOf('day');
var end = moment().subtract(1, 'day').endOf('day');
question.count({_created: { $gte : start, $lte : end}}, function(err, docs){
if (!err){
res.questions.prevDay = docs;
totalBlogCount(res);
} else {throw err;}
});
};
function totalBlogCount(res){
blogpost.count({active: true}, function(err, docs){
if (!err){
res.blogs = {
all: docs
};
prevDayBlogCount(res);
} else {throw err;}
});
};
function prevDayBlogCount(res){
var start = moment().subtract(1, 'day').startOf('day');
var end = moment().subtract(1, 'day').endOf('day');
blogpost.count({_created: { $gte : start, $lte : end}, active: true}, function(err, docs){
if (!err){
res.blogs.prevDay = docs;
router.procmon(res);
} else {throw err;}
});
};
router.procmon = function(stats){
var emailForm = {
toEmail: {
email: "team@exambazaar.com",
name: "Team Exambazaar",
},
fromEmail:{
email: "gaurav@exambazaar.com",
name: "Gaurav Parashar",
},
templateId: "b4c39ee6-7fa6-4611-a85a-a3cbfb89868b",
personalizations: {
'-runtime-': moment().tz("Asia/Calcutta").format("MMMM Do YYYY, h:mm:ss a"),
'-totalusers-': stats.users.all,
'-usersaddedprevDay-': stats.users.prevDay,
'-totalviews-': stats.views.all,
'-viewsprevDay-': stats.views.prevDay,
'-totalproviders-': stats.providers.all,
'-providersprevDay-': stats.providers.prevDay,
'-totalreviews-': stats.reviews.all,
'-reviewsprevDay-': stats.reviews.prevDay,
'-totalquestions-': stats.questions.all,
'-questionsprevDay-': stats.questions.prevDay,
'-totalblogs-': stats.blogs.all,
'-blogsprevDay-': stats.blogs.prevDay,
},
html: " ",
subject: "EB Procmon Report for: " + moment().subtract(1, 'day').format("DD-MMM-YY") + " | Run at: " + moment().tz("Asia/Calcutta").format("MMMM Do YYYY, h:mm:ss a"),
_requested: moment().toDate(),
};
send_email(emailForm, true);
};
router.get('/cron/summaryEmail', function(req, res){
console.log("Called Cron Job");
res.json(true);
totalUserCount();
});
router.post('/eqadDaily', function(req, res){
console.log('Starting Daily EQAD Email');
var userExam = req.body;
var userId = userExam.user;
var examId = userExam.exam;
var _date = moment();
var _dateString = moment(_date).format("DD-MMM-YYYY");
var _dateStart = moment(_date).startOf('day');
var _dateEnd = moment(_date).endOf('day');
var thisUser = user.findOne({_id: userId}, {"basic.name": 1, email: 1, _id: 1}, function(err, thisUser){
if(thisUser){
var userName = thisUser.basic.name;
var toEmail = {
email: thisUser.email,
name: thisUser.name,
};
var fromEmail = {
email: "always@exambazaar.com",
name: "Always Exambazaar",
};
var EmailEQADURL = "";
var existingSendGridCredential = sendGridCredential.findOne({ 'active': true},function (err, existingSendGridCredential) {
if (err) return handleError(err);
//var examId = "58ac288cb9ae260088289996";
var thisExam = exam.findOne({_id: examId}, {exam_page_name: 1}, function(err, thisExam){
if(thisExam){
var thisExamId = thisExam._id;
var subject = thisExam.exam_page_name + " EQAD Daily " + moment(_date).format("DD-MMM-YY");
var allEQADs = eqad
.find({exam: thisExamId, _scheduled: {$lte: _dateEnd, $gte: _dateStart}},{})
.sort('_scheduled')
.deepPopulate("examsection question question.test")
.exec(function (err, allEQADs) {
if(allEQADs){
var divStart = "<div>";
var aStart = "<a>";
var h2Start = "<h2>";
var h3Start = "<h3 style='color:#20C39A;'>";
var divEnd = "</div>";
var aEnd = "</a>";
var h2End = "</h2>";
var h3End = "</h3>";
var htmlCode = "<h2 style='margin-bottom:20px;margin-bottom:20px;font-weight:bold;'>" + subject + "</h2>";
allEQADs.forEach(function(thisEQAD, eIndex){
thisEQAD.exam = thisExam;
var eqadQuestionString = generateEQADString(thisEQAD);
var eqadString = h3Start + thisEQAD.examsection.name.toUpperCase() + h3End;
var thisEQADURL = "https://www.exambazaar.com/" + thisEQAD.urlslug;
if(eIndex == 0){
EmailEQADURL = thisEQADURL;
}
eqadString += "<a style='color: black;text-decoration:none;' href='" + thisEQADURL + "'>" + divStart + eqadQuestionString + divEnd + aEnd;
//console.log(eqadString);
htmlCode = htmlCode + eqadString;
if(eIndex == allEQADs.length - 1){
var formStart = "<div style='width: 100%;padding-top: 20px;padding-bottom: 100px;'><a style='cursor:pointer;' href='" + EmailEQADURL + "'>";
var formEnd = "</a></div>"
var buttonCode = "<button style='background-color:#20C39A;border: 0px;color: white;font-weight: bold;padding:20px;width: 100%;font-size:16px;cursor:pointer;font-color:white;'>Check Your Score</button>";
htmlCode = htmlCode + formStart + buttonCode + formEnd;
if(existingSendGridCredential && existingSendGridCredential.emailTemplate && existingSendGridCredential.emailTemplate.length > 0){
var templateNames = existingSendGridCredential.emailTemplate.map(function(a) {return a.name;});
var tIndex = templateNames.indexOf("EQAD Daily");
var apiKey = existingSendGridCredential.apiKey;
var sg = require("sendgrid")(apiKey);
if(tIndex != -1){
var templateId = existingSendGridCredential.emailTemplate[tIndex].templateKey;
var from_email = new helper.Email(fromEmail);
var to_email = new helper.Email(toEmail);
var content = new helper.Content('text/html', htmlCode);
//console.log(htmlCode);
var mail = new helper.Mail(from_email.email, subject, to_email.email, content);
mail.setTemplateId(templateId);
mail.personalizations[0].addSubstitution(new helper.Substitution('-userName-', userName));
mail.personalizations[0].addSubstitution(new helper.Substitution('-examName-', thisExam.exam_page_name));
mail.personalizations[0].addSubstitution(new helper.Substitution('-date-', _dateString));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});
sg.API(request, function(error, response) {
if(error){
res.json('Could not send email! ' + error);
}else{
console.log("Code is: " + response.statusCode);
console.log("Body is: " + response.body);
console.log("Headers are: " + JSON.stringify(response.headers));
console.log(JSON.stringify(response));
res.json(true);
}
});
}
}
}
});
}
});
}
});
});
}
});
});
function sendDailyEQADEmail(userExam){
//console.log('Starting Daily EQAD Email');
//var userExam = req.body;
var userId = userExam.user;
var examId = userExam.exam;
var _date = moment().tz("Asia/Calcutta");
var _dateString = moment(_date).tz("Asia/Calcutta").format("DD-MMM-YYYY");
var _dateStart = moment(_date).tz("Asia/Calcutta").startOf('day');
var _dateEnd = moment(_date).tz("Asia/Calcutta").endOf('day');
var thisUser = user.findOne({_id: userId}, {"basic.name": 1, email: 1, _id: 1}, function(err, thisUser){
if(thisUser && thisUser.email && validateEmail(thisUser.email)){
var userName = thisUser.basic.name;
var toEmail = {
email: thisUser.email,
name: thisUser.name,
};
var EmailEQADURL = "";
var thisExam = exam.findOne({_id: examId}, {exam_page_name: 1}, function(err, thisExam){
if(thisExam){
var thisExamId = thisExam._id;
var fromEmail = {
email: "eqad@exambazaar.com",
name: "Daily " + thisExam.exam_page_name + " EQAD by Exambazaar",
};
var subject = thisExam.exam_page_name + " EQAD Daily " + moment(_date).tz("Asia/Calcutta").format("DD-MMM-YY");
var allEQADs = eqad
.find({exam: thisExamId, _scheduled: {$lte: _dateEnd, $gte: _dateStart}},{})
.sort('_scheduled')
.deepPopulate("examsection question question.test")
.exec(function (err, allEQADs) {
if(allEQADs){
var divStart = "<div>";
var aStart = "<a>";
var h2Start = "<h2>";
var h3Start = "<h3 style='color:#20C39A;'>";
var divEnd = "</div>";
var aEnd = "</a>";
var h2End = "</h2>";
var h3End = "</h3>";
var htmlCode = "<h2 style='margin-bottom:20px;margin-bottom:20px;font-weight:bold;'>" + subject + "</h2>";
allEQADs.forEach(function(thisEQAD, eIndex){
thisEQAD.exam = thisExam;
var eqadQuestionString = generateEQADString(thisEQAD);
var eqadString = h3Start + thisEQAD.examsection.name.toUpperCase() + h3End;
var thisEQADURL = "https://www.exambazaar.com/" + thisEQAD.urlslug;
if(eIndex == 0){
EmailEQADURL = thisEQADURL;
}
eqadString += "<a style='color: black;text-decoration:none;' href='" + thisEQADURL + "'>" + divStart + eqadQuestionString + divEnd + aEnd;
//console.log(eqadString);
htmlCode = htmlCode + eqadString;
if(eIndex == allEQADs.length - 1){
var formStart = "<div style='width: 100%;padding-top: 20px;padding-bottom: 100px;'><a style='cursor:pointer;' href='" + EmailEQADURL + "'>";
var formEnd = "</a></div>"
var buttonCode = "<button style='background-color:#20C39A;border: 0px;color: white;font-weight: bold;padding:20px;width: 100%;font-size:16px;cursor:pointer;font-color:white;'>Check Your Score</button>";
htmlCode = htmlCode + formStart + buttonCode + formEnd;
var emailForm = {
toEmail: toEmail,
fromEmail: fromEmail,
templateId: "e62d1d23-4cd7-49af-a2b8-5514a93d1bfb",
personalizations: {
'-userName-': userName,
'-examName-': thisExam.exam_page_name,
'-date-': _dateString,
},
html: htmlCode,
subject: " ",
_requested: moment().tz("Asia/Calcutta").toDate(),
};
//console.log(emailForm);
send_email(emailForm, true);
}
});
}
});
}
});
}
});
}
router.get('/cron/eqadSubscriptionEmail', function(req, res){
console.log("Calling Subscription Email Job");
res.json(true);
var allEQADUsers = eqadsubscription.find({}, {}, function(err, allEQADUsers){
if(!err && allEQADUsers && allEQADUsers.length > 0){
allEQADUsers.forEach(function(thisEQADUser, uindex){
var userExam = {
user: thisEQADUser.user,
exam: thisEQADUser.exam,
};
sendDailyEQADEmail(userExam);
});
}
});
});
module.exports = router; | mit |
schneidmaster/action-cable-react | dist/cable_mixin.js | 740 | var CableMixin;CableMixin=function(t){return{componentWillMount:function(){var t;if(!(this.props.cable||this.context&&this.context.cable))throw t=this.constructor.displayName?" of "+this.constructor.displayName:"",new Error("Could not find cable on this.props or this.context"+t)},childContextTypes:{cable:t.PropTypes.object},contextTypes:{cable:t.PropTypes.object},getChildContext:function(){return{cable:this.getCable()}},getCable:function(){return this.props.cable||this.context&&this.context.cable}}},CableMixin.componentWillMount=function(){throw new Error("ActionCableReact.CableMixin is a function that takes React as a parameter and returns the mixin, e.g.: mixins: [ActionCableReact.CableMixin(React)]")},module.exports=CableMixin; | mit |
geek/tribute | spatula/step15.js | 2906 | /// boards handler ///
// Load modules
var Joi = require('joi');
// Declare internals
var internals = {};
module.exports = {
validate: {
params: {
id: Joi.number()
}
},
handler: function (request, reply) {
// Remember that we bound settings to this
var settings = JSON.stringify(this.settings);
boardContext(request.params.id, request.server.plugins.jill, function (err, context) {
if (err) {
return reply(err);
}
context.title = 'Board ' + request.params.id;
context.settings = settings;
var options = {
layout: 'default'
};
reply.view('board', context, options);
});
}
};
var boardContext = function (id, jill, callback) {
// this wasn't exposed in jill yet, so we will need to go back and do that
jill.getBoard(id, function (err, board) {
if (err) {
return callback(err);
}
var allReadings = [];
var addonKeys = board.addons ? Object.keys(board.addons) : [];
var friendlyBoard = {
id: board.id,
name: board.name || ('Board ' + board.id),
addonCount: addonKeys.length - 1
};
allReadings = allReadings.concat(internals.boardReadings(board));
allReadings.sort(function (reading1, reading2) {
if (reading1.time < reading2.time) {
return -1;
}
if (reading1.time > reading2.time) {
return 1;
}
return 0;
});
var readings = internals.convertToFriendlyReadings(allReadings.slice(0, 15));
var context = {
board: friendlyBoard,
readings: readings
};
return callback(null, context);
});
};
internals.boardReadings = function (board) {
var readings = [];
var addonKeys = board.addons ? Object.keys(board.addons) : [];
for (var i = 0, il = addonKeys.length; i < il; ++i) {
var addonKey = addonKeys[i];
if (addonKey !== '255') { // Arduino ID
readings = readings.concat(board.addons[addonKey].readings);
}
}
return readings;
};
internals.convertToFriendlyReadings = function (readings) {
var now = Date.now();
var friendlyReadings = [];
for (var i = 0, il = readings.length; i < il; ++i) {
var reading = readings[i];
var formatter = internals.readingFormatters[reading.type];
friendlyReadings.push({
type: reading.type,
icon: internals.readingIcons[reading.type],
time: Moment(reading.time).fromNow(),
title: formatter ? formatter(reading.value) : reading.value
});
}
return friendlyReadings;
};
/// Go expose the getBoard method on jill ///
| mit |
AlphaHydrae/multi_redis | lib/multi_redis.rb | 677 | require 'redis'
module MultiRedis
VERSION = '0.3.0'
class << self
attr_accessor :redis
end
def self.execute *args, &block
options = args.last.kind_of?(Hash) ? args.pop : {}
executor = nil
@mutex.synchronize do
@executor = Executor.new options
args.each{ |op| @executor.add op }
yield if block_given?
executor = @executor
@executor = nil
end
executor.execute
end
private
@mutex = Mutex.new
@executor = nil
def self.executor
@executor
end
def self.executing?
!!@executor
end
end
Dir[File.join File.dirname(__FILE__), File.basename(__FILE__, '.*'), '*.rb'].each{ |lib| require lib }
| mit |
artemshitov/myfonts | spec/face_spec.rb | 683 | # encoding: utf-8
require 'spec_helper'
require 'myfonts/face'
describe MyFonts::Face do
before :all do
@face = MyFonts::Face.new("http://www.myfonts.com/fonts/letterheadrussia/21-cent/cond-ultra-light-ital/")
end
around do |test|
VCR.use_cassette "21Cent-Cond-Ultra-Light-Ital" do
test.run
end
end
it "shows correct face name" do
@face.name.should == "21 Cent Condensed Ultra Light Italic"
end
it "references correct family" do
@face.family.name.should == "21 Cent"
end
it "returns correct preview image url" do
VCR.use_cassette "TestDrive-Face" do
@face.preview.should =~ /http:\/\/origin\.myfonts\.net/
end
end
end | mit |
kangaroo/coreclr | src/jit/codegenxarch.cpp | 251951 | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Amd64/x86 Code Generator XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator.
#ifdef _TARGET_XARCH_
#include "emit.h"
#include "codegen.h"
#include "lower.h"
#include "gcinfo.h"
#include "gcinfoencoder.h"
// Get the register assigned to the given node
regNumber CodeGenInterface::genGetAssignedReg(GenTreePtr tree)
{
return tree->gtRegNum;
}
//------------------------------------------------------------------------
// genSpillVar: Spill a local variable
//
// Arguments:
// tree - the lclVar node for the variable being spilled
//
// Return Value:
// None.
//
// Assumptions:
// The lclVar must be a register candidate (lvRegCandidate)
void CodeGen::genSpillVar(GenTreePtr tree)
{
unsigned varNum = tree->gtLclVarCommon.gtLclNum;
LclVarDsc * varDsc = &(compiler->lvaTable[varNum]);
assert(varDsc->lvIsRegCandidate());
// We don't actually need to spill if it is already living in memory
bool needsSpill = ((tree->gtFlags & GTF_VAR_DEF) == 0 && varDsc->lvIsInReg());
if (needsSpill)
{
var_types lclTyp = varDsc->TypeGet();
if (varDsc->lvNormalizeOnStore())
lclTyp = genActualType(lclTyp);
emitAttr size = emitTypeSize(lclTyp);
bool restoreRegVar = false;
if (tree->gtOper == GT_REG_VAR)
{
tree->SetOper(GT_LCL_VAR);
restoreRegVar = true;
}
// mask off the flag to generate the right spill code, then bring it back
tree->gtFlags &= ~GTF_REG_VAL;
instruction storeIns = ins_Store(tree->TypeGet(), compiler->isSIMDTypeLocalAligned(varNum));
if (varTypeIsMultiReg(tree))
{
assert(varDsc->lvRegNum == genRegPairLo(tree->gtRegPair));
assert(varDsc->lvOtherReg == genRegPairHi(tree->gtRegPair));
regNumber regLo = genRegPairLo(tree->gtRegPair);
regNumber regHi = genRegPairHi(tree->gtRegPair);
inst_TT_RV(storeIns, tree, regLo);
inst_TT_RV(storeIns, tree, regHi, 4);
}
else
{
assert(varDsc->lvRegNum == tree->gtRegNum);
inst_TT_RV(storeIns, tree, tree->gtRegNum, 0, size);
}
tree->gtFlags |= GTF_REG_VAL;
if (restoreRegVar)
{
tree->SetOper(GT_REG_VAR);
}
genUpdateRegLife(varDsc, /*isBorn*/ false, /*isDying*/ true DEBUGARG(tree));
gcInfo.gcMarkRegSetNpt(varDsc->lvRegMask());
if (VarSetOps::IsMember(compiler, gcInfo.gcTrkStkPtrLcls, varDsc->lvVarIndex))
{
#ifdef DEBUG
if (!VarSetOps::IsMember(compiler, gcInfo.gcVarPtrSetCur, varDsc->lvVarIndex))
{
JITDUMP("\t\t\t\t\t\t\tVar V%02u becoming live\n", varNum);
}
else
{
JITDUMP("\t\t\t\t\t\t\tVar V%02u continuing live\n", varNum);
}
#endif
VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varDsc->lvVarIndex);
}
}
tree->gtFlags &= ~GTF_SPILL;
varDsc->lvRegNum = REG_STK;
if (varTypeIsMultiReg(tree))
{
varDsc->lvOtherReg = REG_STK;
}
}
// inline
void CodeGenInterface::genUpdateVarReg(LclVarDsc * varDsc, GenTreePtr tree)
{
assert(tree->OperIsScalarLocal() || (tree->gtOper == GT_COPY));
varDsc->lvRegNum = tree->gtRegNum;
}
/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************
*
* Generate code that will set the given register to the integer constant.
*/
void CodeGen::genSetRegToIcon(regNumber reg,
ssize_t val,
var_types type,
insFlags flags)
{
// Reg cannot be a FP reg
assert(!genIsValidFloatReg(reg));
// The only TYP_REF constant that can come this path is a managed 'null' since it is not
// relocatable. Other ref type constants (e.g. string objects) go through a different
// code path.
noway_assert(type != TYP_REF || val == 0);
if (val == 0)
{
instGen_Set_Reg_To_Zero(emitActualTypeSize(type), reg, flags);
}
else
{
// TODO-XArch-CQ: needs all the optimized cases
getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(type), reg, val);
}
}
/*****************************************************************************
*
* Generate code to check that the GS cookie wasn't thrashed by a buffer
* overrun. If pushReg is true, preserve all registers around code sequence.
* Otherwise ECX could be modified.
*
* Implementation Note: pushReg = true, in case of tail calls.
*/
void CodeGen::genEmitGSCookieCheck(bool pushReg)
{
noway_assert(compiler->gsGlobalSecurityCookieAddr || compiler->gsGlobalSecurityCookieVal);
// Make sure that EAX is reported as live GC-ref so that any GC that kicks in while
// executing GS cookie check will not collect the object pointed to by EAX.
if (!pushReg && (compiler->info.compRetType == TYP_REF))
gcInfo.gcRegGCrefSetCur |= RBM_INTRET;
regNumber regGSCheck;
if (!pushReg)
{
// Non-tail call: we can use any callee trash register that is not
// a return register or contain 'this' pointer (keep alive this), since
// we are generating GS cookie check after a GT_RETURN block.
if (compiler->lvaKeepAliveAndReportThis() && compiler->lvaTable[compiler->info.compThisArg].lvRegister &&
(compiler->lvaTable[compiler->info.compThisArg].lvRegNum == REG_ECX))
{
regGSCheck = REG_RDX;
}
else
{
regGSCheck = REG_RCX;
}
}
else
{
#ifdef _TARGET_X86_
NYI_X86("Tail calls from methods that need GS check");
regGSCheck = REG_NA;
#else // !_TARGET_X86_
// Tail calls from methods that need GS check: We need to preserve registers while
// emitting GS cookie check for a tail prefixed call or a jmp. To emit GS cookie
// check, we might need a register. This won't be an issue for jmp calls for the
// reason mentioned below (see comment starting with "Jmp Calls:").
//
// The following are the possible solutions in case of tail prefixed calls:
// 1) Use R11 - ignore tail prefix on calls that need to pass a param in R11 when
// present in methods that require GS cookie check. Rest of the tail calls that
// do not require R11 will be honored.
// 2) Internal register - GT_CALL node reserves an internal register and emits GS
// cookie check as part of tail call codegen. GenExitCode() needs to special case
// fast tail calls implemented as epilog+jmp or such tail calls should always get
// dispatched via helper.
// 3) Materialize GS cookie check as a sperate node hanging off GT_CALL node in
// right execution order during rationalization.
//
// There are two calls that use R11: VSD and calli pinvokes with cookie param. Tail
// prefix on pinvokes is ignored. That is, options 2 and 3 will allow tail prefixed
// VSD calls from methods that need GS check.
//
// Tail prefixed calls: Right now for Jit64 compat, method requiring GS cookie check
// ignores tail prefix. In future, if we intend to support tail calls from such a method,
// consider one of the options mentioned above. For now adding an assert that we don't
// expect to see a tail call in a method that requires GS check.
noway_assert(!compiler->compTailCallUsed);
// Jmp calls: specify method handle using which JIT queries VM for its entry point
// address and hence it can neither be a VSD call nor PInvoke calli with cookie
// parameter. Therefore, in case of jmp calls it is safe to use R11.
regGSCheck = REG_R11;
#endif // !_TARGET_X86_
}
if (compiler->gsGlobalSecurityCookieAddr == nullptr)
{
// If GS cookie value fits within 32-bits we can use 'cmp mem64, imm32'.
// Otherwise, load the value into a reg and use 'cmp mem64, reg64'.
if ((int)compiler->gsGlobalSecurityCookieVal != (ssize_t)compiler->gsGlobalSecurityCookieVal)
{
genSetRegToIcon(regGSCheck, compiler->gsGlobalSecurityCookieVal, TYP_I_IMPL);
getEmitter()->emitIns_S_R(INS_cmp, EA_PTRSIZE, regGSCheck, compiler->lvaGSSecurityCookie, 0);
}
else
{
getEmitter()->emitIns_S_I(INS_cmp, EA_PTRSIZE, compiler->lvaGSSecurityCookie, 0,
(int)compiler->gsGlobalSecurityCookieVal);
}
}
else
{
// Ngen case - GS cookie value needs to be accessed through an indirection.
instGen_Set_Reg_To_Imm(EA_HANDLE_CNS_RELOC, regGSCheck, (ssize_t)compiler->gsGlobalSecurityCookieAddr);
getEmitter()->emitIns_R_AR(ins_Load(TYP_I_IMPL), EA_PTRSIZE, regGSCheck, regGSCheck, 0);
getEmitter()->emitIns_S_R(INS_cmp, EA_PTRSIZE, regGSCheck, compiler->lvaGSSecurityCookie, 0);
}
BasicBlock *gsCheckBlk = genCreateTempLabel();
inst_JMP(genJumpKindForOper(GT_EQ, true), gsCheckBlk);
genEmitHelperCall(CORINFO_HELP_FAIL_FAST, 0, EA_UNKNOWN);
genDefineTempLabel(gsCheckBlk);
}
/*****************************************************************************
*
* Generate code for all the basic blocks in the function.
*/
void CodeGen::genCodeForBBlist()
{
unsigned varNum;
LclVarDsc * varDsc;
unsigned savedStkLvl;
#ifdef DEBUG
genInterruptibleUsed = true;
unsigned stmtNum = 0;
UINT64 totalCostEx = 0;
UINT64 totalCostSz = 0;
// You have to be careful if you create basic blocks from now on
compiler->fgSafeBasicBlockCreation = false;
// This stress mode is not comptible with fully interruptible GC
if (genInterruptible && compiler->opts.compStackCheckOnCall)
{
compiler->opts.compStackCheckOnCall = false;
}
// This stress mode is not comptible with fully interruptible GC
if (genInterruptible && compiler->opts.compStackCheckOnRet)
{
compiler->opts.compStackCheckOnRet = false;
}
#endif // DEBUG
// Prepare the blocks for exception handling codegen: mark the blocks that needs labels.
genPrepForEHCodegen();
assert(!compiler->fgFirstBBScratch || compiler->fgFirstBB == compiler->fgFirstBBScratch); // compiler->fgFirstBBScratch has to be first.
/* Initialize the spill tracking logic */
regSet.rsSpillBeg();
/* Initialize the line# tracking logic */
#ifdef DEBUGGING_SUPPORT
if (compiler->opts.compScopeInfo)
{
siInit();
}
#endif
// The current implementation of switch tables requires the first block to have a label so it
// can generate offsets to the switch label targets.
// TODO-XArch-CQ: remove this when switches have been re-implemented to not use this.
if (compiler->fgHasSwitch)
{
compiler->fgFirstBB->bbFlags |= BBF_JMP_TARGET;
}
genPendingCallLabel = nullptr;
/* Initialize the pointer tracking code */
gcInfo.gcRegPtrSetInit();
gcInfo.gcVarPtrSetInit();
/* If any arguments live in registers, mark those regs as such */
for (varNum = 0, varDsc = compiler->lvaTable;
varNum < compiler->lvaCount;
varNum++ , varDsc++)
{
/* Is this variable a parameter assigned to a register? */
if (!varDsc->lvIsParam || !varDsc->lvRegister)
continue;
/* Is the argument live on entry to the method? */
if (!VarSetOps::IsMember(compiler, compiler->fgFirstBB->bbLiveIn, varDsc->lvVarIndex))
continue;
/* Is this a floating-point argument? */
if (varDsc->IsFloatRegType())
continue;
noway_assert(!varTypeIsFloating(varDsc->TypeGet()));
/* Mark the register as holding the variable */
regTracker.rsTrackRegLclVar(varDsc->lvRegNum, varNum);
}
unsigned finallyNesting = 0;
// Make sure a set is allocated for compiler->compCurLife (in the long case), so we can set it to empty without
// allocation at the start of each basic block.
VarSetOps::AssignNoCopy(compiler, compiler->compCurLife, VarSetOps::MakeEmpty(compiler));
/*-------------------------------------------------------------------------
*
* Walk the basic blocks and generate code for each one
*
*/
BasicBlock * block;
BasicBlock * lblk; /* previous block */
for (lblk = NULL, block = compiler->fgFirstBB;
block != NULL;
lblk = block, block = block->bbNext)
{
#ifdef DEBUG
if (compiler->verbose)
{
printf("\n=============== Generating ");
block->dspBlockHeader(compiler, true, true);
compiler->fgDispBBLiveness(block);
}
#endif // DEBUG
/* Figure out which registers hold variables on entry to this block */
regSet.rsMaskVars = RBM_NONE;
gcInfo.gcRegGCrefSetCur = RBM_NONE;
gcInfo.gcRegByrefSetCur = RBM_NONE;
compiler->m_pLinearScan->recordVarLocationsAtStartOfBB(block);
genUpdateLife(block->bbLiveIn);
// Even if liveness didn't change, we need to update the registers containing GC references.
// genUpdateLife will update the registers live due to liveness changes. But what about registers that didn't change?
// We cleared them out above. Maybe we should just not clear them out, but update the ones that change here.
// That would require handling the changes in recordVarLocationsAtStartOfBB().
regMaskTP newLiveRegSet = RBM_NONE;
regMaskTP newRegGCrefSet = RBM_NONE;
regMaskTP newRegByrefSet = RBM_NONE;
#ifdef DEBUG
VARSET_TP VARSET_INIT_NOCOPY(removedGCVars, VarSetOps::MakeEmpty(compiler));
VARSET_TP VARSET_INIT_NOCOPY(addedGCVars, VarSetOps::MakeEmpty(compiler));
#endif
VARSET_ITER_INIT(compiler, iter, block->bbLiveIn, varIndex);
while (iter.NextElem(compiler, &varIndex))
{
unsigned varNum = compiler->lvaTrackedToVarNum[varIndex];
LclVarDsc* varDsc = &(compiler->lvaTable[varNum]);
if (varDsc->lvIsInReg())
{
newLiveRegSet |= varDsc->lvRegMask();
if (varDsc->lvType == TYP_REF)
{
newRegGCrefSet |= varDsc->lvRegMask();
}
else if (varDsc->lvType == TYP_BYREF)
{
newRegByrefSet |= varDsc->lvRegMask();
}
#ifdef DEBUG
if (verbose && VarSetOps::IsMember(compiler, gcInfo.gcVarPtrSetCur, varIndex))
{
VarSetOps::AddElemD(compiler, removedGCVars, varIndex);
}
#endif // DEBUG
VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varIndex);
}
else if (compiler->lvaIsGCTracked(varDsc))
{
#ifdef DEBUG
if (verbose && !VarSetOps::IsMember(compiler, gcInfo.gcVarPtrSetCur, varIndex))
{
VarSetOps::AddElemD(compiler, addedGCVars, varIndex);
}
#endif // DEBUG
VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varIndex);
}
}
#ifdef DEBUG
if (compiler->verbose)
{
printf("\t\t\t\t\t\t\tLive regs: ");
if (regSet.rsMaskVars == newLiveRegSet)
{
printf("(unchanged) ");
}
else
{
printRegMaskInt(regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(regSet.rsMaskVars);
printf(" => ");
}
printRegMaskInt(newLiveRegSet);
compiler->getEmitter()->emitDispRegSet(newLiveRegSet);
printf("\n");
if (!VarSetOps::IsEmpty(compiler, addedGCVars))
{
printf("\t\t\t\t\t\t\tAdded GCVars: ");
dumpConvertedVarSet(compiler, addedGCVars);
printf("\n");
}
if (!VarSetOps::IsEmpty(compiler, removedGCVars))
{
printf("\t\t\t\t\t\t\tRemoved GCVars: ");
dumpConvertedVarSet(compiler, removedGCVars);
printf("\n");
}
}
#endif // DEBUG
regSet.rsMaskVars = newLiveRegSet;
gcInfo.gcMarkRegSetGCref(newRegGCrefSet DEBUG_ARG(true));
gcInfo.gcMarkRegSetByref(newRegByrefSet DEBUG_ARG(true));
/* Blocks with handlerGetsXcptnObj()==true use GT_CATCH_ARG to
represent the exception object (TYP_REF).
We mark REG_EXCEPTION_OBJECT as holding a GC object on entry
to the block, it will be the first thing evaluated
(thanks to GTF_ORDER_SIDEEFF).
*/
if (handlerGetsXcptnObj(block->bbCatchTyp))
{
#if JIT_FEATURE_SSA_SKIP_DEFS
GenTreePtr firstStmt = block->FirstNonPhiDef();
#else
GenTreePtr firstStmt = block->bbTreeList;
#endif
if (firstStmt != NULL)
{
GenTreePtr firstTree = firstStmt->gtStmt.gtStmtExpr;
if (compiler->gtHasCatchArg(firstTree))
{
gcInfo.gcMarkRegSetGCref(RBM_EXCEPTION_OBJECT);
}
}
}
/* Start a new code output block */
genUpdateCurrentFunclet(block);
if (genAlignLoops && block->bbFlags & BBF_LOOP_HEAD)
{
getEmitter()->emitLoopAlign();
}
#ifdef DEBUG
if (compiler->opts.dspCode)
printf("\n L_M%03u_BB%02u:\n", Compiler::s_compMethodsCount, block->bbNum);
#endif
block->bbEmitCookie = NULL;
if (block->bbFlags & (BBF_JMP_TARGET|BBF_HAS_LABEL))
{
/* Mark a label and update the current set of live GC refs */
block->bbEmitCookie = getEmitter()->emitAddLabel(gcInfo.gcVarPtrSetCur,
gcInfo.gcRegGCrefSetCur,
gcInfo.gcRegByrefSetCur,
FALSE);
}
if (block == compiler->fgFirstColdBlock)
{
#ifdef DEBUG
if (compiler->verbose)
{
printf("\nThis is the start of the cold region of the method\n");
}
#endif
// We should never have a block that falls through into the Cold section
noway_assert(!lblk->bbFallsThrough());
// We require the block that starts the Cold section to have a label
noway_assert(block->bbEmitCookie);
getEmitter()->emitSetFirstColdIGCookie(block->bbEmitCookie);
}
/* Both stacks are always empty on entry to a basic block */
genStackLevel = 0;
savedStkLvl = genStackLevel;
/* Tell everyone which basic block we're working on */
compiler->compCurBB = block;
#ifdef DEBUGGING_SUPPORT
siBeginBlock(block);
// BBF_INTERNAL blocks don't correspond to any single IL instruction.
if (compiler->opts.compDbgInfo &&
(block->bbFlags & BBF_INTERNAL) &&
!compiler->fgBBisScratch(block)) // If the block is the distinguished first scratch block, then no need to emit a NO_MAPPING entry, immediately after the prolog.
{
genIPmappingAdd((IL_OFFSETX) ICorDebugInfo::NO_MAPPING, true);
}
bool firstMapping = true;
#endif // DEBUGGING_SUPPORT
/*---------------------------------------------------------------------
*
* Generate code for each statement-tree in the block
*
*/
#if FEATURE_EH_FUNCLETS
if (block->bbFlags & BBF_FUNCLET_BEG)
{
genReserveFuncletProlog(block);
}
#endif // FEATURE_EH_FUNCLETS
for (GenTreePtr stmt = block->FirstNonPhiDef(); stmt; stmt = stmt->gtNext)
{
noway_assert(stmt->gtOper == GT_STMT);
if (stmt->AsStmt()->gtStmtIsEmbedded())
continue;
/* Get hold of the statement tree */
GenTreePtr tree = stmt->gtStmt.gtStmtExpr;
#if defined(DEBUGGING_SUPPORT)
/* Do we have a new IL-offset ? */
if (stmt->gtStmt.gtStmtILoffsx != BAD_IL_OFFSET)
{
/* Create and append a new IP-mapping entry */
genIPmappingAdd(stmt->gtStmt.gtStmt.gtStmtILoffsx, firstMapping);
firstMapping = false;
}
#endif // DEBUGGING_SUPPORT
#ifdef DEBUG
noway_assert(stmt->gtStmt.gtStmtLastILoffs <= compiler->info.compILCodeSize ||
stmt->gtStmt.gtStmtLastILoffs == BAD_IL_OFFSET);
if (compiler->opts.dspCode && compiler->opts.dspInstrs &&
stmt->gtStmt.gtStmtLastILoffs != BAD_IL_OFFSET)
{
while (genCurDispOffset <= stmt->gtStmt.gtStmtLastILoffs)
{
genCurDispOffset +=
dumpSingleInstr(compiler->info.compCode, genCurDispOffset, "> ");
}
}
stmtNum++;
if (compiler->verbose)
{
printf("\nGenerating BB%02u, stmt %u\t\t", block->bbNum, stmtNum);
printf("Holding variables: ");
dspRegMask(regSet.rsMaskVars); printf("\n\n");
if (compiler->verboseTrees)
{
compiler->gtDispTree(compiler->opts.compDbgInfo ? stmt : tree);
printf("\n");
}
}
totalCostEx += ((UINT64)stmt->gtCostEx * block->getBBWeight(compiler));
totalCostSz += (UINT64) stmt->gtCostSz;
#endif // DEBUG
// Traverse the tree in linear order, generating code for each node in the
// tree as we encounter it
compiler->compCurLifeTree = NULL;
compiler->compCurStmt = stmt;
for (GenTreePtr treeNode = stmt->gtStmt.gtStmtList;
treeNode != NULL;
treeNode = treeNode->gtNext)
{
genCodeForTreeNode(treeNode);
if (treeNode->gtHasReg() && treeNode->gtLsraInfo.isLocalDefUse)
{
genConsumeReg(treeNode);
}
}
#ifdef FEATURE_SIMD
// If the next statement expr is a SIMDIntrinsicUpperRestore, don't call rsSpillChk because we
// haven't yet restored spills from the most recent call.
GenTree* nextTopLevelStmt = stmt->AsStmt()->gtStmtNextTopLevelStmt();
if ((nextTopLevelStmt == nullptr) ||
(nextTopLevelStmt->AsStmt()->gtStmtExpr->OperGet() != GT_SIMD) ||
(nextTopLevelStmt->AsStmt()->gtStmtExpr->gtSIMD.gtSIMDIntrinsicID != SIMDIntrinsicUpperRestore))
#endif // FEATURE_SIMD
{
regSet.rsSpillChk();
}
#ifdef DEBUG
/* Make sure we didn't bungle pointer register tracking */
regMaskTP ptrRegs = (gcInfo.gcRegGCrefSetCur|gcInfo.gcRegByrefSetCur);
regMaskTP nonVarPtrRegs = ptrRegs & ~regSet.rsMaskVars;
// If return is a GC-type, clear it. Note that if a common
// epilog is generated (genReturnBB) it has a void return
// even though we might return a ref. We can't use the compRetType
// as the determiner because something we are tracking as a byref
// might be used as a return value of a int function (which is legal)
if (tree->gtOper == GT_RETURN &&
(varTypeIsGC(compiler->info.compRetType) ||
(tree->gtOp.gtOp1 != 0 && varTypeIsGC(tree->gtOp.gtOp1->TypeGet()))))
{
nonVarPtrRegs &= ~RBM_INTRET;
}
// When profiling, the first statement in a catch block will be the
// harmless "inc" instruction (does not interfere with the exception
// object).
if ((compiler->opts.eeFlags & CORJIT_FLG_BBINSTR) &&
(stmt == block->bbTreeList) &&
handlerGetsXcptnObj(block->bbCatchTyp))
{
nonVarPtrRegs &= ~RBM_EXCEPTION_OBJECT;
}
if (nonVarPtrRegs)
{
printf("Regset after tree=");
compiler->printTreeID(tree);
printf(" BB%02u gcr=", block->bbNum);
printRegMaskInt(gcInfo.gcRegGCrefSetCur & ~regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(gcInfo.gcRegGCrefSetCur & ~regSet.rsMaskVars);
printf(", byr=");
printRegMaskInt(gcInfo.gcRegByrefSetCur & ~regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(gcInfo.gcRegByrefSetCur & ~regSet.rsMaskVars);
printf(", regVars=");
printRegMaskInt(regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(regSet.rsMaskVars);
printf("\n");
}
noway_assert(nonVarPtrRegs == 0);
for (GenTree * node = stmt->gtStmt.gtStmtList; node; node=node->gtNext)
{
assert(!(node->gtFlags & GTF_SPILL));
}
#endif // DEBUG
noway_assert(stmt->gtOper == GT_STMT);
#ifdef DEBUGGING_SUPPORT
genEnsureCodeEmitted(stmt->gtStmt.gtStmtILoffsx);
#endif
} //-------- END-FOR each statement-tree of the current block ---------
#if defined(DEBUG) && defined(LATE_DISASM) && defined(_TARGET_AMD64_)
if (block->bbNext == nullptr)
{
// Unit testing of the AMD64 emitter: generate a bunch of instructions into the last block
// (it's as good as any, but better than the prolog, which can only be a single instruction
// group) then use COMPLUS_JitLateDisasm=* to see if the late disassembler
// thinks the instructions are the same as we do.
genAmd64EmitterUnitTests();
}
#endif // defined(DEBUG) && defined(LATE_DISASM) && defined(_TARGET_ARM64_)
#ifdef DEBUGGING_SUPPORT
if (compiler->opts.compScopeInfo && (compiler->info.compVarScopesCount > 0))
{
siEndBlock(block);
/* Is this the last block, and are there any open scopes left ? */
bool isLastBlockProcessed = (block->bbNext == NULL);
if (block->isBBCallAlwaysPair())
{
isLastBlockProcessed = (block->bbNext->bbNext == NULL);
}
if (isLastBlockProcessed && siOpenScopeList.scNext)
{
/* This assert no longer holds, because we may insert a throw
block to demarcate the end of a try or finally region when they
are at the end of the method. It would be nice if we could fix
our code so that this throw block will no longer be necessary. */
//noway_assert(block->bbCodeOffsEnd != compiler->info.compILCodeSize);
siCloseAllOpenScopes();
}
}
#endif // DEBUGGING_SUPPORT
genStackLevel -= savedStkLvl;
#ifdef DEBUG
// compCurLife should be equal to the liveOut set, except that we don't keep
// it up to date for vars that are not register candidates
// (it would be nice to have a xor set function)
VARSET_TP VARSET_INIT_NOCOPY(extraLiveVars, VarSetOps::Diff(compiler, block->bbLiveOut, compiler->compCurLife));
VarSetOps::UnionD(compiler, extraLiveVars, VarSetOps::Diff(compiler, compiler->compCurLife, block->bbLiveOut));
VARSET_ITER_INIT(compiler, extraLiveVarIter, extraLiveVars, extraLiveVarIndex);
while (extraLiveVarIter.NextElem(compiler, &extraLiveVarIndex))
{
unsigned varNum = compiler->lvaTrackedToVarNum[extraLiveVarIndex];
LclVarDsc * varDsc = compiler->lvaTable + varNum;
assert(!varDsc->lvIsRegCandidate());
}
#endif
/* Both stacks should always be empty on exit from a basic block */
noway_assert(genStackLevel == 0);
#ifdef _TARGET_AMD64_
// On AMD64, we need to generate a NOP after a call that is the last instruction of the block, in several
// situations, to support proper exception handling semantics. This is mostly to ensure that when the stack
// walker computes an instruction pointer for a frame, that instruction pointer is in the correct EH region.
// The document "X64 and ARM ABIs.docx" has more details. The situations:
// 1. If the call instruction is in a different EH region as the instruction that follows it.
// 2. If the call immediately precedes an OS epilog. (Note that what the JIT or VM consider an epilog might
// be slightly different from what the OS considers an epilog, and it is the OS-reported epilog that matters here.)
// We handle case #1 here, and case #2 in the emitter.
if (getEmitter()->emitIsLastInsCall())
{
// Ok, the last instruction generated is a call instruction. Do any of the other conditions hold?
// Note: we may be generating a few too many NOPs for the case of call preceding an epilog. Technically,
// if the next block is a BBJ_RETURN, an epilog will be generated, but there may be some instructions
// generated before the OS epilog starts, such as a GS cookie check.
if ((block->bbNext == nullptr) ||
!BasicBlock::sameEHRegion(block, block->bbNext))
{
// We only need the NOP if we're not going to generate any more code as part of the block end.
switch (block->bbJumpKind)
{
case BBJ_ALWAYS:
case BBJ_THROW:
case BBJ_CALLFINALLY:
case BBJ_EHCATCHRET:
// We're going to generate more code below anyway, so no need for the NOP.
case BBJ_RETURN:
case BBJ_EHFINALLYRET:
case BBJ_EHFILTERRET:
// These are the "epilog follows" case, handled in the emitter.
break;
case BBJ_NONE:
if (block->bbNext == nullptr)
{
// Call immediately before the end of the code; we should never get here .
instGen(INS_BREAKPOINT); // This should never get executed
}
else
{
// We need the NOP
instGen(INS_nop);
}
break;
case BBJ_COND:
case BBJ_SWITCH:
// These can't have a call as the last instruction!
default:
noway_assert(!"Unexpected bbJumpKind");
break;
}
}
}
#endif // _TARGET_AMD64_
/* Do we need to generate a jump or return? */
switch (block->bbJumpKind)
{
case BBJ_ALWAYS:
inst_JMP(EJ_jmp, block->bbJumpDest);
break;
case BBJ_RETURN:
genExitCode(block);
break;
case BBJ_THROW:
// If we have a throw at the end of a function or funclet, we need to emit another instruction
// afterwards to help the OS unwinder determine the correct context during unwind.
// We insert an unexecuted breakpoint instruction in several situations
// following a throw instruction:
// 1. If the throw is the last instruction of the function or funclet. This helps
// the OS unwinder determine the correct context during an unwind from the
// thrown exception.
// 2. If this is this is the last block of the hot section.
// 3. If the subsequent block is a special throw block.
// 4. On AMD64, if the next block is in a different EH region.
if ((block->bbNext == NULL)
|| (block->bbNext->bbFlags & BBF_FUNCLET_BEG)
|| !BasicBlock::sameEHRegion(block, block->bbNext)
|| (!isFramePointerUsed() && compiler->fgIsThrowHlpBlk(block->bbNext))
|| block->bbNext == compiler->fgFirstColdBlock
)
{
instGen(INS_BREAKPOINT); // This should never get executed
}
break;
case BBJ_CALLFINALLY:
#if FEATURE_EH_FUNCLETS
// Generate a call to the finally, like this:
// mov rcx,qword ptr [rbp + 20H] // Load rcx with PSPSym
// call finally-funclet
// jmp finally-return // Only for non-retless finally calls
// The jmp can be a NOP if we're going to the next block.
getEmitter()->emitIns_R_S(ins_Load(TYP_I_IMPL), EA_PTRSIZE, REG_RCX, compiler->lvaPSPSym, 0);
getEmitter()->emitIns_J(INS_call, block->bbJumpDest);
if (block->bbFlags & BBF_RETLESS_CALL)
{
// We have a retless call, and the last instruction generated was a call.
// If the next block is in a different EH region (or is the end of the code
// block), then we need to generate a breakpoint here (since it will never
// get executed) to get proper unwind behavior.
if ((block->bbNext == nullptr) ||
!BasicBlock::sameEHRegion(block, block->bbNext))
{
instGen(INS_BREAKPOINT); // This should never get executed
}
}
else
{
// Because of the way the flowgraph is connected, the liveness info for this one instruction
// after the call is not (can not be) correct in cases where a variable has a last use in the
// handler. So turn off GC reporting for this single instruction.
getEmitter()->emitDisableGC();
// Now go to where the finally funclet needs to return to.
if (block->bbNext->bbJumpDest == block->bbNext->bbNext)
{
// Fall-through.
// TODO-XArch-CQ: Can we get rid of this instruction, and just have the call return directly
// to the next instruction? This would depend on stack walking from within the finally
// handler working without this instruction being in this special EH region.
instGen(INS_nop);
}
else
{
inst_JMP(EJ_jmp, block->bbNext->bbJumpDest);
}
getEmitter()->emitEnableGC();
}
// The BBJ_ALWAYS is used because the BBJ_CALLFINALLY can't point to the
// jump target using bbJumpDest - that is already used to point
// to the finally block. So just skip past the BBJ_ALWAYS unless the
// block is RETLESS.
if ( !(block->bbFlags & BBF_RETLESS_CALL) )
{
assert(block->isBBCallAlwaysPair());
lblk = block;
block = block->bbNext;
}
#else // !FEATURE_EH_FUNCLETS
NYI_X86("EH for RyuJIT x86");
#endif // !FEATURE_EH_FUNCLETS
break;
case BBJ_EHCATCHRET:
// Set EAX to the address the VM should return to after the catch.
// Generate a RIP-relative
// lea reg, [rip + disp32] ; the RIP is implicit
// which will be position-indepenent.
// TODO-XArch-Bug?: For ngen, we need to generate a reloc for the displacement (maybe EA_PTR_DSP_RELOC).
getEmitter()->emitIns_R_L(INS_lea, EA_PTRSIZE, block->bbJumpDest, REG_INTRET);
__fallthrough;
case BBJ_EHFINALLYRET:
case BBJ_EHFILTERRET:
#if FEATURE_EH_FUNCLETS
genReserveFuncletEpilog(block);
#else // !FEATURE_EH_FUNCLETS
NYI_X86("EH for RyuJIT x86");
#endif // !FEATURE_EH_FUNCLETS
break;
case BBJ_NONE:
case BBJ_COND:
case BBJ_SWITCH:
break;
default:
noway_assert(!"Unexpected bbJumpKind");
break;
}
#ifdef DEBUG
compiler->compCurBB = 0;
#endif
} //------------------ END-FOR each block of the method -------------------
/* Nothing is live at this point */
genUpdateLife(VarSetOps::MakeEmpty(compiler));
/* Finalize the spill tracking logic */
regSet.rsSpillEnd();
/* Finalize the temp tracking logic */
compiler->tmpEnd();
#ifdef DEBUG
if (compiler->verbose)
{
printf("\n# ");
printf("totalCostEx = %6d, totalCostSz = %5d ",
totalCostEx, totalCostSz);
printf("%s\n", compiler->info.compFullName);
}
#endif
}
// return the child that has the same reg as the dst (if any)
// other child returned (out param) in 'other'
GenTree *
sameRegAsDst(GenTree *tree, GenTree *&other /*out*/)
{
if (tree->gtRegNum == REG_NA)
{
other = nullptr;
return NULL;
}
GenTreePtr op1 = tree->gtOp.gtOp1;
GenTreePtr op2 = tree->gtOp.gtOp2;
if (op1->gtRegNum == tree->gtRegNum)
{
other = op2;
return op1;
}
if (op2->gtRegNum == tree->gtRegNum)
{
other = op1;
return op2;
}
else
{
other = nullptr;
return NULL;
}
}
// move an immediate value into an integer register
void CodeGen::instGen_Set_Reg_To_Imm(emitAttr size,
regNumber reg,
ssize_t imm,
insFlags flags)
{
// reg cannot be a FP register
assert(!genIsValidFloatReg(reg));
if (!compiler->opts.compReloc)
{
size = EA_SIZE(size); // Strip any Reloc flags from size if we aren't doing relocs
}
if ((imm == 0) && !EA_IS_RELOC(size))
{
instGen_Set_Reg_To_Zero(size, reg, flags);
}
else
{
if (genAddrShouldUsePCRel(imm))
{
getEmitter()->emitIns_R_AI(INS_lea, EA_PTR_DSP_RELOC, reg, imm);
}
else
{
getEmitter()->emitIns_R_I(INS_mov, size, reg, imm);
}
}
regTracker.rsTrackRegIntCns(reg, imm);
}
/***********************************************************************************
*
* Generate code to set a register 'targetReg' of type 'targetType' to the constant
* specified by the constant (GT_CNS_INT or GT_CNS_DBL) in 'tree'. This does not call
* genProduceReg() on the target register.
*/
void CodeGen::genSetRegToConst(regNumber targetReg, var_types targetType, GenTreePtr tree)
{
switch (tree->gtOper)
{
case GT_CNS_INT:
{
// relocatable values tend to come down as a CNS_INT of native int type
// so the line between these two opcodes is kind of blurry
GenTreeIntConCommon* con = tree->AsIntConCommon();
ssize_t cnsVal = con->IconValue();
bool needReloc = compiler->opts.compReloc && tree->IsIconHandle();
if (needReloc)
{
instGen_Set_Reg_To_Imm(EA_HANDLE_CNS_RELOC, targetReg, cnsVal);
regTracker.rsTrackRegTrash(targetReg);
}
else
{
genSetRegToIcon(targetReg, cnsVal, targetType);
}
}
break;
case GT_CNS_DBL:
{
double constValue = tree->gtDblCon.gtDconVal;
// Make sure we use "xorpd reg, reg" only for +ve zero constant (0.0) and not for -ve zero (-0.0)
if (*(__int64*)&constValue == 0)
{
// A faster/smaller way to generate 0
instruction ins = genGetInsForOper(GT_XOR, targetType);
inst_RV_RV(ins, targetReg, targetReg, targetType);
}
else
{
GenTreePtr cns;
if (targetType == TYP_FLOAT)
{
float f = forceCastToFloat(constValue);
cns = genMakeConst(&f, targetType, tree, false);
}
else
{
cns = genMakeConst(&constValue, targetType, tree, true);
}
inst_RV_TT(ins_Load(targetType), targetReg, cns);
}
}
break;
default:
unreached();
}
}
// Generate code to get the high N bits of a N*N=2N bit multiplication result
void CodeGen::genCodeForMulHi(GenTreeOp* treeNode)
{
assert(!(treeNode->gtFlags & GTF_UNSIGNED));
assert(!treeNode->gtOverflowEx());
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter *emit = getEmitter();
emitAttr size = emitTypeSize(treeNode);
GenTree *op1 = treeNode->gtOp.gtOp1;
GenTree *op2 = treeNode->gtOp.gtOp2;
// to get the high bits of the multiply, we are constrained to using the
// 1-op form: RDX:RAX = RAX * rm
// The 3-op form (Rx=Ry*Rz) does not support it.
genConsumeOperands(treeNode->AsOp());
GenTree* regOp = op1;
GenTree* rmOp = op2;
// Set rmOp to the contained memory operand (if any)
//
if (op1->isContained() || (!op2->isContained() && (op2->gtRegNum == targetReg)))
{
regOp = op2;
rmOp = op1;
}
assert(!regOp->isContained());
// Setup targetReg when neither of the source operands was a matching register
if (regOp->gtRegNum != targetReg)
{
inst_RV_RV(ins_Copy(targetType), targetReg, regOp->gtRegNum, targetType);
}
emit->emitInsBinary(INS_imulEAX, size, treeNode, rmOp);
// Move the result to the desired register, if necessary
if (targetReg != REG_RDX)
{
inst_RV_RV(INS_mov, targetReg, REG_RDX, targetType);
}
}
// generate code for a DIV or MOD operation
//
void CodeGen::genCodeForDivMod(GenTreeOp* treeNode)
{
GenTree *dividend = treeNode->gtOp1;
GenTree *divisor = treeNode->gtOp2;
genTreeOps oper = treeNode->OperGet();
emitAttr size = emitTypeSize(treeNode);
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter *emit = getEmitter();
// dividend is not contained.
assert(!dividend->isContained());
genConsumeOperands(treeNode->AsOp());
if (varTypeIsFloating(targetType))
{
// divisor is not contained or if contained is a memory op
assert(!divisor->isContained() || divisor->isMemoryOp() || divisor->IsCnsFltOrDbl());
// Floating point div/rem operation
assert(oper == GT_DIV || oper == GT_MOD);
if (dividend->gtRegNum == targetReg)
{
emit->emitInsBinary(genGetInsForOper(treeNode->gtOper, targetType), size, treeNode, divisor);
}
else if (divisor->gtRegNum == targetReg)
{
// It is not possible to generate 2-operand divss or divsd where reg2 = reg1 / reg2
// because divss/divsd reg1, reg2 will over-write reg1. Therefore, in case of AMD64
// LSRA has to make sure that such a register assignment is not generated for floating
// point div/rem operations.
noway_assert(!"GT_DIV/GT_MOD (float): case of reg2 = reg1 / reg2, LSRA should never generate such a reg assignment");
}
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, dividend->gtRegNum, targetType);
emit->emitInsBinary(genGetInsForOper(treeNode->gtOper, targetType), size, treeNode, divisor);
}
}
else
{
// dividend must be in RAX
if (dividend->gtRegNum != REG_RAX)
inst_RV_RV(INS_mov, REG_RAX, dividend->gtRegNum, targetType);
// zero or sign extend rax to rdx
if (oper == GT_UMOD || oper == GT_UDIV)
{
instGen_Set_Reg_To_Zero(EA_PTRSIZE, REG_EDX);
}
else
{
emit->emitIns(INS_cdq, size);
// the cdq instruction writes RDX, So clear the gcInfo for RDX
gcInfo.gcMarkRegSetNpt(RBM_RDX);
}
if (divisor->isContainedIntOrIImmed())
{
GenTreeIntConCommon* divImm = divisor->AsIntConCommon();
assert(divImm->IsIntCnsFitsInI32());
ssize_t imm = divImm->IconValue();
assert(isPow2(abs(imm)));
genCodeForPow2Div(treeNode->AsOp());
}
else
{
// Perform the 'targetType' (64-bit or 32-bit) divide instruction
instruction ins;
if (oper == GT_UMOD || oper == GT_UDIV)
ins = INS_div;
else
ins = INS_idiv;
emit->emitInsBinary(ins, size, treeNode, divisor);
// Signed divide RDX:RAX by r/m64, with result
// stored in RAX := Quotient, RDX := Remainder.
// Move the result to the desired register, if necessary
if (oper == GT_DIV || oper == GT_UDIV)
{
if (targetReg != REG_RAX)
{
inst_RV_RV(INS_mov, targetReg, REG_RAX, targetType);
}
}
else
{
assert((oper == GT_MOD) || (oper == GT_UMOD));
if (targetReg != REG_RDX)
{
inst_RV_RV(INS_mov, targetReg, REG_RDX, targetType);
}
}
}
}
genProduceReg(treeNode);
}
// Generate code for ADD, SUB, AND XOR, and OR.
// mul and div variants have special constraints on x64 so are not handled here.
void CodeGen::genCodeForBinary(GenTree* treeNode)
{
const genTreeOps oper = treeNode->OperGet();
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter *emit = getEmitter();
assert (oper == GT_OR ||
oper == GT_XOR ||
oper == GT_AND ||
oper == GT_ADD ||
oper == GT_SUB);
GenTreePtr op1 = treeNode->gtGetOp1();
GenTreePtr op2 = treeNode->gtGetOp2();
instruction ins = genGetInsForOper(treeNode->OperGet(), targetType);
// The arithmetic node must be sitting in a register (since it's not contained)
noway_assert(targetReg != REG_NA);
regNumber op1reg = op1->gtRegNum;
regNumber op2reg = op2->gtRegNum;
GenTreePtr dst;
GenTreePtr src;
genConsumeOperands(treeNode->AsOp());
// This is the case of reg1 = reg1 op reg2
// We're ready to emit the instruction without any moves
if (op1reg == targetReg)
{
dst = op1;
src = op2;
}
// We have reg1 = reg2 op reg1
// In order for this operation to be correct
// we need that op is a commutative operation so
// we can convert it into reg1 = reg1 op reg2 and emit
// the same code as above
else if (op2reg == targetReg)
{
noway_assert(GenTree::OperIsCommutative(oper));
dst = op2;
src = op1;
}
// now we know there are 3 different operands so attempt to use LEA
else if (oper == GT_ADD
&& !varTypeIsFloating(treeNode)
&& !treeNode->gtOverflowEx() // LEA does not set flags
&& (op2->isContainedIntOrIImmed() || !op2->isContained())
)
{
if (op2->isContainedIntOrIImmed())
{
emit->emitIns_R_AR(INS_lea, emitTypeSize(treeNode), targetReg, op1reg, (int) op2->AsIntConCommon()->IconValue());
}
else
{
assert(op2reg != REG_NA);
emit->emitIns_R_ARX(INS_lea, emitTypeSize(treeNode), targetReg, op1reg, op2reg, 1, 0);
}
genProduceReg(treeNode);
return;
}
// dest, op1 and op2 registers are different:
// reg3 = reg1 op reg2
// We can implement this by issuing a mov:
// reg3 = reg1
// reg3 = reg3 op reg2
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, op1reg, targetType);
regTracker.rsTrackRegCopy(targetReg, op1reg);
gcInfo.gcMarkRegPtrVal(targetReg, targetType);
dst = treeNode;
src = op2;
}
// try to use an inc or dec
if (oper == GT_ADD
&& !varTypeIsFloating(treeNode)
&& src->isContainedIntOrIImmed()
&& !treeNode->gtOverflowEx())
{
if (src->gtIntConCommon.IconValue() == 1)
{
emit->emitIns_R(INS_inc, emitTypeSize(treeNode), targetReg);
genProduceReg(treeNode);
return;
}
else if (src->gtIntConCommon.IconValue() == -1)
{
emit->emitIns_R(INS_dec, emitTypeSize(treeNode), targetReg);
genProduceReg(treeNode);
return;
}
}
regNumber r = emit->emitInsBinary(ins, emitTypeSize(treeNode), dst, src);
noway_assert(r == targetReg);
if (treeNode->gtOverflowEx())
{
assert(oper == GT_ADD || oper == GT_SUB);
genCheckOverflow(treeNode);
}
genProduceReg(treeNode);
}
/*****************************************************************************
*
* Generate code for a single node in the tree.
* Preconditions: All operands have been evaluated
*
*/
void
CodeGen::genCodeForTreeNode(GenTreePtr treeNode)
{
regNumber targetReg;
#if !defined(_TARGET_64BIT_)
if (treeNode->TypeGet() == TYP_LONG)
{
// All long enregistered nodes will have been decomposed into their
// constituent lo and hi nodes.
regPairNo targetPair = treeNode->gtRegPair;
noway_assert(targetPair == REG_PAIR_NONE);
targetReg = REG_NA;
}
else
#endif // !defined(_TARGET_64BIT_)
{
targetReg = treeNode->gtRegNum;
}
var_types targetType = treeNode->TypeGet();
emitter *emit = getEmitter();
#ifdef DEBUG
// Validate that all the operands for the current node are consumed in order.
// This is important because LSRA ensures that any necessary copies will be
// handled correctly.
lastConsumedNode = nullptr;
if (compiler->verbose)
{
unsigned seqNum = treeNode->gtSeqNum; // Useful for setting a conditional break in Visual Studio
printf("Generating: ");
compiler->gtDispTree(treeNode, nullptr, nullptr, true);
}
#endif // DEBUG
// Is this a node whose value is already in a register? LSRA denotes this by
// setting the GTF_REUSE_REG_VAL flag.
if (treeNode->IsReuseRegVal())
{
// For now, this is only used for constant nodes.
assert((treeNode->OperIsConst()));
JITDUMP(" TreeNode is marked ReuseReg\n");
return;
}
// contained nodes are part of their parents for codegen purposes
// ex : immediates, most LEAs
if (treeNode->isContained())
{
return;
}
switch (treeNode->gtOper)
{
case GT_START_NONGC:
getEmitter()->emitDisableGC();
break;
case GT_PROF_HOOK:
#ifdef PROFILING_SUPPORTED
// We should be seeing this only if profiler hook is needed
noway_assert(compiler->compIsProfilerHookNeeded());
// Right now this node is used only for tail calls. In future if
// we intend to use it for Enter or Leave hooks, add a data member
// to this node indicating the kind of profiler hook. For example,
// helper number can be used.
genProfilingLeaveCallback(CORINFO_HELP_PROF_FCN_TAILCALL);
#endif // PROFILING_SUPPORTED
break;
case GT_LCLHEAP:
genLclHeap(treeNode);
break;
case GT_CNS_INT:
case GT_CNS_DBL:
genSetRegToConst(targetReg, targetType, treeNode);
genProduceReg(treeNode);
break;
case GT_NEG:
case GT_NOT:
if (varTypeIsFloating(targetType))
{
assert(treeNode->gtOper == GT_NEG);
genSSE2BitwiseOp(treeNode);
}
else
{
GenTreePtr operand = treeNode->gtGetOp1();
assert(!operand->isContained());
regNumber operandReg = genConsumeReg(operand);
if (operandReg != targetReg)
{
inst_RV_RV(INS_mov, targetReg, operandReg, targetType);
}
instruction ins = genGetInsForOper(treeNode->OperGet(), targetType);
inst_RV(ins, targetReg, targetType);
}
genProduceReg(treeNode);
break;
case GT_OR:
case GT_XOR:
case GT_AND:
assert(varTypeIsIntegralOrI(treeNode));
__fallthrough;
case GT_ADD:
case GT_SUB:
genCodeForBinary(treeNode);
break;
case GT_LSH:
case GT_RSH:
case GT_RSZ:
genCodeForShift(treeNode->gtGetOp1(), treeNode->gtGetOp2(), treeNode);
// genCodeForShift() calls genProduceReg()
break;
case GT_CAST:
#if !defined(_TARGET_64BIT_)
// We will NYI in DecomposeNode() if we are cast TO a long type, but we do not
// yet support casting FROM a long type either, and that's simpler to catch
// here.
NYI_IF(varTypeIsLong(treeNode->gtOp.gtOp1), "Casts from TYP_LONG");
#endif // !defined(_TARGET_64BIT_)
if (varTypeIsFloating(targetType) && varTypeIsFloating(treeNode->gtOp.gtOp1))
{
// Casts float/double <--> double/float
genFloatToFloatCast(treeNode);
}
else if (varTypeIsFloating(treeNode->gtOp.gtOp1))
{
// Casts float/double --> int32/int64
genFloatToIntCast(treeNode);
}
else if (varTypeIsFloating(targetType))
{
// Casts int32/uint32/int64/uint64 --> float/double
genIntToFloatCast(treeNode);
}
else
{
// Casts int <--> int
genIntToIntCast(treeNode);
}
// The per-case functions call genProduceReg()
break;
case GT_LCL_VAR:
{
// lcl_vars are not defs
assert((treeNode->gtFlags & GTF_VAR_DEF) == 0);
GenTreeLclVarCommon *lcl = treeNode->AsLclVarCommon();
bool isRegCandidate = compiler->lvaTable[lcl->gtLclNum].lvIsRegCandidate();
if (isRegCandidate && !(treeNode->gtFlags & GTF_VAR_DEATH))
{
assert((treeNode->InReg()) || (treeNode->gtFlags & GTF_SPILLED));
}
// If this is a register candidate that has been spilled, genConsumeReg() will
// reload it at the point of use. Otherwise, if it's not in a register, we load it here.
if (!treeNode->InReg() && !(treeNode->gtFlags & GTF_SPILLED))
{
assert(!isRegCandidate);
emit->emitIns_R_S(ins_Load(treeNode->TypeGet(), compiler->isSIMDTypeLocalAligned(lcl->gtLclNum)),
emitTypeSize(treeNode), treeNode->gtRegNum, lcl->gtLclNum, 0);
genProduceReg(treeNode);
}
}
break;
case GT_LCL_FLD_ADDR:
case GT_LCL_VAR_ADDR:
{
// Address of a local var. This by itself should never be allocated a register.
// If it is worth storing the address in a register then it should be cse'ed into
// a temp and that would be allocated a register.
noway_assert(targetType == TYP_BYREF);
noway_assert(!treeNode->InReg());
inst_RV_TT(INS_lea, targetReg, treeNode, 0, EA_BYREF);
}
genProduceReg(treeNode);
break;
case GT_LCL_FLD:
{
noway_assert(targetType != TYP_STRUCT);
noway_assert(treeNode->gtRegNum != REG_NA);
#ifdef FEATURE_SIMD
// Loading of TYP_SIMD12 (i.e. Vector3) field
if (treeNode->TypeGet() == TYP_SIMD12)
{
genLoadLclFldTypeSIMD12(treeNode);
break;
}
#endif
emitAttr size = emitTypeSize(targetType);
unsigned offs = treeNode->gtLclFld.gtLclOffs;
unsigned varNum = treeNode->gtLclVarCommon.gtLclNum;
assert(varNum < compiler->lvaCount);
emit->emitIns_R_S(ins_Move_Extend(targetType, treeNode->InReg()), size, targetReg, varNum, offs);
}
genProduceReg(treeNode);
break;
case GT_STORE_LCL_FLD:
{
noway_assert(targetType != TYP_STRUCT);
noway_assert(!treeNode->InReg());
assert(!varTypeIsFloating(targetType) || (targetType == treeNode->gtGetOp1()->TypeGet()));
#ifdef FEATURE_SIMD
// storing of TYP_SIMD12 (i.e. Vector3) field
if (treeNode->TypeGet() == TYP_SIMD12)
{
genStoreLclFldTypeSIMD12(treeNode);
break;
}
#endif
GenTreePtr op1 = treeNode->gtOp.gtOp1;
genConsumeRegs(op1);
emit->emitInsBinary(ins_Store(targetType), emitTypeSize(treeNode), treeNode, op1);
}
break;
case GT_STORE_LCL_VAR:
{
noway_assert(targetType != TYP_STRUCT);
assert(!varTypeIsFloating(targetType) || (targetType == treeNode->gtGetOp1()->TypeGet()));
unsigned lclNum = treeNode->AsLclVarCommon()->gtLclNum;
LclVarDsc* varDsc = &(compiler->lvaTable[lclNum]);
// Ensure that lclVar nodes are typed correctly.
assert(!varDsc->lvNormalizeOnStore() || treeNode->TypeGet() == genActualType(varDsc->TypeGet()));
#if !defined(_TARGET_64BIT_)
if (treeNode->TypeGet() == TYP_LONG)
{
genStoreLongLclVar(treeNode);
break;
}
#endif // !defined(_TARGET_64BIT_)
GenTreePtr op1 = treeNode->gtOp.gtOp1;
genConsumeRegs(op1);
if (treeNode->gtRegNum == REG_NA)
{
// stack store
emit->emitInsMov(ins_Store(targetType, compiler->isSIMDTypeLocalAligned(lclNum)), emitTypeSize(treeNode), treeNode);
varDsc->lvRegNum = REG_STK;
}
else
{
bool containedOp1 = op1->isContained();
// Look for the case where we have a constant zero which we've marked for reuse,
// but which isn't actually in the register we want. In that case, it's better to create
// zero in the target register, because an xor is smaller than a copy. Note that we could
// potentially handle this in the register allocator, but we can't always catch it there
// because the target may not have a register allocated for it yet.
if (!containedOp1 && (op1->gtRegNum != treeNode->gtRegNum) && op1->IsZero())
{
op1->gtRegNum = REG_NA;
op1->ResetReuseRegVal();
containedOp1 = true;
}
if (containedOp1)
{
// Currently, we assume that the contained source of a GT_STORE_LCL_VAR writing to a register
// must be a constant. However, in the future we might want to support a contained memory op.
// This is a bit tricky because we have to decide it's contained before register allocation,
// and this would be a case where, once that's done, we need to mark that node as always
// requiring a register - which we always assume now anyway, but once we "optimize" that
// we'll have to take cases like this into account.
assert((op1->gtRegNum == REG_NA) && op1->OperIsConst());
genSetRegToConst(treeNode->gtRegNum, targetType, op1);
}
else if (op1->gtRegNum != treeNode->gtRegNum)
{
assert(op1->gtRegNum != REG_NA);
emit->emitInsBinary(ins_Move_Extend(targetType, true), emitTypeSize(treeNode), treeNode, op1);
}
}
if (treeNode->gtRegNum != REG_NA)
genProduceReg(treeNode);
}
break;
case GT_RETFILT:
// A void GT_RETFILT is the end of a finally. For non-void filter returns we need to load the result in
// the return register, if it's not already there. The processing is the same as GT_RETURN.
if (targetType != TYP_VOID)
{
// For filters, the IL spec says the result is type int32. Further, the only specified legal values
// are 0 or 1, with the use of other values "undefined".
assert(targetType == TYP_INT);
}
__fallthrough;
case GT_RETURN:
{
GenTreePtr op1 = treeNode->gtOp.gtOp1;
if (targetType == TYP_VOID)
{
assert(op1 == nullptr);
}
#if !defined(_TARGET_64BIT_)
else if (treeNode->TypeGet() == TYP_LONG)
{
assert(op1 != nullptr);
noway_assert(op1->OperGet() == GT_LONG);
GenTree* loRetVal = op1->gtGetOp1();
GenTree* hiRetVal = op1->gtGetOp2();
noway_assert((loRetVal->gtRegNum != REG_NA) && (hiRetVal->gtRegNum != REG_NA));
genConsumeReg(loRetVal);
genConsumeReg(hiRetVal);
if (loRetVal->gtRegNum != REG_LNGRET_LO)
{
inst_RV_RV(ins_Copy(targetType), REG_LNGRET_LO, loRetVal->gtRegNum, TYP_INT);
}
if (hiRetVal->gtRegNum != REG_LNGRET_HI)
{
inst_RV_RV(ins_Copy(targetType), REG_LNGRET_HI, hiRetVal->gtRegNum, TYP_INT);
}
}
#endif // !defined(_TARGET_64BIT_)
else
{
assert(op1 != nullptr);
noway_assert(op1->gtRegNum != REG_NA);
// !! NOTE !! genConsumeReg will clear op1 as GC ref after it has
// consumed a reg for the operand. This is because the variable
// is dead after return. But we are issuing more instructions
// like "profiler leave callback" after this consumption. So
// if you are issuing more instructions after this point,
// remember to keep the variable live up until the new method
// exit point where it is actually dead.
genConsumeReg(op1);
regNumber retReg = varTypeIsFloating(treeNode) ? REG_FLOATRET : REG_INTRET;
#ifdef _TARGET_X86_
if (varTypeIsFloating(treeNode))
{
if (genIsRegCandidateLocal(op1) && !compiler->lvaTable[op1->gtLclVarCommon.gtLclNum].lvRegister)
{
// Store local variable to its home location, if necessary.
if ((op1->gtFlags & GTF_REG_VAL) != 0)
{
op1->gtFlags &= ~GTF_REG_VAL;
inst_TT_RV(ins_Store(op1->gtType, compiler->isSIMDTypeLocalAligned(op1->gtLclVarCommon.gtLclNum)), op1, op1->gtRegNum);
}
// Now, load it to the fp stack.
getEmitter()->emitIns_S(INS_fld, emitTypeSize(op1), op1->AsLclVarCommon()->gtLclNum, 0);
}
else
{
// Spill the value, which should be in a register, then load it to the fp stack.
// TODO-X86-CQ: Deal with things that are already in memory (don't call genConsumeReg yet).
op1->gtFlags |= GTF_SPILL;
regSet.rsSpillTree(op1->gtRegNum, op1);
op1->gtFlags |= GTF_SPILLED;
op1->gtFlags &= ~GTF_SPILL;
TempDsc* t = regSet.rsUnspillInPlace(op1);
inst_FS_ST(INS_fld, emitActualTypeSize(op1->gtType), t, 0);
op1->gtFlags &= ~GTF_SPILLED;
compiler->tmpRlsTemp(t);
}
}
else
#endif // _TARGET_X86_
if (op1->gtRegNum != retReg)
{
inst_RV_RV(ins_Copy(targetType), retReg, op1->gtRegNum, targetType);
}
}
#ifdef PROFILING_SUPPORTED
// There will be a single return block while generating profiler ELT callbacks.
//
// Reason for not materializing Leave callback as a GT_PROF_HOOK node after GT_RETURN:
// In flowgraph and other places assert that the last node of a block marked as
// GT_RETURN is either a GT_RETURN or GT_JMP or a tail call. It would be nice to
// maintain such an invariant irrespective of whether profiler hook needed or not.
// Also, there is not much to be gained by materializing it as an explicit node.
if (compiler->compCurBB == compiler->genReturnBB)
{
// !! NOTE !!
// Since we are invalidating the assumption that we would slip into the epilog
// right after the "return", we need to preserve the return reg's GC state
// across the call until actual method return.
if (varTypeIsGC(compiler->info.compRetType))
{
gcInfo.gcMarkRegPtrVal(REG_INTRET, compiler->info.compRetType);
}
genProfilingLeaveCallback();
if (varTypeIsGC(compiler->info.compRetType))
{
gcInfo.gcMarkRegSetNpt(REG_INTRET);
}
}
#endif
}
break;
case GT_LEA:
{
// if we are here, it is the case where there is an LEA that cannot
// be folded into a parent instruction
GenTreeAddrMode *lea = treeNode->AsAddrMode();
genLeaInstruction(lea);
}
// genLeaInstruction calls genProduceReg()
break;
case GT_IND:
#ifdef FEATURE_SIMD
// Handling of Vector3 type values loaded through indirection.
if (treeNode->TypeGet() == TYP_SIMD12)
{
genLoadIndTypeSIMD12(treeNode);
break;
}
#endif // FEATURE_SIMD
genConsumeAddress(treeNode->AsIndir()->Addr());
emit->emitInsMov(ins_Load(treeNode->TypeGet()), emitTypeSize(treeNode), treeNode);
genProduceReg(treeNode);
break;
case GT_MULHI:
genCodeForMulHi(treeNode->AsOp());
genProduceReg(treeNode);
break;
case GT_MUL:
{
instruction ins;
emitAttr size = emitTypeSize(treeNode);
bool isUnsignedMultiply = ((treeNode->gtFlags & GTF_UNSIGNED) != 0);
bool requiresOverflowCheck = treeNode->gtOverflowEx();
// TODO-XArch-CQ: use LEA for mul by imm
GenTree *op1 = treeNode->gtOp.gtOp1;
GenTree *op2 = treeNode->gtOp.gtOp2;
// there are 3 forms of x64 multiply:
// 1-op form with 128 result: RDX:RAX = RAX * rm
// 2-op form: reg *= rm
// 3-op form: reg = rm * imm
genConsumeOperands(treeNode->AsOp());
// This matches the 'mul' lowering in Lowering::SetMulOpCounts()
//
// immOp :: Only one operand can be an immediate
// rmOp :: Only operand can be a memory op.
// regOp :: A register op (especially the operand that matches 'targetReg')
// (can be nullptr when we have both a memory op and an immediate op)
GenTree * immOp = nullptr;
GenTree * rmOp = op1;
GenTree * regOp;
if (op2->isContainedIntOrIImmed())
{
immOp = op2;
}
else if (op1->isContainedIntOrIImmed())
{
immOp = op1;
rmOp = op2;
}
if (immOp != nullptr)
{
// This must be a non-floating point operation.
assert(!varTypeIsFloating(treeNode));
// use the 3-op form with immediate
ins = getEmitter()->inst3opImulForReg(targetReg);
emit->emitInsBinary(ins, size, rmOp, immOp);
}
else // we have no contained immediate operand
{
regOp = op1;
rmOp = op2;
regNumber mulTargetReg = targetReg;
if (isUnsignedMultiply && requiresOverflowCheck)
{
ins = INS_mulEAX;
mulTargetReg = REG_RAX;
}
else
{
ins = genGetInsForOper(GT_MUL, targetType);
}
// Set rmOp to the contain memory operand (if any)
// or set regOp to the op2 when it has the matching target register for our multiply op
//
if (op1->isContained() || (!op2->isContained() && (op2->gtRegNum == mulTargetReg)))
{
regOp = op2;
rmOp = op1;
}
assert(!regOp->isContained());
// Setup targetReg when neither of the source operands was a matching register
if (regOp->gtRegNum != mulTargetReg)
{
inst_RV_RV(ins_Copy(targetType), mulTargetReg, regOp->gtRegNum, targetType);
}
emit->emitInsBinary(ins, size, treeNode, rmOp);
// Move the result to the desired register, if necessary
if ((ins == INS_mulEAX) && (targetReg != REG_RAX))
{
inst_RV_RV(INS_mov, targetReg, REG_RAX, targetType);
}
}
if (requiresOverflowCheck)
{
// Overflow checking is only used for non-floating point types
noway_assert(!varTypeIsFloating(treeNode));
genCheckOverflow(treeNode);
}
}
genProduceReg(treeNode);
break;
case GT_MOD:
case GT_UDIV:
case GT_UMOD:
// We shouldn't be seeing GT_MOD on float/double args as it should get morphed into a
// helper call by front-end. Similarly we shouldn't be seeing GT_UDIV and GT_UMOD
// on float/double args.
noway_assert(!varTypeIsFloating(treeNode));
__fallthrough;
case GT_DIV:
genCodeForDivMod(treeNode->AsOp());
break;
case GT_MATH:
genMathIntrinsic(treeNode);
break;
#ifdef FEATURE_SIMD
case GT_SIMD:
genSIMDIntrinsic(treeNode->AsSIMD());
break;
#endif // FEATURE_SIMD
case GT_CKFINITE:
genCkfinite(treeNode);
break;
case GT_EQ:
case GT_NE:
case GT_LT:
case GT_LE:
case GT_GE:
case GT_GT:
{
// TODO-XArch-CQ: Check if we can use the currently set flags.
// TODO-XArch-CQ: Check for the case where we can simply transfer the carry bit to a register
// (signed < or >= where targetReg != REG_NA)
GenTreeOp *tree = treeNode->AsOp();
GenTreePtr op1 = tree->gtOp1;
GenTreePtr op2 = tree->gtOp2;
var_types op1Type = op1->TypeGet();
var_types op2Type = op2->TypeGet();
#if !defined(_TARGET_64BIT_)
NYI_IF(varTypeIsLong(op1Type) || varTypeIsLong(op2Type), "Comparison of longs");
#endif // !defined(_TARGET_64BIT_)
genConsumeOperands(tree);
instruction ins;
emitAttr cmpAttr;
if (varTypeIsFloating(op1Type))
{
// SSE2 instruction ucomis[s|d] is performs unordered comparison and
// updates rFLAGS register as follows.
// Result of compare ZF PF CF
// ----------------- ------------
// Unordered 1 1 1 <-- this result implies one of operands of compare is a NAN.
// Greater 0 0 0
// Less Than 0 0 1
// Equal 1 0 0
//
// From the above table the following equalities follow. As per ECMA spec *.UN opcodes perform
// unordered comparison of floating point values. That is *.UN comparisons result in true when
// one of the operands is a NaN whereas ordered comparisons results in false.
//
// Opcode Amd64 equivalent Comment
// ------ ----------------- --------
// BLT.UN(a,b) ucomis[s|d] a, b Jb branches if CF=1, which means either a<b or unordered from the above table.
// jb
//
// BLT(a,b) ucomis[s|d] b, a Ja branches if CF=0 and ZF=0, which means b>a that in turn implies a<b
// ja
//
// BGT.UN(a,b) ucomis[s|d] b, a branch if b<a or unordered ==> branch if a>b or unordered
// jb
//
// BGT(a, b) ucomis[s|d] a, b branch if a>b
// ja
//
// BLE.UN(a,b) ucomis[s|d] a, b jbe branches if CF=1 or ZF=1, which implies a<=b or unordered
// jbe
//
// BLE(a,b) ucomis[s|d] b, a jae branches if CF=0, which mean b>=a or a<=b
// jae
//
// BGE.UN(a,b) ucomis[s|d] b, a branch if b<=a or unordered ==> branch if a>=b or unordered
// jbe
//
// BGE(a,b) ucomis[s|d] a, b branch if a>=b
// jae
//
// BEQ.UN(a,b) ucomis[s|d] a, b branch if a==b or unordered. There is no BEQ.UN opcode in ECMA spec.
// je This case is given for completeness, in case if JIT generates such
// a gentree internally.
//
// BEQ(a,b) ucomis[s|d] a, b From the above table, PF=0 and ZF=1 corresponds to a==b.
// jpe L1
// je <true label>
// L1:
//
// BNE(a,b) ucomis[s|d] a, b branch if a!=b. There is no BNE opcode in ECMA spec. This case is
// jne given for completeness, in case if JIT generates such a gentree
// internally.
//
// BNE.UN(a,b) ucomis[s|d] a, b From the above table, PF=1 or ZF=0 implies unordered or a!=b
// jpe <true label>
// jne <true label>
//
// As we can see from the above equalities that the operands of a compare operator need to be
// reveresed in case of BLT/CLT, BGT.UN/CGT.UN, BLE/CLE, BGE.UN/CGE.UN.
bool reverseOps;
if ((tree->gtFlags & GTF_RELOP_NAN_UN) != 0)
{
// Unordered comparison case
reverseOps = (tree->gtOper == GT_GT || tree->gtOper == GT_GE);
}
else
{
reverseOps = (tree->gtOper == GT_LT || tree->gtOper == GT_LE);
}
if (reverseOps)
{
GenTreePtr tmp = op1;
op1 = op2;
op2 = tmp;
}
ins = ins_FloatCompare(op1Type);
cmpAttr = emitTypeSize(op1Type);
}
else // not varTypeIsFloating(op1Type)
{
assert(!op1->isContainedIntOrIImmed()); // We no longer support swapping op1 and op2 to generate cmp reg, imm
assert(!varTypeIsFloating(op2Type));
// By default we use an int32 sized cmp instruction
//
ins = INS_cmp;
var_types cmpType = TYP_INT;
// In the if/then/else statement below we may change the
// 'cmpType' and/or 'ins' to generate a smaller instruction
// Are we comparing two values that are the same size?
//
if (genTypeSize(op1Type) == genTypeSize(op2Type))
{
if (op1Type == op2Type)
{
// If both types are exactly the same we can use that type
cmpType = op1Type;
}
else if (genTypeSize(op1Type) == 8)
{
// If we have two different int64 types we need to use a long compare
cmpType = TYP_LONG;
}
cmpAttr = emitTypeSize(cmpType);
}
else // Here we know that (op1Type != op2Type)
{
// Do we have a short compare against a constant in op2?
//
// We checked for this case in LowerCmp() and if we can perform a small
// compare immediate we labeled this compare with a GTF_RELOP_SMALL
// and for unsigned small non-equality compares the GTF_UNSIGNED flag.
//
if (op2->isContainedIntOrIImmed() && ((tree->gtFlags & GTF_RELOP_SMALL) != 0))
{
assert(varTypeIsSmall(op1Type));
cmpType = op1Type;
}
else // compare two different sized operands
{
// For this case we don't want any memory operands, only registers or immediates
//
assert(!op1->isContainedMemoryOp());
assert(!op2->isContainedMemoryOp());
// Check for the case where one operand is an int64 type
// Lower should have placed 32-bit operand in a register
// for signed comparisons we will sign extend the 32-bit value in place.
//
bool op1Is64Bit = (genTypeSize(op1Type) == 8);
bool op2Is64Bit = (genTypeSize(op2Type) == 8);
if (op1Is64Bit)
{
cmpType = TYP_LONG;
if (!(treeNode->gtFlags & GTF_UNSIGNED) && !op2Is64Bit)
{
assert(op2->gtRegNum != REG_NA);
#ifdef _TARGET_X86_
NYI_X86("64 bit sign extensions for x86/RyuJIT");
#else // !_TARGET_X86_
inst_RV_RV(INS_movsxd, op2->gtRegNum, op2->gtRegNum, op2Type);
#endif // !_TARGET_X86_
}
}
else if (op2Is64Bit)
{
cmpType = TYP_LONG;
if (!(treeNode->gtFlags & GTF_UNSIGNED) && !op1Is64Bit)
{
assert(op1->gtRegNum != REG_NA);
#ifdef _TARGET_X86_
NYI_X86("64 bit sign extensions for x86/RyuJIT");
#else // !_TARGET_X86_
inst_RV_RV(INS_movsxd, op1->gtRegNum, op1->gtRegNum, op1Type);
#endif // !_TARGET_X86_
}
}
}
cmpAttr = emitTypeSize(cmpType);
}
// See if we can generate a "test" instruction instead of a "cmp".
// For this to generate the correct conditional branch we must have
// a compare against zero.
//
if (op2->IsZero())
{
if (op1->isContained())
{
// op1 can be a contained memory op
// or the special contained GT_AND that we created in Lowering::LowerCmp()
//
if ((op1->OperGet() == GT_AND))
{
noway_assert(op1->gtOp.gtOp2->isContainedIntOrIImmed());
ins = INS_test; // we will generate "test andOp1, andOp2CnsVal"
op2 = op1->gtOp.gtOp2; // must assign op2 before we overwrite op1
op1 = op1->gtOp.gtOp1; // overwrite op1
// fallthrough to emit->emitInsBinary(ins, cmpAttr, op1, op2);
}
}
else // op1 is not contained thus it must be in a register
{
ins = INS_test;
op2 = op1; // we will generate "test reg1,reg1"
// fallthrough to emit->emitInsBinary(ins, cmpAttr, op1, op2);
}
}
}
emit->emitInsBinary(ins, cmpAttr, op1, op2);
// Are we evaluating this into a register?
if (targetReg != REG_NA)
{
genSetRegToCond(targetReg, tree);
genProduceReg(tree);
}
}
break;
case GT_JTRUE:
{
GenTree *cmp = treeNode->gtOp.gtOp1;
assert(cmp->OperIsCompare());
assert(compiler->compCurBB->bbJumpKind == BBJ_COND);
// Get the "kind" and type of the comparison. Note that whether it is an unsigned cmp
// is governed by a flag NOT by the inherent type of the node
// TODO-XArch-CQ: Check if we can use the currently set flags.
emitJumpKind jumpKind[2];
bool branchToTrueLabel[2];
genJumpKindsForTree(cmp, jumpKind, branchToTrueLabel);
BasicBlock* skipLabel = nullptr;
if (jumpKind[0] != EJ_NONE)
{
BasicBlock *jmpTarget;
if (branchToTrueLabel[0])
{
jmpTarget = compiler->compCurBB->bbJumpDest;
}
else
{
// This case arises only for ordered GT_EQ right now
assert((cmp->gtOper == GT_EQ) && ((cmp->gtFlags & GTF_RELOP_NAN_UN) == 0));
skipLabel = genCreateTempLabel();
jmpTarget = skipLabel;
}
inst_JMP(jumpKind[0], jmpTarget);
}
if (jumpKind[1] != EJ_NONE)
{
// the second conditional branch always has to be to the true label
assert(branchToTrueLabel[1]);
inst_JMP(jumpKind[1], compiler->compCurBB->bbJumpDest);
}
if (skipLabel != nullptr)
genDefineTempLabel(skipLabel);
}
break;
case GT_RETURNTRAP:
{
// this is nothing but a conditional call to CORINFO_HELP_STOP_FOR_GC
// based on the contents of 'data'
GenTree *data = treeNode->gtOp.gtOp1;
genConsumeRegs(data);
GenTreeIntCon cns = intForm(TYP_INT, 0);
emit->emitInsBinary(INS_cmp, emitTypeSize(TYP_INT), data, &cns);
BasicBlock* skipLabel = genCreateTempLabel();
inst_JMP(genJumpKindForOper(GT_EQ, true), skipLabel);
// emit the call to the EE-helper that stops for GC (or other reasons)
genEmitHelperCall(CORINFO_HELP_STOP_FOR_GC, 0, EA_UNKNOWN);
genDefineTempLabel(skipLabel);
}
break;
case GT_STOREIND:
{
#ifdef FEATURE_SIMD
// Storing Vector3 of size 12 bytes through indirection
if (treeNode->TypeGet() == TYP_SIMD12)
{
genStoreIndTypeSIMD12(treeNode);
break;
}
#endif //FEATURE_SIMD
GenTree* data = treeNode->gtOp.gtOp2;
GenTree* addr = treeNode->gtOp.gtOp1;
assert(!varTypeIsFloating(targetType) || (targetType == data->TypeGet()));
GCInfo::WriteBarrierForm writeBarrierForm = gcInfo.gcIsWriteBarrierCandidate(treeNode, data);
if (writeBarrierForm != GCInfo::WBF_NoBarrier)
{
// data and addr must be in registers.
// Consume both registers so that any copies of interfering registers are taken care of.
genConsumeOperands(treeNode->AsOp());
// At this point, we should not have any interference.
// That is, 'data' must not be in REG_ARG_0, as that is where 'addr' must go.
noway_assert(data->gtRegNum != REG_ARG_0);
// addr goes in REG_ARG_0
if (addr->gtRegNum != REG_ARG_0)
{
inst_RV_RV(INS_mov, REG_ARG_0, addr->gtRegNum, addr->TypeGet());
}
// data goes in REG_ARG_1
if (data->gtRegNum != REG_ARG_1)
{
inst_RV_RV(INS_mov, REG_ARG_1, data->gtRegNum, data->TypeGet());
}
genGCWriteBarrier(treeNode, writeBarrierForm);
}
else
{
bool reverseOps = ((treeNode->gtFlags & GTF_REVERSE_OPS) != 0);
bool dataIsUnary = false;
GenTree* nonRMWsrc = nullptr;
// We must consume the operands in the proper execution order, so that liveness is
// updated appropriately.
if (!reverseOps)
{
genConsumeAddress(addr);
}
if (data->isContained() && !data->OperIsLeaf())
{
dataIsUnary = (GenTree::OperIsUnary(data->OperGet()) != 0);
if (!dataIsUnary)
{
nonRMWsrc = data->gtGetOp1();
if (nonRMWsrc->isIndir() && Lowering::IndirsAreEquivalent(nonRMWsrc, treeNode))
{
nonRMWsrc = data->gtGetOp2();
}
genConsumeRegs(nonRMWsrc);
}
}
else
{
genConsumeRegs(data);
}
if (reverseOps)
{
genConsumeAddress(addr);
}
if (data->isContained() && !data->OperIsLeaf())
{
if (dataIsUnary)
{
emit->emitInsRMW(genGetInsForOper(data->OperGet(), data->TypeGet()),
emitTypeSize(treeNode),
treeNode);
}
else
{
if (data->OperGet() == GT_LSH ||
data->OperGet() == GT_RSH ||
data->OperGet() == GT_RSZ)
{
genCodeForShift(addr, data->gtOp.gtOp2, data);
}
else
{
emit->emitInsRMW(genGetInsForOper(data->OperGet(), data->TypeGet()),
emitTypeSize(treeNode),
treeNode,
nonRMWsrc);
}
}
}
else
{
emit->emitInsMov(ins_Store(data->TypeGet()), emitTypeSize(treeNode), treeNode);
}
}
}
break;
case GT_COPY:
// This is handled at the time we call genConsumeReg() on the GT_COPY
break;
case GT_SWAP:
{
// Swap is only supported for lclVar operands that are enregistered
// We do not consume or produce any registers. Both operands remain enregistered.
// However, the gc-ness may change.
assert(genIsRegCandidateLocal(treeNode->gtOp.gtOp1) && genIsRegCandidateLocal(treeNode->gtOp.gtOp2));
GenTreeLclVarCommon* lcl1 = treeNode->gtOp.gtOp1->AsLclVarCommon();
LclVarDsc* varDsc1 = &(compiler->lvaTable[lcl1->gtLclNum]);
var_types type1 = varDsc1->TypeGet();
GenTreeLclVarCommon* lcl2 = treeNode->gtOp.gtOp2->AsLclVarCommon();
LclVarDsc* varDsc2 = &(compiler->lvaTable[lcl2->gtLclNum]);
var_types type2 = varDsc2->TypeGet();
// We must have both int or both fp regs
assert(!varTypeIsFloating(type1) || varTypeIsFloating(type2));
// FP swap is not yet implemented (and should have NYI'd in LSRA)
assert(!varTypeIsFloating(type1));
regNumber oldOp1Reg = lcl1->gtRegNum;
regMaskTP oldOp1RegMask = genRegMask(oldOp1Reg);
regNumber oldOp2Reg = lcl2->gtRegNum;
regMaskTP oldOp2RegMask = genRegMask(oldOp2Reg);
// We don't call genUpdateVarReg because we don't have a tree node with the new register.
varDsc1->lvRegNum = oldOp2Reg;
varDsc2->lvRegNum = oldOp1Reg;
// Do the xchg
emitAttr size = EA_PTRSIZE;
if (varTypeGCtype(type1) != varTypeGCtype(type2))
{
// If the type specified to the emitter is a GC type, it will swap the GC-ness of the registers.
// Otherwise it will leave them alone, which is correct if they have the same GC-ness.
size = EA_GCREF;
}
inst_RV_RV(INS_xchg, oldOp1Reg, oldOp2Reg, TYP_I_IMPL, size);
// Update the gcInfo.
// Manually remove these regs for the gc sets (mostly to avoid confusing duplicative dump output)
gcInfo.gcRegByrefSetCur &= ~(oldOp1RegMask|oldOp2RegMask);
gcInfo.gcRegGCrefSetCur &= ~(oldOp1RegMask|oldOp2RegMask);
// gcMarkRegPtrVal will do the appropriate thing for non-gc types.
// It will also dump the updates.
gcInfo.gcMarkRegPtrVal(oldOp2Reg, type1);
gcInfo.gcMarkRegPtrVal(oldOp1Reg, type2);
}
break;
case GT_LIST:
case GT_ARGPLACE:
// Nothing to do
break;
case GT_PUTARG_STK:
#ifdef _TARGET_X86_
genPutArgStk(treeNode);
#else // !_TARGET_X86_
{
noway_assert(targetType != TYP_STRUCT);
assert(!varTypeIsFloating(targetType) || (targetType == treeNode->gtGetOp1()->TypeGet()));
// Get argument offset on stack.
// Here we cross check that argument offset hasn't changed from lowering to codegen since
// we are storing arg slot number in GT_PUTARG_STK node in lowering phase.
int argOffset = treeNode->AsPutArgStk()->gtSlotNum * TARGET_POINTER_SIZE;
#ifdef DEBUG
fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(treeNode->AsPutArgStk()->gtCall, treeNode);
assert(curArgTabEntry);
assert(argOffset == (int)curArgTabEntry->slotNum * TARGET_POINTER_SIZE);
#endif
GenTreePtr data = treeNode->gtOp.gtOp1;
unsigned varNum;
#if FEATURE_FASTTAILCALL
bool putInIncomingArgArea = treeNode->AsPutArgStk()->putInIncomingArgArea;
#else
const bool putInIncomingArgArea = false;
#endif
// Whether to setup stk arg in incoming or out-going arg area?
// Fast tail calls implemented as epilog+jmp = stk arg is setup in incoming arg area.
// All other calls - stk arg is setup in out-going arg area.
if (putInIncomingArgArea)
{
// The first varNum is guaranteed to be the first incoming arg of the method being compiled.
// See lvaInitTypeRef() for the order in which lvaTable entries are initialized.
varNum = 0;
#ifdef DEBUG
// This must be a fast tail call.
assert(treeNode->AsPutArgStk()->gtCall->AsCall()->IsFastTailCall());
// Since it is a fast tail call, the existence of first incoming arg is guaranteed
// because fast tail call requires that in-coming arg area of caller is >= out-going
// arg area required for tail call.
LclVarDsc* varDsc = compiler->lvaTable;
assert(varDsc != nullptr);
assert(varDsc->lvIsRegArg && ((varDsc->lvArgReg == REG_ARG_0) || (varDsc->lvArgReg == REG_FLTARG_0)));
#endif
}
else
{
#if FEATURE_FIXED_OUT_ARGS
varNum = compiler->lvaOutgoingArgSpaceVar;
#else // !FEATURE_FIXED_OUT_ARGS
NYI_X86("Stack args for x86/RyuJIT");
varNum = BAD_VAR_NUM;
#endif // !FEATURE_FIXED_OUT_ARGS
}
if (data->isContained())
{
getEmitter()->emitIns_S_I(ins_Store(targetType), emitTypeSize(targetType), varNum,
argOffset, (int) data->AsIntConCommon()->IconValue());
}
else
{
genConsumeReg(data);
getEmitter()->emitIns_S_R(ins_Store(targetType), emitTypeSize(targetType), data->gtRegNum, varNum, argOffset);
}
}
#endif // !_TARGET_X86_
break;
case GT_PUTARG_REG:
{
noway_assert(targetType != TYP_STRUCT);
// commas show up here commonly, as part of a nullchk operation
GenTree *op1 = treeNode->gtOp.gtOp1;
// If child node is not already in the register we need, move it
genConsumeReg(op1);
if (treeNode->gtRegNum != op1->gtRegNum)
{
inst_RV_RV(ins_Copy(targetType), treeNode->gtRegNum, op1->gtRegNum, targetType);
}
}
genProduceReg(treeNode);
break;
case GT_CALL:
genCallInstruction(treeNode);
break;
case GT_JMP:
genJmpMethod(treeNode);
break;
case GT_LOCKADD:
case GT_XCHG:
case GT_XADD:
genLockedInstructions(treeNode);
break;
case GT_MEMORYBARRIER:
instGen_MemoryBarrier();
break;
case GT_CMPXCHG:
{
GenTreePtr location = treeNode->gtCmpXchg.gtOpLocation; // arg1
GenTreePtr value = treeNode->gtCmpXchg.gtOpValue; // arg2
GenTreePtr comparand = treeNode->gtCmpXchg.gtOpComparand; // arg3
assert(location->gtRegNum != REG_NA && location->gtRegNum != REG_RAX);
assert(value->gtRegNum != REG_NA && value->gtRegNum != REG_RAX);
genConsumeReg(location);
genConsumeReg(value);
genConsumeReg(comparand);
// comparand goes to RAX;
// Note that we must issue this move after the genConsumeRegs(), in case any of the above
// have a GT_COPY from RAX.
if (comparand->gtRegNum != REG_RAX)
{
inst_RV_RV(ins_Copy(comparand->TypeGet()), REG_RAX, comparand->gtRegNum, comparand->TypeGet());
}
// location is Rm
instGen(INS_lock);
emit->emitIns_AR_R(INS_cmpxchg, emitTypeSize(targetType), value->gtRegNum, location->gtRegNum, 0);
// Result is in RAX
if (targetReg != REG_RAX)
{
inst_RV_RV(ins_Copy(targetType), targetReg, REG_RAX, targetType);
}
}
genProduceReg(treeNode);
break;
case GT_RELOAD:
// do nothing - reload is just a marker.
// The parent node will call genConsumeReg on this which will trigger the unspill of this node's child
// into the register specified in this node.
break;
case GT_NOP:
break;
case GT_NO_OP:
if (treeNode->gtFlags & GTF_NO_OP_NO)
{
noway_assert(!"GTF_NO_OP_NO should not be set");
}
else
{
getEmitter()->emitIns_Nop(1);
}
break;
case GT_ARR_BOUNDS_CHECK:
#ifdef FEATURE_SIMD
case GT_SIMD_CHK:
#endif // FEATURE_SIMD
genRangeCheck(treeNode);
break;
case GT_PHYSREG:
if (treeNode->gtRegNum != treeNode->AsPhysReg()->gtSrcReg)
{
inst_RV_RV(INS_mov, treeNode->gtRegNum, treeNode->AsPhysReg()->gtSrcReg, targetType);
genTransferRegGCState(treeNode->gtRegNum, treeNode->AsPhysReg()->gtSrcReg);
}
genProduceReg(treeNode);
break;
case GT_PHYSREGDST:
break;
case GT_NULLCHECK:
{
assert(!treeNode->gtOp.gtOp1->isContained());
regNumber reg = genConsumeReg(treeNode->gtOp.gtOp1);
emit->emitIns_AR_R(INS_cmp, EA_4BYTE, reg, reg, 0);
}
break;
case GT_CATCH_ARG:
noway_assert(handlerGetsXcptnObj(compiler->compCurBB->bbCatchTyp));
/* Catch arguments get passed in a register. genCodeForBBlist()
would have marked it as holding a GC object, but not used. */
noway_assert(gcInfo.gcRegGCrefSetCur & RBM_EXCEPTION_OBJECT);
genConsumeReg(treeNode);
break;
#if !FEATURE_EH_FUNCLETS
case GT_END_LFIN:
NYI_X86("GT_END_LFIN codegen");
#endif
case GT_PINVOKE_PROLOG:
noway_assert(((gcInfo.gcRegGCrefSetCur|gcInfo.gcRegByrefSetCur) & ~RBM_ARG_REGS) == 0);
// the runtime side requires the codegen here to be consistent
emit->emitDisableRandomNops();
break;
case GT_LABEL:
genPendingCallLabel = genCreateTempLabel();
treeNode->gtLabel.gtLabBB = genPendingCallLabel;
emit->emitIns_R_L(INS_lea, EA_PTRSIZE, genPendingCallLabel, treeNode->gtRegNum);
break;
case GT_COPYOBJ:
genCodeForCpObj(treeNode->AsCpObj());
break;
case GT_COPYBLK:
{
GenTreeCpBlk* cpBlkOp = treeNode->AsCpBlk();
if (cpBlkOp->gtBlkOpGcUnsafe)
{
getEmitter()->emitDisableGC();
}
switch (cpBlkOp->gtBlkOpKind)
{
#ifdef _TARGET_AMD64_
case GenTreeBlkOp::BlkOpKindHelper:
genCodeForCpBlk(cpBlkOp);
break;
#endif // _TARGET_AMD64_
case GenTreeBlkOp::BlkOpKindRepInstr:
genCodeForCpBlkRepMovs(cpBlkOp);
break;
case GenTreeBlkOp::BlkOpKindUnroll:
genCodeForCpBlkUnroll(cpBlkOp);
break;
default:
unreached();
}
if (cpBlkOp->gtBlkOpGcUnsafe)
{
getEmitter()->emitEnableGC();
}
}
break;
case GT_INITBLK:
{
GenTreeInitBlk* initBlkOp = treeNode->AsInitBlk();
switch (initBlkOp->gtBlkOpKind)
{
case GenTreeBlkOp::BlkOpKindHelper:
genCodeForInitBlk(initBlkOp);
break;
case GenTreeBlkOp::BlkOpKindRepInstr:
genCodeForInitBlkRepStos(initBlkOp);
break;
case GenTreeBlkOp::BlkOpKindUnroll:
genCodeForInitBlkUnroll(initBlkOp);
break;
default:
unreached();
}
}
break;
case GT_JMPTABLE:
genJumpTable(treeNode);
break;
case GT_SWITCH_TABLE:
genTableBasedSwitch(treeNode);
break;
case GT_ARR_INDEX:
genCodeForArrIndex(treeNode->AsArrIndex());
break;
case GT_ARR_OFFSET:
genCodeForArrOffset(treeNode->AsArrOffs());
break;
case GT_CLS_VAR_ADDR:
getEmitter()->emitIns_R_C(INS_lea, EA_PTRSIZE, targetReg, treeNode->gtClsVar.gtClsVarHnd, 0);
break;
default:
{
#ifdef DEBUG
char message[256];
sprintf(message, "Unimplemented node type %s\n", GenTree::NodeName(treeNode->OperGet()));
#endif
assert(!"Unknown node in codegen");
}
break;
}
}
// Generate code for division (or mod) by power of two
// or negative powers of two. (meaning -1 * a power of two, not 2^(-1))
// Op2 must be a contained integer constant.
void
CodeGen::genCodeForPow2Div(GenTreeOp* tree)
{
GenTree *dividend = tree->gtOp.gtOp1;
GenTree *divisor = tree->gtOp.gtOp2;
genTreeOps oper = tree->OperGet();
emitAttr size = emitTypeSize(tree);
emitter *emit = getEmitter();
regNumber targetReg = tree->gtRegNum;
var_types targetType = tree->TypeGet();
bool isSigned = oper == GT_MOD || oper == GT_DIV;
// precondition: extended dividend is in RDX:RAX
// which means it is either all zeros or all ones
noway_assert(divisor->isContained());
GenTreeIntConCommon* divImm = divisor->AsIntConCommon();
ssize_t imm = divImm->IconValue();
ssize_t abs_imm = abs(imm);
noway_assert(isPow2(abs_imm));
if (isSigned)
{
if (imm == 1)
{
if (oper == GT_DIV)
{
if (targetReg != REG_RAX)
inst_RV_RV(INS_mov, targetReg, REG_RAX, targetType);
}
else
{
assert(oper == GT_MOD);
instGen_Set_Reg_To_Zero(size, targetReg);
}
return;
}
if (abs_imm == 2)
{
if (oper == GT_MOD)
{
emit->emitIns_R_I(INS_and, size, REG_RAX, 1); // result is 0 or 1
// xor with rdx will flip all bits if negative
emit->emitIns_R_R(INS_xor, size, REG_RAX, REG_RDX); // 111.11110 or 0
}
else
{
assert(oper == GT_DIV);
// add 1 if it's negative
emit->emitIns_R_R(INS_sub, size, REG_RAX, REG_RDX);
}
}
else
{
// add imm-1 if negative
emit->emitIns_R_I(INS_and, size, REG_RDX, abs_imm - 1);
emit->emitIns_R_R(INS_add, size, REG_RAX, REG_RDX);
}
if (oper == GT_DIV)
{
unsigned shiftAmount = genLog2(unsigned(abs_imm));
inst_RV_SH(INS_sar, size, REG_RAX, shiftAmount);
if (imm < 0)
{
emit->emitIns_R(INS_neg, size, REG_RAX);
}
}
else
{
assert(oper == GT_MOD);
if (abs_imm > 2)
{
emit->emitIns_R_I(INS_and, size, REG_RAX, abs_imm - 1);
}
// RDX contains 'imm-1' if negative
emit->emitIns_R_R(INS_sub, size, REG_RAX, REG_RDX);
}
if (targetReg != REG_RAX)
{
inst_RV_RV(INS_mov, targetReg, REG_RAX, targetType);
}
}
else
{
assert (imm > 0);
if (targetReg != dividend->gtRegNum)
{
inst_RV_RV(INS_mov, targetReg, dividend->gtRegNum, targetType);
}
if (oper == GT_UDIV)
{
inst_RV_SH(INS_shr, size, targetReg, genLog2(unsigned(imm)));
}
else
{
assert(oper == GT_UMOD);
emit->emitIns_R_I(INS_and, size, targetReg, imm -1);
}
}
}
/***********************************************************************************************
* Generate code for localloc
*/
void
CodeGen::genLclHeap(GenTreePtr tree)
{
NYI_X86("Localloc");
assert(tree->OperGet() == GT_LCLHEAP);
GenTreePtr size = tree->gtOp.gtOp1;
noway_assert((genActualType(size->gtType) == TYP_INT) || (genActualType(size->gtType) == TYP_I_IMPL));
regNumber targetReg = tree->gtRegNum;
regMaskTP tmpRegsMask = tree->gtRsvdRegs;
regNumber regCnt = REG_NA;
regNumber pspSymReg = REG_NA;
var_types type = genActualType(size->gtType);
emitAttr easz = emitTypeSize(type);
BasicBlock* endLabel = nullptr;
#ifdef DEBUG
// Verify ESP
if (compiler->opts.compStackCheckOnRet)
{
noway_assert(compiler->lvaReturnEspCheck != 0xCCCCCCCC && compiler->lvaTable[compiler->lvaReturnEspCheck].lvDoNotEnregister && compiler->lvaTable[compiler->lvaReturnEspCheck].lvOnFrame);
getEmitter()->emitIns_S_R(INS_cmp, EA_PTRSIZE, REG_SPBASE, compiler->lvaReturnEspCheck, 0);
BasicBlock * esp_check = genCreateTempLabel();
inst_JMP(genJumpKindForOper(GT_EQ, true), esp_check);
getEmitter()->emitIns(INS_BREAKPOINT);
genDefineTempLabel(esp_check);
}
#endif
noway_assert(isFramePointerUsed()); // localloc requires Frame Pointer to be established since SP changes
noway_assert(genStackLevel == 0); // Can't have anything on the stack
// Whether method has PSPSym.
bool hasPspSym;
unsigned stackAdjustment = 0;
BasicBlock* loop = NULL;
#if FEATURE_EH_FUNCLETS
hasPspSym = (compiler->lvaPSPSym != BAD_VAR_NUM);
#else
hasPspSym = false;
#endif
// compute the amount of memory to allocate to properly STACK_ALIGN.
size_t amount = 0;
if (size->IsCnsIntOrI())
{
// If size is a constant, then it must be contained.
assert(size->isContained());
// If amount is zero then return null in targetReg
amount = size->gtIntCon.gtIconVal;
if (amount == 0)
{
instGen_Set_Reg_To_Zero(EA_PTRSIZE, targetReg);
goto BAILOUT;
}
// 'amount' is the total numbe of bytes to localloc to properly STACK_ALIGN
amount = AlignUp(amount, STACK_ALIGN);
}
else
{
// If 0 bail out by returning null in targetReg
genConsumeRegAndCopy(size, targetReg);
endLabel = genCreateTempLabel();
getEmitter()->emitIns_R_R(INS_test, easz, targetReg, targetReg);
inst_JMP(EJ_je, endLabel);
// Compute the size of the block to allocate and perform alignment.
// If the method has no PSPSym and compInitMem=true, we can reuse targetReg as regcnt,
// since we don't need any internal registers.
if (!hasPspSym && compiler->info.compInitMem)
{
assert(genCountBits(tmpRegsMask) == 0);
regCnt = targetReg;
}
else
{
assert(genCountBits(tmpRegsMask) >= 1);
regMaskTP regCntMask = genFindLowestBit(tmpRegsMask);
tmpRegsMask &= ~regCntMask;
regCnt = genRegNumFromMask(regCntMask);
if (regCnt != targetReg)
inst_RV_RV(INS_mov, regCnt, targetReg, size->TypeGet());
}
// Align to STACK_ALIGN
// regCnt will be the total number of bytes to localloc
inst_RV_IV(INS_add, regCnt, (STACK_ALIGN - 1), emitActualTypeSize(type));
inst_RV_IV(INS_AND, regCnt, ~(STACK_ALIGN - 1), emitActualTypeSize(type));
}
#if FEATURE_EH_FUNCLETS
// If we have PSPsym, then need to re-locate it after localloc.
if (hasPspSym)
{
stackAdjustment += STACK_ALIGN;
// Save a copy of PSPSym
assert(genCountBits(tmpRegsMask) >= 1);
regMaskTP pspSymRegMask = genFindLowestBit(tmpRegsMask);
tmpRegsMask &= ~pspSymRegMask;
pspSymReg = genRegNumFromMask(pspSymRegMask);
getEmitter()->emitIns_R_S(ins_Store(TYP_I_IMPL), EA_PTRSIZE, pspSymReg, compiler->lvaPSPSym, 0);
}
#endif
#if FEATURE_FIXED_OUT_ARGS
// If we have an outgoing arg area then we must adjust the SP by popping off the
// outgoing arg area. We will restore it right before we return from this method.
//
// Localloc is supposed to return stack space that is STACK_ALIGN'ed. The following
// are the cases that needs to be handled:
// i) Method has PSPSym + out-going arg area.
// It is guaranteed that size of out-going arg area is STACK_ALIGNED (see fgMorphArgs).
// Therefore, we will pop-off RSP upto out-going arg area before locallocating.
// We need to add padding to ensure RSP is STACK_ALIGN'ed while re-locating PSPSym + arg area.
// ii) Method has no PSPSym but out-going arg area.
// Almost same case as above without the requirement to pad for the final RSP to be STACK_ALIGN'ed.
// iii) Method has PSPSym but no out-going arg area.
// Nothing to pop-off from the stack but needs to relocate PSPSym with SP padded.
// iv) Method has neither PSPSym nor out-going arg area.
// Nothing needs to popped off from stack nor relocated.
if (compiler->lvaOutgoingArgSpaceSize > 0)
{
assert((compiler->lvaOutgoingArgSpaceSize % STACK_ALIGN) == 0); // This must be true for the stack to remain aligned
inst_RV_IV(INS_add, REG_SPBASE, compiler->lvaOutgoingArgSpaceSize, EA_PTRSIZE);
stackAdjustment += compiler->lvaOutgoingArgSpaceSize;
}
#endif
if (size->IsCnsIntOrI())
{
// We should reach here only for non-zero, constant size allocations.
assert(amount > 0);
// For small allocations we will generate up to six push 0 inline
size_t cntPtrSizedWords = (amount >> STACK_ALIGN_SHIFT);
if (cntPtrSizedWords <= 6)
{
while (cntPtrSizedWords != 0)
{
// push_hide means don't track the stack
inst_IV(INS_push_hide, 0);
cntPtrSizedWords--;
}
goto ALLOC_DONE;
}
else if (!compiler->info.compInitMem && (amount < CORINFO_PAGE_SIZE)) // must be < not <=
{
// Since the size is a page or less, simply adjust ESP
// ESP might already be in the guard page, must touch it BEFORE
// the alloc, not after.
getEmitter()->emitIns_AR_R(INS_TEST, EA_4BYTE, REG_SPBASE, REG_SPBASE, 0);
inst_RV_IV(INS_sub, REG_SPBASE, amount, EA_PTRSIZE);
goto ALLOC_DONE;
}
// else, "mov regCnt, amount"
// If the method has no PSPSym and compInitMem=true, we can reuse targetReg as regcnt.
// Since size is a constant, regCnt is not yet initialized.
assert(regCnt == REG_NA);
if (!hasPspSym && compiler->info.compInitMem)
{
assert(genCountBits(tmpRegsMask) == 0);
regCnt = targetReg;
}
else
{
assert(genCountBits(tmpRegsMask) >= 1);
regMaskTP regCntMask = genFindLowestBit(tmpRegsMask);
tmpRegsMask &= ~regCntMask;
regCnt = genRegNumFromMask(regCntMask);
}
genSetRegToIcon(regCnt, amount, ((int)amount == amount)? TYP_INT : TYP_LONG);
}
loop = genCreateTempLabel();
if (compiler->info.compInitMem)
{
// At this point 'regCnt' is set to the total number of bytes to locAlloc.
// Since we have to zero out the allocated memory AND ensure that RSP is always valid
// by tickling the pages, we will just push 0's on the stack.
//
// Note: regCnt is guaranteed to be even on Amd64 since STACK_ALIGN/TARGET_POINTER_SIZE = 2
// and localloc size is a multiple of STACK_ALIGN.
// Loop:
genDefineTempLabel(loop);
// dec is a 2 byte instruction, but sub is 4 (could be 3 if
// we know size is TYP_INT instead of TYP_I_IMPL)
// Also we know that we can only push 8 bytes at a time, but
// alignment is 16 bytes, so we can push twice and do a sub
// for just a little bit of loop unrolling
inst_IV(INS_push_hide, 0); // --- push 0
inst_IV(INS_push_hide, 0); // --- push 0
// If not done, loop
// Note that regCnt is the number of bytes to stack allocate.
// Therefore we need to subtract 16 from regcnt here.
assert(genIsValidIntReg(regCnt));
inst_RV_IV(INS_sub, regCnt, 16, emitActualTypeSize(type));
inst_JMP(EJ_jne, loop);
}
else
{
//At this point 'regCnt' is set to the total number of bytes to locAlloc.
//
//We don't need to zero out the allocated memory. However, we do have
//to tickle the pages to ensure that ESP is always valid and is
//in sync with the "stack guard page". Note that in the worst
//case ESP is on the last byte of the guard page. Thus you must
//touch ESP+0 first not ESP+x01000.
//
//Another subtlety is that you don't want ESP to be exactly on the
//boundary of the guard page because PUSH is predecrement, thus
//call setup would not touch the guard page but just beyond it
//
//Note that we go through a few hoops so that ESP never points to
//illegal pages at any time during the ticking process
//
// neg REGCNT
// add REGCNT, ESP // reg now holds ultimate ESP
// jb loop // result is smaller than orignial ESP (no wrap around)
// xor REGCNT, REGCNT, // Overflow, pick lowest possible number
// loop:
// test ESP, [ESP+0] // tickle the page
// mov REGTMP, ESP
// sub REGTMP, PAGE_SIZE
// mov ESP, REGTMP
// cmp ESP, REGCNT
// jae loop
//
// mov ESP, REG
// end:
inst_RV(INS_NEG, regCnt, TYP_I_IMPL);
inst_RV_RV(INS_add, regCnt, REG_SPBASE, TYP_I_IMPL);
inst_JMP(EJ_jb, loop);
instGen_Set_Reg_To_Zero(EA_PTRSIZE, regCnt);
genDefineTempLabel(loop);
// Tickle the decremented value, and move back to ESP,
// note that it has to be done BEFORE the update of ESP since
// ESP might already be on the guard page. It is OK to leave
// the final value of ESP on the guard page
getEmitter()->emitIns_AR_R(INS_TEST, EA_4BYTE, REG_SPBASE, REG_SPBASE, 0);
// This is a harmless trick to avoid the emitter trying to track the
// decrement of the ESP - we do the subtraction in another reg instead
// of adjusting ESP directly.
assert(tmpRegsMask != RBM_NONE);
assert(genCountBits(tmpRegsMask) == 1);
regNumber regTmp = genRegNumFromMask(tmpRegsMask);
inst_RV_RV(INS_mov, regTmp, REG_SPBASE, TYP_I_IMPL);
inst_RV_IV(INS_sub, regTmp, CORINFO_PAGE_SIZE, EA_PTRSIZE);
inst_RV_RV(INS_mov, REG_SPBASE, regTmp, TYP_I_IMPL);
inst_RV_RV(INS_cmp, REG_SPBASE, regCnt, TYP_I_IMPL);
inst_JMP(EJ_jae, loop);
// Move the final value to ESP
inst_RV_RV(INS_mov, REG_SPBASE, regCnt);
}
ALLOC_DONE:
// Re-adjust SP to allocate PSPSym and out-going arg area
if (stackAdjustment > 0)
{
assert((stackAdjustment % STACK_ALIGN) == 0); // This must be true for the stack to remain aligned
inst_RV_IV(INS_sub, REG_SPBASE, stackAdjustment, EA_PTRSIZE);
#if FEATURE_EH_FUNCLETS
// Write PSPSym to its new location.
if (hasPspSym)
{
assert(genIsValidIntReg(pspSymReg));
getEmitter()->emitIns_S_R(ins_Store(TYP_I_IMPL), EA_PTRSIZE, pspSymReg, compiler->lvaPSPSym, 0);
}
#endif
}
// Return the stackalloc'ed address in result register.
// TargetReg = RSP + stackAdjustment.
getEmitter()->emitIns_R_AR(INS_lea, EA_PTRSIZE, targetReg, REG_SPBASE, stackAdjustment);
BAILOUT:
if (endLabel != nullptr)
genDefineTempLabel(endLabel);
// Write the lvaShadowSPfirst stack frame slot
noway_assert(compiler->lvaLocAllocSPvar != BAD_VAR_NUM);
getEmitter()->emitIns_S_R(ins_Store(TYP_I_IMPL), EA_PTRSIZE, REG_SPBASE, compiler->lvaLocAllocSPvar, 0);
#if STACK_PROBES
if (compiler->opts.compNeedStackProbes)
{
genGenerateStackProbe();
}
#endif
#ifdef DEBUG
// Update new ESP
if (compiler->opts.compStackCheckOnRet)
{
noway_assert(compiler->lvaReturnEspCheck != 0xCCCCCCCC && compiler->lvaTable[compiler->lvaReturnEspCheck].lvDoNotEnregister && compiler->lvaTable[compiler->lvaReturnEspCheck].lvOnFrame);
getEmitter()->emitIns_S_R(ins_Store(TYP_I_IMPL), EA_PTRSIZE, REG_SPBASE, compiler->lvaReturnEspCheck, 0);
}
#endif
genProduceReg(tree);
}
// Generate code for InitBlk using rep stos.
// Preconditions:
// The size of the buffers must be a constant and also less than INITBLK_STOS_LIMIT bytes.
// Any value larger than that, we'll use the helper even if both the
// fill byte and the size are integer constants.
void CodeGen::genCodeForInitBlkRepStos(GenTreeInitBlk* initBlkNode)
{
// Make sure we got the arguments of the initblk/initobj operation in the right registers
GenTreePtr blockSize = initBlkNode->Size();
GenTreePtr dstAddr = initBlkNode->Dest();
GenTreePtr initVal = initBlkNode->InitVal();
#ifdef DEBUG
assert(!dstAddr->isContained());
assert(!initVal->isContained());
assert(!blockSize->isContained());
assert(blockSize->gtSkipReloadOrCopy()->IsCnsIntOrI());
size_t size = blockSize->gtIntCon.gtIconVal;
if (initVal->IsCnsIntOrI())
{
assert(size > INITBLK_UNROLL_LIMIT && size < INITBLK_STOS_LIMIT);
}
#endif // DEBUG
genConsumeBlockOp(initBlkNode, REG_RDI, REG_RAX, REG_RCX);
instGen(INS_r_stosb);
}
// Generate code for InitBlk by performing a loop unroll
// Preconditions:
// a) Both the size and fill byte value are integer constants.
// b) The size of the struct to initialize is smaller than INITBLK_UNROLL_LIMIT bytes.
//
void CodeGen::genCodeForInitBlkUnroll(GenTreeInitBlk* initBlkNode)
{
// Make sure we got the arguments of the initblk/initobj operation in the right registers
GenTreePtr blockSize = initBlkNode->Size();
GenTreePtr dstAddr = initBlkNode->Dest();
GenTreePtr initVal = initBlkNode->InitVal();
#ifdef DEBUG
assert(!dstAddr->isContained());
assert(!initVal->isContained());
assert(blockSize->isContained());
assert(blockSize->IsCnsIntOrI());
#endif // DEBUG
size_t size = blockSize->gtIntCon.gtIconVal;
assert(size <= INITBLK_UNROLL_LIMIT);
assert(initVal->gtSkipReloadOrCopy()->IsCnsIntOrI());
emitter *emit = getEmitter();
genConsumeOperands(initBlkNode->gtGetOp1()->AsOp());
// If the initVal was moved, or spilled and reloaded to a different register,
// get the original initVal from below the GT_RELOAD, but only after capturing the valReg,
// which needs to be the new register.
regNumber valReg = initVal->gtRegNum;
initVal = initVal->gtSkipReloadOrCopy();
unsigned offset = 0;
// Perform an unroll using SSE2 loads and stores.
if (size >= XMM_REGSIZE_BYTES)
{
regNumber tmpReg = genRegNumFromMask(initBlkNode->gtRsvdRegs);
#ifdef DEBUG
assert(initBlkNode->gtRsvdRegs != RBM_NONE);
assert(genCountBits(initBlkNode->gtRsvdRegs) == 1);
assert(genIsValidFloatReg(tmpReg));
#endif // DEBUG
if (initVal->gtIntCon.gtIconVal != 0)
{
emit->emitIns_R_R(INS_mov_i2xmm, EA_8BYTE, tmpReg, valReg);
emit->emitIns_R_R(INS_punpckldq, EA_8BYTE, tmpReg, tmpReg);
}
else
{
emit->emitIns_R_R(INS_xorpd, EA_8BYTE, tmpReg, tmpReg);
}
// Determine how many 16 byte slots we're going to fill using SSE movs.
size_t slots = size / XMM_REGSIZE_BYTES;
while (slots-- > 0)
{
emit->emitIns_AR_R(INS_movdqu, EA_8BYTE, tmpReg, dstAddr->gtRegNum, offset);
offset += XMM_REGSIZE_BYTES;
}
}
// Fill the remainder (or a < 16 byte sized struct)
if ((size & 8) != 0)
{
#ifdef _TARGET_X86_
// TODO-X86-CQ: [1091735] Revisit block ops codegen. One example: use movq for 8 byte movs.
emit->emitIns_AR_R(INS_mov, EA_4BYTE, valReg, dstAddr->gtRegNum, offset);
offset += 4;
emit->emitIns_AR_R(INS_mov, EA_4BYTE, valReg, dstAddr->gtRegNum, offset);
offset += 4;
#else // !_TARGET_X86_
emit->emitIns_AR_R(INS_mov, EA_8BYTE, valReg, dstAddr->gtRegNum, offset);
offset += 8;
#endif // !_TARGET_X86_
}
if ((size & 4) != 0)
{
emit->emitIns_AR_R(INS_mov, EA_4BYTE, valReg, dstAddr->gtRegNum, offset);
offset += 4;
}
if ((size & 2) != 0)
{
emit->emitIns_AR_R(INS_mov, EA_2BYTE, valReg, dstAddr->gtRegNum, offset);
offset += 2;
}
if ((size & 1) != 0)
{
emit->emitIns_AR_R(INS_mov, EA_1BYTE, valReg, dstAddr->gtRegNum, offset);
}
}
// Generates code for InitBlk by calling the VM memset helper function.
// Preconditions:
// a) The size argument of the InitBlk is not an integer constant.
// b) The size argument of the InitBlk is >= INITBLK_STOS_LIMIT bytes.
void CodeGen::genCodeForInitBlk(GenTreeInitBlk* initBlkNode)
{
#ifdef _TARGET_AMD64_
// Make sure we got the arguments of the initblk operation in the right registers
GenTreePtr blockSize = initBlkNode->Size();
GenTreePtr dstAddr = initBlkNode->Dest();
GenTreePtr initVal = initBlkNode->InitVal();
#ifdef DEBUG
assert(!dstAddr->isContained());
assert(!initVal->isContained());
assert(!blockSize->isContained());
if (blockSize->IsCnsIntOrI())
{
assert(blockSize->gtIntCon.gtIconVal >= INITBLK_STOS_LIMIT);
}
#endif // DEBUG
genConsumeBlockOp(initBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2);
genEmitHelperCall(CORINFO_HELP_MEMSET, 0, EA_UNKNOWN);
#else // !_TARGET_AMD64_
NYI_X86("Helper call for InitBlk");
#endif // !_TARGET_AMD64_
}
// Generate code for a load from some address + offset
// base: tree node which can be either a local address or arbitrary node
// offset: distance from the base from which to load
void CodeGen::genCodeForLoadOffset(instruction ins, emitAttr size, regNumber dst, GenTree* base, unsigned offset)
{
emitter *emit = getEmitter();
if (base->OperIsLocalAddr())
{
if (base->gtOper == GT_LCL_FLD_ADDR)
offset += base->gtLclFld.gtLclOffs;
emit->emitIns_R_S(ins, size, dst, base->gtLclVarCommon.gtLclNum, offset);
}
else
{
emit->emitIns_R_AR(ins, size, dst, base->gtRegNum, offset);
}
}
// Generate code for a store to some address + offset
// base: tree node which can be either a local address or arbitrary node
// offset: distance from the base from which to load
void CodeGen::genCodeForStoreOffset(instruction ins, emitAttr size, regNumber src, GenTree* base, unsigned offset)
{
emitter *emit = getEmitter();
if (base->OperIsLocalAddr())
{
if (base->gtOper == GT_LCL_FLD_ADDR)
offset += base->gtLclFld.gtLclOffs;
emit->emitIns_S_R(ins, size, src, base->gtLclVarCommon.gtLclNum, offset);
}
else
{
emit->emitIns_AR_R(ins, size, src, base->gtRegNum, offset);
}
}
// Generates CpBlk code by performing a loop unroll
// Preconditions:
// The size argument of the CpBlk node is a constant and <= 64 bytes.
// This may seem small but covers >95% of the cases in several framework assemblies.
//
void CodeGen::genCodeForCpBlkUnroll(GenTreeCpBlk* cpBlkNode)
{
// Make sure we got the arguments of the cpblk operation in the right registers
GenTreePtr blockSize = cpBlkNode->Size();
GenTreePtr dstAddr = cpBlkNode->Dest();
GenTreePtr srcAddr = cpBlkNode->Source();
assert(blockSize->IsCnsIntOrI());
size_t size = blockSize->gtIntCon.gtIconVal;
assert(size <= CPBLK_UNROLL_LIMIT);
emitter *emit = getEmitter();
if (!srcAddr->isContained())
genConsumeReg(srcAddr);
if (!dstAddr->isContained())
genConsumeReg(dstAddr);
unsigned offset = 0;
// If the size of this struct is larger than 16 bytes
// let's use SSE2 to be able to do 16 byte at a time
// loads and stores.
if (size >= XMM_REGSIZE_BYTES)
{
assert(cpBlkNode->gtRsvdRegs != RBM_NONE);
regNumber xmmReg = genRegNumFromMask(cpBlkNode->gtRsvdRegs & RBM_ALLFLOAT);
assert(genIsValidFloatReg(xmmReg));
size_t slots = size / XMM_REGSIZE_BYTES;
while (slots-- > 0)
{
// Load
genCodeForLoadOffset(INS_movdqu, EA_8BYTE, xmmReg, srcAddr, offset);
// Store
genCodeForStoreOffset(INS_movdqu, EA_8BYTE, xmmReg, dstAddr, offset);
offset += XMM_REGSIZE_BYTES;
}
}
// Fill the remainder (15 bytes or less) if there's one.
if ((size & 0xf) != 0)
{
// Grab the integer temp register to emit the remaining loads and stores.
regNumber tmpReg = genRegNumFromMask(cpBlkNode->gtRsvdRegs & RBM_ALLINT);
if ((size & 8) != 0)
{
#ifdef _TARGET_X86_
// TODO-X86-CQ: [1091735] Revisit block ops codegen. One example: use movq for 8 byte movs.
for (unsigned savedOffs = offset; offset < savedOffs + 8; offset += 4)
{
genCodeForLoadOffset(INS_mov, EA_4BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_mov, EA_4BYTE, tmpReg, dstAddr, offset);
}
#else // !_TARGET_X86_
genCodeForLoadOffset(INS_mov, EA_8BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_mov, EA_8BYTE, tmpReg, dstAddr, offset);
offset += 8;
#endif // !_TARGET_X86_
}
if ((size & 4) != 0)
{
genCodeForLoadOffset(INS_mov, EA_4BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_mov, EA_4BYTE, tmpReg, dstAddr, offset);
offset += 4;
}
if ((size & 2) != 0)
{
genCodeForLoadOffset(INS_mov, EA_2BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_mov, EA_2BYTE, tmpReg, dstAddr, offset);
offset += 2;
}
if ((size & 1) != 0)
{
genCodeForLoadOffset(INS_mov, EA_1BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_mov, EA_1BYTE, tmpReg, dstAddr, offset);
}
}
}
// Generate code for CpBlk by using rep movs
// Preconditions:
// The size argument of the CpBlk is a constant and is between
// CPBLK_UNROLL_LIMIT and CPBLK_MOVS_LIMIT bytes.
void CodeGen::genCodeForCpBlkRepMovs(GenTreeCpBlk* cpBlkNode)
{
// Make sure we got the arguments of the cpblk operation in the right registers
GenTreePtr blockSize = cpBlkNode->Size();
GenTreePtr dstAddr = cpBlkNode->Dest();
GenTreePtr srcAddr = cpBlkNode->Source();
#ifdef DEBUG
assert(!dstAddr->isContained());
assert(!srcAddr->isContained());
assert(!blockSize->isContained());
assert(blockSize->IsCnsIntOrI());
size_t size = blockSize->gtIntCon.gtIconVal;
#ifdef _TARGET_X64_
assert(size > CPBLK_UNROLL_LIMIT && size < CPBLK_MOVS_LIMIT);
#else
assert(size > CPBLK_UNROLL_LIMIT);
#endif
#endif // DEBUG
genConsumeBlockOp(cpBlkNode, REG_RDI, REG_RSI, REG_RCX);
instGen(INS_r_movsb);
}
// Generate code for CpObj nodes wich copy structs that have interleaved
// GC pointers.
// This will generate a sequence of movsq instructions for the cases of non-gc members
// and calls to the BY_REF_ASSIGN helper otherwise.
void CodeGen::genCodeForCpObj(GenTreeCpObj* cpObjNode)
{
// Make sure we got the arguments of the cpobj operation in the right registers
GenTreePtr clsTok = cpObjNode->ClsTok();
GenTreePtr dstAddr = cpObjNode->Dest();
GenTreePtr srcAddr = cpObjNode->Source();
bool dstOnStack = dstAddr->OperIsLocalAddr();
#ifdef DEBUG
bool isRepMovsqUsed = false;
assert(!dstAddr->isContained());
assert(!srcAddr->isContained());
// If the GenTree node has data about GC pointers, this means we're dealing
// with CpObj, so this requires special logic.
assert(cpObjNode->gtGcPtrCount > 0);
// MovSq instruction is used for copying non-gcref fields and it needs
// src = RSI and dst = RDI.
// Either these registers must not contain lclVars, or they must be dying or marked for spill.
// This is because these registers are incremented as we go through the struct.
if (srcAddr->gtRegNum == REG_RSI)
{
assert(!genIsRegCandidateLocal(srcAddr) || (srcAddr->gtFlags & (GTF_VAR_DEATH | GTF_SPILL)) != 0);
}
if (dstAddr->gtRegNum == REG_RDI)
{
assert(!genIsRegCandidateLocal(dstAddr) || (dstAddr->gtFlags & (GTF_VAR_DEATH | GTF_SPILL)) != 0);
}
#endif // DEBUG
// Consume these registers.
// They may now contain gc pointers (depending on their type; gcMarkRegPtrVal will "do the right thing").
genConsumeBlockOp(cpObjNode, REG_RDI, REG_RSI, REG_NA);
gcInfo.gcMarkRegPtrVal(REG_RSI, srcAddr->TypeGet());
gcInfo.gcMarkRegPtrVal(REG_RDI, dstAddr->TypeGet());
unsigned slots = cpObjNode->gtSlots;
// If we can prove it's on the stack we don't need to use the write barrier.
if (dstOnStack)
{
if (slots >= CPOBJ_NONGC_SLOTS_LIMIT)
{
#ifdef DEBUG
// If the destination of the CpObj is on the stack
// make sure we allocated RCX to emit rep movsq.
regNumber tmpReg = genRegNumFromMask(cpObjNode->gtRsvdRegs & RBM_ALLINT);
assert(tmpReg == REG_RCX);
isRepMovsqUsed = true;
#endif // DEBUG
getEmitter()->emitIns_R_I(INS_mov, EA_4BYTE, REG_RCX, slots);
instGen(INS_r_movsq);
}
else
{
// For small structs, it's better to emit a sequence of movsq than to
// emit a rep movsq instruction.
while (slots > 0)
{
instGen(INS_movsq);
slots--;
}
}
}
else
{
BYTE* gcPtrs = cpObjNode->gtGcPtrs;
unsigned gcPtrCount = cpObjNode->gtGcPtrCount;
unsigned i = 0;
while (i < slots)
{
switch (gcPtrs[i])
{
case TYPE_GC_NONE:
// Let's see if we can use rep movsq instead of a sequence of movsq instructions
// to save cycles and code size.
{
unsigned nonGcSlotCount = 0;
do
{
nonGcSlotCount++;
i++;
} while (i < slots && gcPtrs[i] == TYPE_GC_NONE);
// If we have a very small contiguous non-gc region, it's better just to
// emit a sequence of movsq instructions
if (nonGcSlotCount < CPOBJ_NONGC_SLOTS_LIMIT)
{
while (nonGcSlotCount > 0)
{
instGen(INS_movsq);
nonGcSlotCount--;
}
}
else
{
#ifdef DEBUG
// Otherwise, we can save code-size and improve CQ by emitting
// rep movsq
regNumber tmpReg = genRegNumFromMask(cpObjNode->gtRsvdRegs & RBM_ALLINT);
assert(tmpReg == REG_RCX);
isRepMovsqUsed = true;
#endif // DEBUG
getEmitter()->emitIns_R_I(INS_mov, EA_4BYTE, REG_RCX, nonGcSlotCount);
instGen(INS_r_movsq);
}
}
break;
default:
// We have a GC pointer, call the memory barrier.
genEmitHelperCall(CORINFO_HELP_ASSIGN_BYREF, 0, EA_PTRSIZE);
gcPtrCount--;
i++;
}
}
#ifdef DEBUG
if (!isRepMovsqUsed)
{
assert(clsTok->isContained());
}
assert(gcPtrCount == 0);
#endif // DEBUG
}
// Clear the gcInfo for RSI and RDI.
// While we normally update GC info prior to the last instruction that uses them,
// these actually live into the helper call.
gcInfo.gcMarkRegSetNpt(RBM_RSI);
gcInfo.gcMarkRegSetNpt(RBM_RDI);
}
// Generate code for a CpBlk node by the means of the VM memcpy helper call
// Preconditions:
// a) The size argument of the CpBlk is not an integer constant
// b) The size argument is a constant but is larger than CPBLK_MOVS_LIMIT bytes.
void CodeGen::genCodeForCpBlk(GenTreeCpBlk* cpBlkNode)
{
#ifdef _TARGET_AMD64_
// Make sure we got the arguments of the cpblk operation in the right registers
GenTreePtr blockSize = cpBlkNode->Size();
GenTreePtr dstAddr = cpBlkNode->Dest();
GenTreePtr srcAddr = cpBlkNode->Source();
assert(!dstAddr->isContained());
assert(!srcAddr->isContained());
assert(!blockSize->isContained());
#ifdef DEBUG
if (blockSize->IsCnsIntOrI())
{
assert(blockSize->gtIntCon.gtIconVal >= CPBLK_MOVS_LIMIT);
}
#endif // DEBUG
genConsumeBlockOp(cpBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2);
genEmitHelperCall(CORINFO_HELP_MEMCPY, 0, EA_UNKNOWN);
#else // !_TARGET_AMD64_
NYI_X86("Helper call for CpBlk");
#endif // !_TARGET_AMD64_
}
// generate code do a switch statement based on a table of ip-relative offsets
void
CodeGen::genTableBasedSwitch(GenTree* treeNode)
{
genConsumeOperands(treeNode->AsOp());
regNumber idxReg = treeNode->gtOp.gtOp1->gtRegNum;
regNumber baseReg = treeNode->gtOp.gtOp2->gtRegNum;
regNumber tmpReg = genRegNumFromMask(treeNode->gtRsvdRegs);
// load the ip-relative offset (which is relative to start of fgFirstBB)
getEmitter()->emitIns_R_ARX(INS_mov, EA_4BYTE, baseReg, baseReg, idxReg, 4, 0);
// add it to the absolute address of fgFirstBB
compiler->fgFirstBB->bbFlags |= BBF_JMP_TARGET;
getEmitter()->emitIns_R_L(INS_lea, EA_PTRSIZE, compiler->fgFirstBB, tmpReg);
getEmitter()->emitIns_R_R(INS_add, EA_PTRSIZE, baseReg, tmpReg);
// jmp baseReg
getEmitter()->emitIns_R(INS_i_jmp, emitTypeSize(TYP_I_IMPL), baseReg);
}
// emits the table and an instruction to get the address of the first element
void
CodeGen::genJumpTable(GenTree* treeNode)
{
noway_assert(compiler->compCurBB->bbJumpKind == BBJ_SWITCH);
assert(treeNode->OperGet() == GT_JMPTABLE);
unsigned jumpCount = compiler->compCurBB->bbJumpSwt->bbsCount;
BasicBlock** jumpTable = compiler->compCurBB->bbJumpSwt->bbsDstTab;
unsigned jmpTabOffs;
unsigned jmpTabBase;
jmpTabBase = getEmitter()->emitBBTableDataGenBeg(jumpCount, true);
jmpTabOffs = 0;
JITDUMP("\n J_M%03u_DS%02u LABEL DWORD\n", Compiler::s_compMethodsCount, jmpTabBase);
for (unsigned i=0; i<jumpCount; i++)
{
BasicBlock* target = *jumpTable++;
noway_assert(target->bbFlags & BBF_JMP_TARGET);
JITDUMP(" DD L_M%03u_BB%02u\n", Compiler::s_compMethodsCount, target->bbNum);
getEmitter()->emitDataGenData(i, target);
};
getEmitter()->emitDataGenEnd();
// Access to inline data is 'abstracted' by a special type of static member
// (produced by eeFindJitDataOffs) which the emitter recognizes as being a reference
// to constant data, not a real static field.
getEmitter()->emitIns_R_C(INS_lea,
emitTypeSize(TYP_I_IMPL),
treeNode->gtRegNum,
compiler->eeFindJitDataOffs(jmpTabBase),
0);
genProduceReg(treeNode);
}
// generate code for the locked operations:
// GT_LOCKADD, GT_XCHG, GT_XADD
void
CodeGen::genLockedInstructions(GenTree* treeNode)
{
GenTree* data = treeNode->gtOp.gtOp2;
GenTree* addr = treeNode->gtOp.gtOp1;
regNumber targetReg = treeNode->gtRegNum;
regNumber dataReg = data->gtRegNum;
regNumber addrReg = addr->gtRegNum;
instruction ins;
// all of these nodes implicitly do an indirection on op1
// so create a temporary node to feed into the pattern matching
GenTreeIndir i = indirForm(data->TypeGet(), addr);
genConsumeReg(addr);
// The register allocator should have extended the lifetime of the address
// so that it is not used as the target.
noway_assert(addrReg != targetReg);
// If data is a lclVar that's not a last use, we'd better have allocated a register
// for the result (except in the case of GT_LOCKADD which does not produce a register result).
assert(targetReg != REG_NA || treeNode->OperGet() == GT_LOCKADD || !genIsRegCandidateLocal(data) || (data->gtFlags & GTF_VAR_DEATH) != 0);
genConsumeIfReg(data);
if (targetReg != REG_NA && dataReg != REG_NA && dataReg != targetReg)
{
inst_RV_RV(ins_Copy(data->TypeGet()), targetReg, dataReg);
data->gtRegNum = targetReg;
// TODO-XArch-Cleanup: Consider whether it is worth it, for debugging purposes, to restore the
// original gtRegNum on data, after calling emitInsBinary below.
}
switch (treeNode->OperGet())
{
case GT_LOCKADD:
instGen(INS_lock);
ins = INS_add;
break;
case GT_XCHG:
// lock is implied by xchg
ins = INS_xchg;
break;
case GT_XADD:
instGen(INS_lock);
ins = INS_xadd;
break;
default:
unreached();
}
getEmitter()->emitInsBinary(ins, emitTypeSize(data), &i, data);
if (treeNode->gtRegNum != REG_NA)
{
genProduceReg(treeNode);
}
}
// generate code for BoundsCheck nodes
void
CodeGen::genRangeCheck(GenTreePtr oper)
{
#ifdef FEATURE_SIMD
noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK || oper->OperGet() == GT_SIMD_CHK);
#else // !FEATURE_SIMD
noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK);
#endif // !FEATURE_SIMD
GenTreeBoundsChk* bndsChk = oper->AsBoundsChk();
GenTreePtr arrLen = bndsChk->gtArrLen;
GenTreePtr arrIndex = bndsChk->gtIndex;
GenTreePtr arrRef = NULL;
int lenOffset = 0;
GenTree *src1, *src2;
emitJumpKind jmpKind;
genConsumeRegs(arrLen);
genConsumeRegs(arrIndex);
if (arrIndex->isContainedIntOrIImmed())
{
src1 = arrLen;
src2 = arrIndex;
jmpKind = EJ_jbe;
}
else
{
src1 = arrIndex;
src2 = arrLen;
jmpKind = EJ_jae;
}
#if DEBUG
var_types bndsChkType = src2->TypeGet();
// Bounds checks can only be 32 or 64 bit sized comparisons.
assert(bndsChkType == TYP_INT || bndsChkType == TYP_LONG);
// The type of the bounds check should always wide enough to compare against the index.
assert(emitTypeSize(bndsChkType) >= emitTypeSize(src1->TypeGet()));
#endif //DEBUG
getEmitter()->emitInsBinary(INS_cmp, emitTypeSize(src2->TypeGet()), src1, src2);
genJumpToThrowHlpBlk(jmpKind, Compiler::ACK_RNGCHK_FAIL, bndsChk->gtIndRngFailBB);
}
//------------------------------------------------------------------------
// genOffsetOfMDArrayLowerBound: Returns the offset from the Array object to the
// lower bound for the given dimension.
//
// Arguments:
// elemType - the element type of the array
// rank - the rank of the array
// dimension - the dimension for which the lower bound offset will be returned.
//
// Return Value:
// The offset.
unsigned
CodeGen::genOffsetOfMDArrayLowerBound(var_types elemType, unsigned rank, unsigned dimension)
{
// Note that the lower bound and length fields of the Array object are always TYP_INT, even on 64-bit targets.
return compiler->eeGetArrayDataOffset(elemType) + genTypeSize(TYP_INT) * (dimension + rank);
}
//------------------------------------------------------------------------
// genOffsetOfMDArrayLength: Returns the offset from the Array object to the
// size for the given dimension.
//
// Arguments:
// elemType - the element type of the array
// rank - the rank of the array
// dimension - the dimension for which the lower bound offset will be returned.
//
// Return Value:
// The offset.
unsigned
CodeGen::genOffsetOfMDArrayDimensionSize(var_types elemType, unsigned rank, unsigned dimension)
{
// Note that the lower bound and length fields of the Array object are always TYP_INT, even on 64-bit targets.
return compiler->eeGetArrayDataOffset(elemType) + genTypeSize(TYP_INT) * dimension;
}
//------------------------------------------------------------------------
// genCodeForArrIndex: Generates code to bounds check the index for one dimension of an array reference,
// producing the effective index by subtracting the lower bound.
//
// Arguments:
// arrIndex - the node for which we're generating code
//
// Return Value:
// None.
//
void
CodeGen::genCodeForArrIndex(GenTreeArrIndex* arrIndex)
{
GenTreePtr arrObj = arrIndex->ArrObj();
GenTreePtr indexNode = arrIndex->IndexExpr();
regNumber arrReg = genConsumeReg(arrObj);
regNumber indexReg = genConsumeReg(indexNode);
regNumber tgtReg = arrIndex->gtRegNum;
unsigned dim = arrIndex->gtCurrDim;
unsigned rank = arrIndex->gtArrRank;
var_types elemType = arrIndex->gtArrElemType;
noway_assert(tgtReg != REG_NA);
// Subtract the lower bound for this dimension.
// TODO-XArch-CQ: make this contained if it's an immediate that fits.
if (tgtReg != indexReg)
{
inst_RV_RV(INS_mov, tgtReg, indexReg, indexNode->TypeGet());
}
getEmitter()->emitIns_R_AR(INS_sub,
emitActualTypeSize(TYP_INT),
tgtReg,
arrReg,
genOffsetOfMDArrayLowerBound(elemType, rank, dim));
getEmitter()->emitIns_R_AR(INS_cmp,
emitActualTypeSize(TYP_INT),
tgtReg,
arrReg,
genOffsetOfMDArrayDimensionSize(elemType, rank, dim));
genJumpToThrowHlpBlk(EJ_jae, Compiler::ACK_RNGCHK_FAIL);
genProduceReg(arrIndex);
}
//------------------------------------------------------------------------
// genCodeForArrOffset: Generates code to compute the flattened array offset for
// one dimension of an array reference:
// result = (prevDimOffset * dimSize) + effectiveIndex
// where dimSize is obtained from the arrObj operand
//
// Arguments:
// arrOffset - the node for which we're generating code
//
// Return Value:
// None.
//
// Notes:
// dimSize and effectiveIndex are always non-negative, the former by design,
// and the latter because it has been normalized to be zero-based.
void
CodeGen::genCodeForArrOffset(GenTreeArrOffs* arrOffset)
{
GenTreePtr offsetNode = arrOffset->gtOffset;
GenTreePtr indexNode = arrOffset->gtIndex;
GenTreePtr arrObj = arrOffset->gtArrObj;
regNumber tgtReg = arrOffset->gtRegNum;
noway_assert(tgtReg != REG_NA);
unsigned dim = arrOffset->gtCurrDim;
unsigned rank = arrOffset->gtArrRank;
var_types elemType = arrOffset->gtArrElemType;
// We will use a temp register for the offset*scale+effectiveIndex computation.
regMaskTP tmpRegMask = arrOffset->gtRsvdRegs;
regNumber tmpReg = genRegNumFromMask(tmpRegMask);
// First, consume the operands in the correct order.
regNumber offsetReg = REG_NA;
if (!offsetNode->IsZero())
{
offsetReg = genConsumeReg(offsetNode);
}
else
{
assert(offsetNode->isContained());
}
regNumber indexReg = genConsumeReg(indexNode);
// Although arrReg may not be used in the constant-index case, if we have generated
// the value into a register, we must consume it, otherwise we will fail to end the
// live range of the gc ptr.
// TODO-CQ: Currently arrObj will always have a register allocated to it.
// We could avoid allocating a register for it, which would be of value if the arrObj
// is an on-stack lclVar.
regNumber arrReg = REG_NA;
if (arrObj->gtHasReg())
{
arrReg = genConsumeReg(arrObj);
}
if (!offsetNode->IsZero())
{
// Evaluate tgtReg = offsetReg*dim_size + indexReg.
// tmpReg is used to load dim_size and the result of the multiplication.
// Note that dim_size will never be negative.
getEmitter()->emitIns_R_AR(INS_mov,
emitActualTypeSize(TYP_INT),
tmpReg,
arrReg,
genOffsetOfMDArrayDimensionSize(elemType, rank, dim));
inst_RV_RV(INS_imul, tmpReg, offsetReg);
if (tmpReg == tgtReg)
{
inst_RV_RV(INS_add, tmpReg, indexReg);
}
else
{
if (indexReg != tgtReg)
{
inst_RV_RV(INS_mov, tgtReg, indexReg, TYP_I_IMPL);
}
inst_RV_RV(INS_add, tgtReg, tmpReg);
}
}
else
{
if (indexReg != tgtReg)
{
inst_RV_RV(INS_mov, tgtReg, indexReg, TYP_INT);
}
}
genProduceReg(arrOffset);
}
// make a temporary indir we can feed to pattern matching routines
// in cases where we don't want to instantiate all the indirs that happen
//
GenTreeIndir CodeGen::indirForm(var_types type, GenTree *base)
{
GenTreeIndir i(GT_IND, type, base, nullptr);
i.gtRegNum = REG_NA;
// has to be nonnull (because contained nodes can't be the last in block)
// but don't want it to be a valid pointer
i.gtNext = (GenTree *)(-1);
return i;
}
// make a temporary int we can feed to pattern matching routines
// in cases where we don't want to instantiate
//
GenTreeIntCon CodeGen::intForm(var_types type, ssize_t value)
{
GenTreeIntCon i(type, value);
i.gtRegNum = REG_NA;
// has to be nonnull (because contained nodes can't be the last in block)
// but don't want it to be a valid pointer
i.gtNext = (GenTree *)(-1);
return i;
}
instruction CodeGen::genGetInsForOper(genTreeOps oper, var_types type)
{
instruction ins;
// Operations on SIMD vectors shouldn't come this path
assert(!varTypeIsSIMD(type));
if (varTypeIsFloating(type))
{
return ins_MathOp(oper, type);
}
switch (oper)
{
case GT_ADD: ins = INS_add; break;
case GT_AND: ins = INS_and; break;
case GT_MUL: ins = INS_imul; break;
case GT_LSH: ins = INS_shl; break;
case GT_NEG: ins = INS_neg; break;
case GT_NOT: ins = INS_not; break;
case GT_OR: ins = INS_or; break;
case GT_RSH: ins = INS_sar; break;
case GT_RSZ: ins = INS_shr; break;
case GT_SUB: ins = INS_sub; break;
case GT_XOR: ins = INS_xor; break;
default: unreached();
break;
}
return ins;
}
/** Generates the code sequence for a GenTree node that
* represents a bit shift operation (<<, >>, >>>).
*
* Arguments: operand: the value to be shifted by shiftBy bits.
* shiftBy: the number of bits to shift the operand.
* parent: the actual bitshift node (that specifies the
* type of bitshift to perform.
*
* Preconditions: a) All GenTrees are register allocated.
* b) Either shiftBy is a contained constant or
* it's an expression sitting in RCX.
*/
void CodeGen::genCodeForShift(GenTreePtr operand, GenTreePtr shiftBy,
GenTreePtr parent)
{
var_types targetType = parent->TypeGet();
genTreeOps oper = parent->OperGet();
instruction ins = genGetInsForOper(oper, targetType);
GenTreePtr actualOperand = operand->gtSkipReloadOrCopy();
bool isRMW = parent->gtOp.gtOp1->isContained();
assert(parent->gtRegNum != REG_NA || isRMW);
regNumber operandReg = REG_NA;
regNumber indexReg = REG_NA;
int offset = 0;
emitAttr attr = EA_UNKNOWN;
bool isClsVarAddr = (operand->OperGet() == GT_CLS_VAR_ADDR);;
if (!isRMW)
{
genConsumeOperands(parent->AsOp());
operandReg = operand->gtRegNum;
}
else
{
targetType = parent->gtOp.gtOp1->TypeGet();
if (actualOperand->OperGet() == GT_LCL_VAR)
{
operandReg = operand->gtRegNum;
}
else if (actualOperand->OperGet() == GT_LEA)
{
operandReg = actualOperand->gtOp.gtOp1->gtRegNum;
GenTreeAddrMode* addrMode = actualOperand->AsAddrMode();
offset = addrMode->gtOffset;
if(addrMode->Index() != nullptr)
{
indexReg = addrMode->Index()->gtRegNum;
// GT_LEA with an indexReg is not supported for shift by immediate
assert(!shiftBy->isContainedIntOrIImmed());
}
}
else
{
// The only other supported operand for RMW is GT_CLS_VAR_ADDR
assert(actualOperand->OperGet() == GT_CLS_VAR_ADDR);
// We don't expect to see GT_COPY or GT_RELOAD for GT_CLS_VAR_ADDR
// so 'actualOperand' should be the same as 'operand'
assert(operand == actualOperand);
}
attr = EA_ATTR(genTypeSize(targetType));
}
if (shiftBy->isContainedIntOrIImmed())
{
int shiftByValue = (int)shiftBy->AsIntConCommon()->IconValue();
if (!isRMW)
{
// First, move the operand to the destination register and
// later on perform the shift in-place.
// (LSRA will try to avoid this situation through preferencing.)
if (parent->gtRegNum != operandReg)
{
inst_RV_RV(INS_mov, parent->gtRegNum, operandReg, targetType);
}
inst_RV_SH(ins, emitTypeSize(parent), parent->gtRegNum, shiftByValue);
}
else
{
if (isClsVarAddr && shiftByValue == 1)
{
switch (ins)
{
case INS_sar:
ins = INS_sar_1;
break;
case INS_shl:
ins = INS_shl_1;
break;
case INS_shr:
ins = INS_shr_1;
break;
}
getEmitter()->emitIns_C(ins, attr, operand->gtClsVar.gtClsVarHnd, 0);
}
else
{
switch (ins)
{
case INS_sar:
ins = INS_sar_N;
break;
case INS_shl:
ins = INS_shl_N;
break;
case INS_shr:
ins = INS_shr_N;
break;
}
if (isClsVarAddr)
{
getEmitter()->emitIns_C_I(ins, attr, operand->gtClsVar.gtClsVarHnd, 0, shiftByValue);
}
else
{
getEmitter()->emitIns_I_AR(ins, attr, shiftByValue, operandReg, offset);
}
}
}
}
else
{
// We must have the number of bits to shift
// stored in ECX, since we constrained this node to
// sit in ECX, in case this didn't happen, LSRA expects
// the code generator to move it since it's a single
// register destination requirement.
regNumber shiftReg = shiftBy->gtRegNum;
if (shiftReg != REG_RCX)
{
// Issue the mov to RCX:
inst_RV_RV(INS_mov, REG_RCX, shiftReg, shiftBy->TypeGet());
shiftReg = REG_RCX;
}
// The operand to be shifted must not be in ECX
noway_assert(operandReg != REG_RCX);
if (isRMW)
{
if (isClsVarAddr)
{
getEmitter()->emitIns_C_R(ins, attr, operand->gtClsVar.gtClsVarHnd, shiftReg, 0);
}
else
{
getEmitter()->emitIns_AR_R(ins, attr, indexReg, operandReg, offset);
}
}
else
{
if (parent->gtRegNum != operandReg)
{
inst_RV_RV(INS_mov, parent->gtRegNum, operandReg, targetType);
}
inst_RV_CL(ins, parent->gtRegNum, targetType);
}
}
genProduceReg(parent);
}
void CodeGen::genUnspillRegIfNeeded(GenTree *tree)
{
regNumber dstReg = tree->gtRegNum;
GenTree* unspillTree = tree;
if (tree->gtOper == GT_RELOAD)
{
unspillTree = tree->gtOp.gtOp1;
}
if (unspillTree->gtFlags & GTF_SPILLED)
{
if (genIsRegCandidateLocal(unspillTree))
{
// Reset spilled flag, since we are going to load a local variable from its home location.
unspillTree->gtFlags &= ~GTF_SPILLED;
GenTreeLclVarCommon* lcl = unspillTree->AsLclVarCommon();
LclVarDsc* varDsc = &compiler->lvaTable[lcl->gtLclNum];
// Load local variable from its home location.
// In most cases the tree type will indicate the correct type to use for the load.
// However, if it is NOT a normalizeOnLoad lclVar (i.e. NOT a small int that always gets
// widened when loaded into a register), and its size is not the same as genActualType of
// the type of the lclVar, then we need to change the type of the tree node when loading.
// This situation happens due to "optimizations" that avoid a cast and
// simply retype the node when using long type lclVar as an int.
// While loading the int in that case would work for this use of the lclVar, if it is
// later used as a long, we will have incorrectly truncated the long.
// In the normalizeOnLoad case ins_Load will return an appropriate sign- or zero-
// extending load.
var_types treeType = unspillTree->TypeGet();
if (treeType != genActualType(varDsc->lvType) &&
!varTypeIsGC(treeType) &&
!varDsc->lvNormalizeOnLoad())
{
assert(!varTypeIsGC(varDsc));
var_types spillType = genActualType(varDsc->lvType);
unspillTree->gtType = spillType;
inst_RV_TT(ins_Load(spillType, compiler->isSIMDTypeLocalAligned(lcl->gtLclNum)), dstReg, unspillTree);
unspillTree->gtType = treeType;
}
else
{
inst_RV_TT(ins_Load(treeType, compiler->isSIMDTypeLocalAligned(lcl->gtLclNum)), dstReg, unspillTree);
}
unspillTree->SetInReg();
// TODO-Review: We would like to call:
// genUpdateRegLife(varDsc, /*isBorn*/ true, /*isDying*/ false DEBUGARG(tree));
// instead of the following code, but this ends up hitting this assert:
// assert((regSet.rsMaskVars & regMask) == 0);
// due to issues with LSRA resolution moves.
// So, just force it for now. This probably indicates a condition that creates a GC hole!
//
// Extra note: I think we really want to call something like gcInfo.gcUpdateForRegVarMove,
// because the variable is not really going live or dead, but that method is somewhat poorly
// factored because it, in turn, updates rsMaskVars which is part of RegSet not GCInfo.
// TODO-Cleanup: This code exists in other CodeGen*.cpp files, and should be moved to CodeGenCommon.cpp.
// Don't update the variable's location if we are just re-spilling it again.
if ((unspillTree->gtFlags & GTF_SPILL) == 0)
{
genUpdateVarReg(varDsc, tree);
#ifdef DEBUG
if (VarSetOps::IsMember(compiler, gcInfo.gcVarPtrSetCur, varDsc->lvVarIndex))
{
JITDUMP("\t\t\t\t\t\t\tRemoving V%02u from gcVarPtrSetCur\n", lcl->gtLclNum);
}
#endif // DEBUG
VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varDsc->lvVarIndex);
#ifdef DEBUG
if (compiler->verbose)
{
printf("\t\t\t\t\t\t\tV%02u in reg ", lcl->gtLclNum);
varDsc->PrintVarReg();
printf(" is becoming live ");
compiler->printTreeID(unspillTree);
printf("\n");
}
#endif // DEBUG
regSet.rsMaskVars |= genGetRegMask(varDsc);
}
}
else
{
TempDsc* t = regSet.rsUnspillInPlace(unspillTree);
getEmitter()->emitIns_R_S(ins_Load(unspillTree->gtType),
emitActualTypeSize(unspillTree->gtType),
dstReg,
t->tdTempNum(),
0);
compiler->tmpRlsTemp(t);
unspillTree->gtFlags &= ~GTF_SPILLED;
unspillTree->SetInReg();
}
gcInfo.gcMarkRegPtrVal(dstReg, unspillTree->TypeGet());
}
}
// Do Liveness update for a subnodes that is being consumed by codegen
// including the logic for reload in case is needed and also takes care
// of locating the value on the desired register.
void CodeGen::genConsumeRegAndCopy(GenTree *tree, regNumber needReg)
{
if (needReg == REG_NA)
{
return;
}
regNumber treeReg = genConsumeReg(tree);
if (treeReg != needReg)
{
inst_RV_RV(INS_mov, needReg, treeReg, tree->TypeGet());
}
}
void CodeGen::genRegCopy(GenTree* treeNode)
{
assert(treeNode->OperGet() == GT_COPY);
var_types targetType = treeNode->TypeGet();
regNumber targetReg = treeNode->gtRegNum;
assert(targetReg != REG_NA);
GenTree* op1 = treeNode->gtOp.gtOp1;
// Check whether this node and the node from which we're copying the value have the same
// register type.
// This can happen if (currently iff) we have a SIMD vector type that fits in an integer
// register, in which case it is passed as an argument, or returned from a call,
// in an integer register and must be copied if it's in an xmm register.
if (varTypeIsFloating(treeNode) != varTypeIsFloating(op1))
{
instruction ins;
regNumber fpReg;
regNumber intReg;
if(varTypeIsFloating(treeNode))
{
ins = ins_CopyIntToFloat(op1->TypeGet(), treeNode->TypeGet());
fpReg = targetReg;
intReg = op1->gtRegNum;
}
else
{
ins = ins_CopyFloatToInt(op1->TypeGet(), treeNode->TypeGet());
intReg = targetReg;
fpReg = op1->gtRegNum;
}
inst_RV_RV(ins, fpReg, intReg, targetType);
}
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, genConsumeReg(op1), targetType);
}
if (op1->IsLocal())
{
// The lclVar will never be a def.
// If it is a last use, the lclVar will be killed by genConsumeReg(), as usual, and genProduceReg will
// appropriately set the gcInfo for the copied value.
// If not, there are two cases we need to handle:
// - If this is a TEMPORARY copy (indicated by the GTF_VAR_DEATH flag) the variable
// will remain live in its original register.
// genProduceReg() will appropriately set the gcInfo for the copied value,
// and genConsumeReg will reset it.
// - Otherwise, we need to update register info for the lclVar.
GenTreeLclVarCommon* lcl = op1->AsLclVarCommon();
assert((lcl->gtFlags & GTF_VAR_DEF) == 0);
if ((lcl->gtFlags & GTF_VAR_DEATH) == 0 && (treeNode->gtFlags & GTF_VAR_DEATH) == 0)
{
LclVarDsc* varDsc = &compiler->lvaTable[lcl->gtLclNum];
// If we didn't just spill it (in genConsumeReg, above), then update the register info
if (varDsc->lvRegNum != REG_STK)
{
// The old location is dying
genUpdateRegLife(varDsc, /*isBorn*/ false, /*isDying*/ true DEBUGARG(op1));
gcInfo.gcMarkRegSetNpt(genRegMask(op1->gtRegNum));
genUpdateVarReg(varDsc, treeNode);
// The new location is going live
genUpdateRegLife(varDsc, /*isBorn*/ true, /*isDying*/ false DEBUGARG(treeNode));
}
}
}
genProduceReg(treeNode);
}
// Check that registers are consumed in the right order for the current node being generated.
#ifdef DEBUG
void CodeGen::genCheckConsumeNode(GenTree* treeNode)
{
// GT_PUTARG_REG is consumed out of order.
if (treeNode->gtSeqNum != 0 && treeNode->OperGet() != GT_PUTARG_REG)
{
if (lastConsumedNode != nullptr)
{
if (treeNode == lastConsumedNode)
{
if (verbose)
{
printf("Node was consumed twice:\n ");
compiler->gtDispTree(treeNode, nullptr, nullptr, true);
}
}
else
{
if (verbose && (lastConsumedNode->gtSeqNum > treeNode->gtSeqNum))
{
printf("Nodes were consumed out-of-order:\n");
compiler->gtDispTree(lastConsumedNode, nullptr, nullptr, true);
compiler->gtDispTree(treeNode, nullptr, nullptr, true);
}
// assert(lastConsumedNode->gtSeqNum < treeNode->gtSeqNum);
}
}
lastConsumedNode = treeNode;
}
}
#endif // DEBUG
// Do liveness update for a subnode that is being consumed by codegen.
regNumber CodeGen::genConsumeReg(GenTree *tree)
{
if (tree->OperGet() == GT_COPY)
{
genRegCopy(tree);
}
// Handle the case where we have a lclVar that needs to be copied before use (i.e. because it
// interferes with one of the other sources (or the target, if it's a "delayed use" register)).
// TODO-Cleanup: This is a special copyReg case in LSRA - consider eliminating these and
// always using GT_COPY to make the lclVar location explicit.
// Note that we have to do this before calling genUpdateLife because otherwise if we spill it
// the lvRegNum will be set to REG_STK and we will lose track of what register currently holds
// the lclVar (normally when a lclVar is spilled it is then used from its former register
// location, which matches the gtRegNum on the node).
// (Note that it doesn't matter if we call this before or after genUnspillRegIfNeeded
// because if it's on the stack it will always get reloaded into tree->gtRegNum).
if (genIsRegCandidateLocal(tree))
{
GenTreeLclVarCommon *lcl = tree->AsLclVarCommon();
LclVarDsc* varDsc = &compiler->lvaTable[lcl->GetLclNum()];
if (varDsc->lvRegNum != REG_STK && varDsc->lvRegNum != tree->gtRegNum)
{
inst_RV_RV(INS_mov, tree->gtRegNum, varDsc->lvRegNum);
}
}
genUnspillRegIfNeeded(tree);
// genUpdateLife() will also spill local var if marked as GTF_SPILL by calling CodeGen::genSpillVar
genUpdateLife(tree);
assert(tree->gtRegNum != REG_NA);
// there are three cases where consuming a reg means clearing the bit in the live mask
// 1. it was not produced by a local
// 2. it was produced by a local that is going dead
// 3. it was produced by a local that does not live in that reg (like one allocated on the stack)
if (genIsRegCandidateLocal(tree))
{
GenTreeLclVarCommon *lcl = tree->AsLclVarCommon();
LclVarDsc* varDsc = &compiler->lvaTable[lcl->GetLclNum()];
assert(varDsc->lvLRACandidate);
if ((tree->gtFlags & GTF_VAR_DEATH) != 0)
{
gcInfo.gcMarkRegSetNpt(genRegMask(varDsc->lvRegNum));
}
else if (varDsc->lvRegNum == REG_STK)
{
// We have loaded this into a register only temporarily
gcInfo.gcMarkRegSetNpt(genRegMask(tree->gtRegNum));
}
}
else
{
gcInfo.gcMarkRegSetNpt(genRegMask(tree->gtRegNum));
}
genCheckConsumeNode(tree);
return tree->gtRegNum;
}
// Do liveness update for an address tree: one of GT_LEA, GT_LCL_VAR, or GT_CNS_INT (for call indirect).
void CodeGen::genConsumeAddress(GenTree* addr)
{
if (addr->OperGet() == GT_LEA)
{
genConsumeAddrMode(addr->AsAddrMode());
}
else if (!addr->isContained())
{
genConsumeReg(addr);
}
}
// do liveness update for a subnode that is being consumed by codegen
void CodeGen::genConsumeAddrMode(GenTreeAddrMode *addr)
{
genConsumeOperands(addr);
}
void CodeGen::genConsumeRegs(GenTree* tree)
{
#if !defined(_TARGET_64BIT_)
if (tree->OperGet() == GT_LONG)
{
genConsumeRegs(tree->gtGetOp1());
genConsumeRegs(tree->gtGetOp2());
return;
}
#endif // !defined(_TARGET_64BIT_)
if (tree->isContained())
{
if (tree->isIndir())
{
genConsumeAddress(tree->AsIndir()->Addr());
}
else if (tree->OperGet() == GT_AND)
{
// This is the special contained GT_AND that we created in Lowering::LowerCmp()
// Now we need to consume the operands of the GT_AND node.
genConsumeOperands(tree->AsOp());
}
else
{
assert(tree->OperIsLeaf());
}
}
else
{
genConsumeReg(tree);
}
}
//------------------------------------------------------------------------
// genConsumeOperands: Do liveness update for the operands of a unary or binary tree
//
// Arguments:
// tree - the GenTreeOp whose operands will have their liveness updated.
//
// Return Value:
// None.
//
// Notes:
// Note that this logic is localized here because we must do the liveness update in
// the correct execution order. This is important because we may have two operands
// that involve the same lclVar, and if one is marked "lastUse" we must handle it
// after the first.
void CodeGen::genConsumeOperands(GenTreeOp* tree)
{
GenTree* firstOp = tree->gtOp1;
GenTree* secondOp = tree->gtOp2;
if ((tree->gtFlags & GTF_REVERSE_OPS) != 0)
{
assert(secondOp != nullptr);
firstOp = secondOp;
secondOp = tree->gtOp1;
}
if (firstOp != nullptr)
{
genConsumeRegs(firstOp);
}
if (secondOp != nullptr)
{
genConsumeRegs(secondOp);
}
}
void CodeGen::genConsumeBlockOp(GenTreeBlkOp* blkNode, regNumber dstReg, regNumber srcReg, regNumber sizeReg)
{
// We have to consume the registers, and perform any copies, in the actual execution order.
// The nominal order is: dst, src, size. However this may have been changed
// with reverse flags on either the GT_LIST or the GT_INITVAL itself.
GenTree* dst = blkNode->Dest();
GenTree* src = blkNode->gtOp.gtOp1->gtOp.gtOp2;
GenTree* size = blkNode->gtOp.gtOp2;
if (!blkNode->IsReverseOp() && !blkNode->gtOp1->IsReverseOp())
{
genConsumeRegAndCopy(dst, dstReg);
genConsumeRegAndCopy(src, srcReg);
genConsumeRegAndCopy(size, sizeReg);
}
else if (!blkNode->IsReverseOp())
{
// We know that the GT_LIST must be reversed.
genConsumeRegAndCopy(src, srcReg);
genConsumeRegAndCopy(dst, dstReg);
genConsumeRegAndCopy(size, sizeReg);
}
else if (!blkNode->gtOp1->IsReverseOp())
{
// We know from above that the initBlkNode must be reversed.
genConsumeRegAndCopy(size, sizeReg);
genConsumeRegAndCopy(dst, dstReg);
genConsumeRegAndCopy(src, srcReg);
}
else
{
// They are BOTH reversed.
genConsumeRegAndCopy(size, sizeReg);
genConsumeRegAndCopy(src, srcReg);
genConsumeRegAndCopy(dst, dstReg);
}
}
// do liveness update for register produced by the current node in codegen
void CodeGen::genProduceReg(GenTree *tree)
{
if (tree->gtFlags & GTF_SPILL)
{
if (genIsRegCandidateLocal(tree))
{
// Store local variable to its home location.
tree->gtFlags &= ~GTF_REG_VAL;
// Ensure that lclVar stores are typed correctly.
unsigned varNum = tree->gtLclVarCommon.gtLclNum;
assert(!compiler->lvaTable[varNum].lvNormalizeOnStore() || (tree->TypeGet() == genActualType(compiler->lvaTable[varNum].TypeGet())));
inst_TT_RV(ins_Store(tree->gtType, compiler->isSIMDTypeLocalAligned(varNum)), tree, tree->gtRegNum);
}
else
{
tree->SetInReg();
regSet.rsSpillTree(tree->gtRegNum, tree);
tree->gtFlags |= GTF_SPILLED;
tree->gtFlags &= ~GTF_SPILL;
gcInfo.gcMarkRegSetNpt(genRegMask(tree->gtRegNum));
return;
}
}
genUpdateLife(tree);
// If we've produced a register, mark it as a pointer, as needed.
if (tree->gtHasReg())
{
// We only mark the register in the following cases:
// 1. It is not a register candidate local. In this case, we're producing a
// register from a local, but the local is not a register candidate. Thus,
// we must be loading it as a temp register, and any "last use" flag on
// the register wouldn't be relevant.
// 2. The register candidate local is going dead. There's no point to mark
// the register as live, with a GC pointer, if the variable is dead.
if (!genIsRegCandidateLocal(tree) ||
((tree->gtFlags & GTF_VAR_DEATH) == 0))
{
gcInfo.gcMarkRegPtrVal(tree->gtRegNum, tree->TypeGet());
}
}
tree->SetInReg();
}
// transfer gc/byref status of src reg to dst reg
void CodeGen::genTransferRegGCState(regNumber dst, regNumber src)
{
regMaskTP srcMask = genRegMask(src);
regMaskTP dstMask = genRegMask(dst);
if (gcInfo.gcRegGCrefSetCur & srcMask)
{
gcInfo.gcMarkRegSetGCref(dstMask);
}
else if (gcInfo.gcRegByrefSetCur & srcMask)
{
gcInfo.gcMarkRegSetByref(dstMask);
}
else
{
gcInfo.gcMarkRegSetNpt(dstMask);
}
}
// generates an ip-relative call or indirect call via reg ('call reg')
// pass in 'addr' for a relative call or 'base' for a indirect register call
// methHnd - optional, only used for pretty printing
// retSize - emitter type of return for GC purposes, should be EA_BYREF, EA_GCREF, or EA_PTRSIZE(not GC)
void CodeGen::genEmitCall(int callType,
CORINFO_METHOD_HANDLE methHnd,
INDEBUG_LDISASM_COMMA(CORINFO_SIG_INFO* sigInfo)
void* addr
X86_ARG(ssize_t argSize),
emitAttr retSize,
IL_OFFSETX ilOffset,
regNumber base,
bool isJump,
bool isNoGC)
{
#ifndef _TARGET_X86_
ssize_t argSize = 0;
#endif // !_TARGET_X86_
getEmitter()->emitIns_Call(emitter::EmitCallType(callType),
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
addr,
argSize,
retSize,
gcInfo.gcVarPtrSetCur,
gcInfo.gcRegGCrefSetCur,
gcInfo.gcRegByrefSetCur,
ilOffset,
base, REG_NA, 0, 0,
isJump,
emitter::emitNoGChelper(compiler->eeGetHelperNum(methHnd)));
}
// generates an indirect call via addressing mode (call []) given an indir node
// methHnd - optional, only used for pretty printing
// retSize - emitter type of return for GC purposes, should be EA_BYREF, EA_GCREF, or EA_PTRSIZE(not GC)
void CodeGen::genEmitCall(int callType,
CORINFO_METHOD_HANDLE methHnd,
INDEBUG_LDISASM_COMMA(CORINFO_SIG_INFO* sigInfo)
GenTreeIndir* indir
X86_ARG(ssize_t argSize),
emitAttr retSize,
IL_OFFSETX ilOffset)
{
#ifndef _TARGET_X86_
ssize_t argSize = 0;
#endif // !_TARGET_X86_
genConsumeAddress(indir->Addr());
getEmitter()->emitIns_Call(emitter::EmitCallType(callType),
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
nullptr,
argSize,
retSize,
gcInfo.gcVarPtrSetCur,
gcInfo.gcRegGCrefSetCur,
gcInfo.gcRegByrefSetCur,
ilOffset,
indir->Base() ? indir->Base()->gtRegNum : REG_NA,
indir->Index() ? indir->Index()->gtRegNum : REG_NA,
indir->Scale(),
indir->Offset());
}
// Produce code for a GT_CALL node
void CodeGen::genCallInstruction(GenTreePtr node)
{
GenTreeCall *call = node->AsCall();
assert(call->gtOper == GT_CALL);
gtCallTypes callType = (gtCallTypes)call->gtCallType;
IL_OFFSETX ilOffset = BAD_IL_OFFSET;
// all virtuals should have been expanded into a control expression
assert (!call->IsVirtual() || call->gtControlExpr || call->gtCallAddr);
// Consume all the arg regs
for (GenTreePtr list = call->gtCallLateArgs; list; list = list->MoveNext())
{
assert(list->IsList());
GenTreePtr argNode = list->Current();
fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(call, argNode->gtSkipReloadOrCopy());
assert(curArgTabEntry);
if (curArgTabEntry->regNum == REG_STK)
continue;
regNumber argReg = curArgTabEntry->regNum;
genConsumeReg(argNode);
if (argNode->gtRegNum != argReg)
{
inst_RV_RV(ins_Move_Extend(argNode->TypeGet(), argNode->InReg()), argReg, argNode->gtRegNum);
}
// In the case of a varargs call,
// the ABI dictates that if we have floating point args,
// we must pass the enregistered arguments in both the
// integer and floating point registers so, let's do that.
if (call->IsVarargs() && varTypeIsFloating(argNode))
{
regNumber targetReg = compiler->getCallArgIntRegister(argNode->gtRegNum);
instruction ins = ins_CopyFloatToInt(argNode->TypeGet(), TYP_LONG);
inst_RV_RV(ins, argNode->gtRegNum, targetReg);
}
}
#ifdef _TARGET_X86_
// The call will pop its arguments.
// for each putarg_stk:
ssize_t stackArgBytes = 0;
GenTreePtr args = call->gtCallArgs;
while (args)
{
GenTreePtr arg = args->gtOp.gtOp1;
if (arg->OperGet() != GT_ARGPLACE && !(arg->gtFlags & GTF_LATE_ARG))
{
assert((arg->OperGet() == GT_PUTARG_STK) || (arg->OperGet() == GT_LONG));
if (arg->OperGet() == GT_LONG)
{
assert((arg->gtGetOp1()->OperGet() == GT_PUTARG_STK) && (arg->gtGetOp2()->OperGet() == GT_PUTARG_STK));
}
stackArgBytes += genTypeSize(genActualType(arg->TypeGet()));
}
args = args->gtOp.gtOp2;
}
#endif // _TARGET_X86_
// Insert a null check on "this" pointer if asked.
if (call->NeedsNullCheck())
{
const regNumber regThis = genGetThisArgReg(call);
getEmitter()->emitIns_AR_R(INS_cmp, EA_4BYTE, regThis, regThis, 0);
}
// Either gtControlExpr != null or gtCallAddr != null or it is a direct non-virtual call to a user or helper method.
CORINFO_METHOD_HANDLE methHnd;
GenTree* target = call->gtControlExpr;
if (callType == CT_INDIRECT)
{
assert(target == nullptr);
target = call->gtCall.gtCallAddr;
methHnd = nullptr;
}
else
{
methHnd = call->gtCallMethHnd;
}
CORINFO_SIG_INFO* sigInfo = nullptr;
#ifdef DEBUG
// Pass the call signature information down into the emitter so the emitter can associate
// native call sites with the signatures they were generated from.
if (callType != CT_HELPER)
{
sigInfo = call->callSig;
}
#endif // DEBUG
// If fast tail call, then we are done. In this case we setup the args (both reg args
// and stack args in incoming arg area) and call target in rax. Epilog sequence would
// generate "jmp rax".
if (call->IsFastTailCall())
{
// Don't support fast tail calling JIT helpers
assert(callType != CT_HELPER);
// Fast tail calls materialize call target either in gtControlExpr or in gtCallAddr.
assert(target != nullptr);
genConsumeReg(target);
if (target->gtRegNum != REG_RAX)
{
inst_RV_RV(INS_mov, REG_RAX, target->gtRegNum);
}
return ;
}
// For a pinvoke to unmanged code we emit a label to clear
// the GC pointer state before the callsite.
// We can't utilize the typical lazy killing of GC pointers
// at (or inside) the callsite.
if (call->IsUnmanaged())
{
genDefineTempLabel(genCreateTempLabel());
}
// Determine return value size.
emitAttr retSize = EA_PTRSIZE;
if (call->gtType == TYP_REF ||
call->gtType == TYP_ARRAY)
{
retSize = EA_GCREF;
}
else if (call->gtType == TYP_BYREF)
{
retSize = EA_BYREF;
}
#ifdef DEBUGGING_SUPPORT
// We need to propagate the IL offset information to the call instruction, so we can emit
// an IL to native mapping record for the call, to support managed return value debugging.
// We don't want tail call helper calls that were converted from normal calls to get a record,
// so we skip this hash table lookup logic in that case.
if (compiler->opts.compDbgInfo && compiler->genCallSite2ILOffsetMap != nullptr && !call->IsTailCall())
{
(void)compiler->genCallSite2ILOffsetMap->Lookup(call, &ilOffset);
}
#endif // DEBUGGING_SUPPORT
if (target != nullptr)
{
if (target->isContainedIndir())
{
if (target->AsIndir()->HasBase() && target->AsIndir()->Base()->isContainedIntOrIImmed())
{
// Note that if gtControlExpr is an indir of an absolute address, we mark it as
// contained only if it can be encoded as PC-relative offset.
assert(genAddrShouldUsePCRel(target->AsIndir()->Base()->AsIntConCommon()->IconValue()));
genEmitCall(emitter::EC_FUNC_TOKEN_INDIR,
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
(void*) target->AsIndir()->Base()->AsIntConCommon()->IconValue(),
#ifdef _TARGET_X86_
stackArgBytes,
#endif // _TARGET_X86_
retSize,
ilOffset);
}
else
{
GenTree* addr = target->gtGetOp1();
genConsumeAddress(addr);
genEmitCall(emitter::EC_INDIR_ARD,
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
target->AsIndir(),
#ifdef _TARGET_X86_
stackArgBytes,
#endif // _TARGET_X86_
retSize,
ilOffset);
}
}
else
{
// We have already generated code for gtControlExpr evaluating it into a register.
// We just need to emit "call reg" in this case.
assert(genIsValidIntReg(target->gtRegNum));
genEmitCall(emitter::EC_INDIR_R,
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
nullptr, //addr
#ifdef _TARGET_X86_
stackArgBytes,
#endif // _TARGET_X86_
retSize,
ilOffset,
genConsumeReg(target));
}
}
#if defined(_TARGET_AMD64_) && defined(FEATURE_READYTORUN_COMPILER)
else if (call->gtEntryPoint.addr != nullptr)
{
genEmitCall(emitter::EC_FUNC_TOKEN_INDIR,
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
(void*) call->gtEntryPoint.addr,
retSize,
ilOffset);
}
#endif
else
{
// Generate a direct call to a non-virtual user defined or helper method
assert(callType == CT_HELPER || callType == CT_USER_FUNC);
void *addr = nullptr;
if (callType == CT_HELPER)
{
// Direct call to a helper method.
CorInfoHelpFunc helperNum = compiler->eeGetHelperNum(methHnd);
noway_assert(helperNum != CORINFO_HELP_UNDEF);
void *pAddr = nullptr;
addr = compiler->compGetHelperFtn(helperNum, (void **)&pAddr);
if (addr == nullptr)
{
addr = pAddr;
}
}
else
{
// Direct call to a non-virtual user function.
CORINFO_ACCESS_FLAGS aflags = CORINFO_ACCESS_ANY;
if (call->IsSameThis())
{
aflags = (CORINFO_ACCESS_FLAGS)(aflags | CORINFO_ACCESS_THIS);
}
if ((call->NeedsNullCheck()) == 0)
{
aflags = (CORINFO_ACCESS_FLAGS)(aflags | CORINFO_ACCESS_NONNULL);
}
CORINFO_CONST_LOOKUP addrInfo;
compiler->info.compCompHnd->getFunctionEntryPoint(methHnd, &addrInfo, aflags);
addr = addrInfo.addr;
}
// Non-virtual direct calls to known addresses
genEmitCall(emitter::EC_FUNC_TOKEN,
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
addr,
#ifdef _TARGET_X86_
stackArgBytes,
#endif // _TARGET_X86_
retSize,
ilOffset);
}
// if it was a pinvoke we may have needed to get the address of a label
if (genPendingCallLabel)
{
assert(call->IsUnmanaged());
genDefineTempLabel(genPendingCallLabel);
genPendingCallLabel = nullptr;
}
#ifdef _TARGET_X86_
// The call will pop its arguments.
genStackLevel -= stackArgBytes;
#endif // _TARGET_X86_
// Update GC info:
// All Callee arg registers are trashed and no longer contain any GC pointers.
// TODO-XArch-Bug?: As a matter of fact shouldn't we be killing all of callee trashed regs here?
// For now we will assert that other than arg regs gc ref/byref set doesn't contain any other
// registers from RBM_CALLEE_TRASH.
assert((gcInfo.gcRegGCrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0);
assert((gcInfo.gcRegByrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0);
gcInfo.gcRegGCrefSetCur &= ~RBM_ARG_REGS;
gcInfo.gcRegByrefSetCur &= ~RBM_ARG_REGS;
var_types returnType = call->TypeGet();
if (returnType != TYP_VOID)
{
#ifdef _TARGET_X86_
if (varTypeIsFloating(returnType))
{
// Spill the value from the fp stack.
// Then, load it into the target register.
call->gtFlags |= GTF_SPILL;
regSet.rsSpillFPStack(call);
call->gtFlags |= GTF_SPILLED;
call->gtFlags &= ~GTF_SPILL;
genUnspillRegIfNeeded(call);
}
else
#endif // _TARGET_X86_
{
regNumber returnReg = (varTypeIsFloating(returnType) ? REG_FLOATRET : REG_INTRET);
if (call->gtRegNum != returnReg)
{
inst_RV_RV(ins_Copy(returnType), call->gtRegNum, returnReg, returnType);
}
genProduceReg(call);
}
}
// If there is nothing next, that means the result is thrown away, so this value is not live.
// However, for minopts or debuggable code, we keep it live to support managed return value debugging.
if ((call->gtNext == nullptr) && !compiler->opts.MinOpts() && !compiler->opts.compDbgCode)
{
gcInfo.gcMarkRegSetNpt(RBM_INTRET);
}
}
// Produce code for a GT_JMP node.
// The arguments of the caller needs to be transferred to the callee before exiting caller.
// The actual jump to callee is generated as part of caller epilog sequence.
// Therefore the codegen of GT_JMP is to ensure that the callee arguments are correctly setup.
void CodeGen::genJmpMethod(GenTreePtr jmp)
{
assert(jmp->OperGet() == GT_JMP);
assert(compiler->compJmpOpUsed);
// If no arguments, nothing to do
if (compiler->info.compArgsCount == 0)
{
return;
}
// Make sure register arguments are in their initial registers
// and stack arguments are put back as well.
unsigned varNum;
LclVarDsc* varDsc;
// First move any en-registered stack arguments back to the stack.
// At the same time any reg arg not in correct reg is moved back to its stack location.
//
// We are not strictly required to spill reg args that are not in the desired reg for a jmp call
// But that would require us to deal with circularity while moving values around. Spilling
// to stack makes the implementation simple, which is not a bad trade off given Jmp calls
// are not frequent.
for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++)
{
varDsc = compiler->lvaTable + varNum;
if (varDsc->lvPromoted)
{
noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here
unsigned fieldVarNum = varDsc->lvFieldLclStart;
varDsc = compiler->lvaTable + fieldVarNum;
}
noway_assert(varDsc->lvIsParam);
if (varDsc->lvIsRegArg && (varDsc->lvRegNum != REG_STK))
{
// Skip reg args which are already in its right register for jmp call.
// If not, we will spill such args to their stack locations.
//
// If we need to generate a tail call profiler hook, then spill all
// arg regs to free them up for the callback.
if (!compiler->compIsProfilerHookNeeded() && (varDsc->lvRegNum == varDsc->lvArgReg))
continue;
}
else if (varDsc->lvRegNum == REG_STK)
{
// Skip args which are currently living in stack.
continue;
}
// If we came here it means either a reg argument not in the right register or
// a stack argument currently living in a register. In either case the following
// assert should hold.
assert(varDsc->lvRegNum != REG_STK);
var_types loadType = varDsc->lvaArgType();
getEmitter()->emitIns_S_R(ins_Store(loadType), emitTypeSize(loadType), varDsc->lvRegNum, varNum, 0);
// Update lvRegNum life and GC info to indicate lvRegNum is dead and varDsc stack slot is going live.
// Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it.
// Therefore manually update life of varDsc->lvRegNum.
regMaskTP tempMask = genRegMask(varDsc->lvRegNum);
regSet.rsMaskVars &= ~tempMask;
gcInfo.gcMarkRegSetNpt(tempMask);
if (varDsc->lvTracked)
{
VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
}
#ifdef PROFILING_SUPPORTED
// At this point all arg regs are free.
// Emit tail call profiler callback.
genProfilingLeaveCallback(CORINFO_HELP_PROF_FCN_TAILCALL);
#endif
// Next move any un-enregistered register arguments back to their register.
regMaskTP fixedIntArgMask = RBM_NONE; // tracks the int arg regs occupying fixed args in case of a vararg method.
unsigned firstArgVarNum = BAD_VAR_NUM; // varNum of the first argument in case of a vararg method.
for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++)
{
varDsc = compiler->lvaTable + varNum;
if (varDsc->lvPromoted)
{
noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here
unsigned fieldVarNum = varDsc->lvFieldLclStart;
varDsc = compiler->lvaTable + fieldVarNum;
}
noway_assert(varDsc->lvIsParam);
// Skip if arg not passed in a register.
if (!varDsc->lvIsRegArg)
continue;
// Register argument
noway_assert(isRegParamType(genActualType(varDsc->TypeGet())));
// Is register argument already in the right register?
// If not load it from its stack location.
var_types loadType = varDsc->lvaArgType();
regNumber argReg = varDsc->lvArgReg; // incoming arg register
if (varDsc->lvRegNum != argReg)
{
assert(genIsValidReg(argReg));
getEmitter()->emitIns_R_S(ins_Load(loadType), emitTypeSize(loadType), argReg, varNum, 0);
// Update argReg life and GC Info to indicate varDsc stack slot is dead and argReg is going live.
// Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it.
// Therefore manually update life of argReg. Note that GT_JMP marks the end of the basic block
// and after which reg life and gc info will be recomputed for the new block in genCodeForBBList().
regSet.rsMaskVars |= genRegMask(argReg);
gcInfo.gcMarkRegPtrVal(argReg, loadType);
if (varDsc->lvTracked)
{
VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
}
// In case of a jmp call to a vararg method also pass the float/double arg in the corresponding int arg register.
if (compiler->info.compIsVarArgs)
{
regNumber intArgReg;
if (varTypeIsFloating(loadType))
{
intArgReg = compiler->getCallArgIntRegister(argReg);
instruction ins = ins_CopyFloatToInt(loadType, TYP_LONG);
inst_RV_RV(ins, argReg, intArgReg, loadType);
}
else
{
intArgReg = argReg;
}
fixedIntArgMask |= genRegMask(intArgReg);
if (intArgReg == REG_ARG_0)
{
assert(firstArgVarNum == BAD_VAR_NUM);
firstArgVarNum = varNum;
}
}
}
// Jmp call to a vararg method - if the method has fewer than 4 fixed arguments,
// load the remaining arg registers (both int and float) from the corresponding
// shadow stack slots. This is for the reason that we don't know the number and type
// of non-fixed params passed by the caller, therefore we have to assume the worst case
// of caller passing float/double args both in int and float arg regs.
//
// The caller could have passed gc-ref/byref type var args. Since these are var args
// the callee no way of knowing their gc-ness. Therefore, mark the region that loads
// remaining arg registers from shadow stack slots as non-gc interruptible.
if (fixedIntArgMask != RBM_NONE)
{
assert(compiler->info.compIsVarArgs);
assert(firstArgVarNum != BAD_VAR_NUM);
regMaskTP remainingIntArgMask = RBM_ARG_REGS & ~fixedIntArgMask;
if (remainingIntArgMask != RBM_NONE)
{
instruction insCopyIntToFloat = ins_CopyIntToFloat(TYP_LONG, TYP_DOUBLE);
getEmitter()->emitDisableGC();
for (int argNum = 0, argOffset=0; argNum < MAX_REG_ARG; ++argNum)
{
regNumber argReg = intArgRegs[argNum];
regMaskTP argRegMask = genRegMask(argReg);
if ((remainingIntArgMask & argRegMask) != 0)
{
remainingIntArgMask &= ~argRegMask;
getEmitter()->emitIns_R_S(INS_mov, EA_8BYTE, argReg, firstArgVarNum, argOffset);
// also load it in corresponding float arg reg
regNumber floatReg = compiler->getCallArgFloatRegister(argReg);
inst_RV_RV(insCopyIntToFloat, floatReg, argReg);
}
argOffset += REGSIZE_BYTES;
}
getEmitter()->emitEnableGC();
}
}
}
// produce code for a GT_LEA subnode
void CodeGen::genLeaInstruction(GenTreeAddrMode *lea)
{
emitAttr size = emitTypeSize(lea);
genConsumeOperands(lea);
if (lea->Base() && lea->Index())
{
regNumber baseReg = lea->Base()->gtRegNum;
regNumber indexReg = lea->Index()->gtRegNum;
getEmitter()->emitIns_R_ARX (INS_lea, size, lea->gtRegNum, baseReg, indexReg, lea->gtScale, lea->gtOffset);
}
else if (lea->Base())
{
getEmitter()->emitIns_R_AR (INS_lea, size, lea->gtRegNum, lea->Base()->gtRegNum, lea->gtOffset);
}
else if (lea->Index())
{
getEmitter()->emitIns_R_ARX (INS_lea, size, lea->gtRegNum, REG_NA, lea->Index()->gtRegNum, lea->gtScale, lea->gtOffset);
}
genProduceReg(lea);
}
/*****************************************************************************
* The condition to use for (the jmp/set for) the given type of compare operation are
* returned in 'jmpKind' array. The corresponding elements of jmpToTrueLabel indicate
* the branch target when the condition being true.
*
* jmpToTrueLabel[i]= true implies branch to the target when the compare operation is true.
* jmpToTrueLabel[i]= false implies branch to the target when the compare operation is false.
*/
// static
void CodeGen::genJumpKindsForTree(GenTreePtr cmpTree,
emitJumpKind jmpKind[2],
bool jmpToTrueLabel[2])
{
// Except for BEQ (= ordered GT_EQ) both jumps are to the true label.
jmpToTrueLabel[0] = true;
jmpToTrueLabel[1] = true;
// For integer comparisons just use genJumpKindForOper
if (!varTypeIsFloating(cmpTree->gtOp.gtOp1->gtEffectiveVal()))
{
jmpKind[0] = genJumpKindForOper(cmpTree->gtOper, (cmpTree->gtFlags & GTF_UNSIGNED) != 0);
jmpKind[1] = EJ_NONE;
}
else
{
assert(cmpTree->OperIsCompare());
// For details on how we arrived at this mapping, see the comment block in genCodeForTreeNode()
// while generating code for compare opererators (e.g. GT_EQ etc).
if ((cmpTree->gtFlags & GTF_RELOP_NAN_UN) != 0)
{
// Unordered
switch (cmpTree->gtOper)
{
case GT_LT:
case GT_GT:
jmpKind[0] = EJ_jb;
jmpKind[1] = EJ_NONE;
break;
case GT_LE:
case GT_GE:
jmpKind[0] = EJ_jbe;
jmpKind[1] = EJ_NONE;
break;
case GT_NE:
jmpKind[0] = EJ_jpe;
jmpKind[1] = EJ_jne;
break;
case GT_EQ:
jmpKind[0] = EJ_je;
jmpKind[1] = EJ_NONE;
break;
default:
unreached();
}
}
else
{
switch (cmpTree->gtOper)
{
case GT_LT:
case GT_GT:
jmpKind[0] = EJ_ja;
jmpKind[1] = EJ_NONE;
break;
case GT_LE:
case GT_GE:
jmpKind[0] = EJ_jae;
jmpKind[1] = EJ_NONE;
break;
case GT_NE:
jmpKind[0] = EJ_jne;
jmpKind[1] = EJ_NONE;
break;
case GT_EQ:
jmpKind[0] = EJ_jpe;
jmpKind[1] = EJ_je;
jmpToTrueLabel[0] = false;
break;
default:
unreached();
}
}
}
}
// Generate code to materialize a condition into a register
// (the condition codes must already have been appropriately set)
void CodeGen::genSetRegToCond(regNumber dstReg, GenTreePtr tree)
{
noway_assert((genRegMask(dstReg) & RBM_BYTE_REGS) != 0);
emitJumpKind jumpKind[2];
bool branchToTrueLabel[2];
genJumpKindsForTree(tree, jumpKind, branchToTrueLabel);
if (jumpKind[1] == EJ_NONE)
{
// Set (lower byte of) reg according to the flags
inst_SET(jumpKind[0], dstReg);
}
else
{
// jmpKind[1] != EJ_NONE implies BEQ and BEN.UN of floating point values.
// These are represented by two conditions.
#ifdef DEBUG
if (tree->gtOper == GT_EQ)
{
// This must be an ordered comparison.
assert((tree->gtFlags & GTF_RELOP_NAN_UN) == 0);
}
else
{
// This must be BNE.UN
assert((tree->gtOper == GT_NE) && ((tree->gtFlags & GTF_RELOP_NAN_UN) != 0));
}
#endif
// Here is the sample code generated in each case:
// BEQ == cmp, jpe <false label>, je <true label>
// That is, to materialize comparison reg needs to be set if PF=0 and ZF=1
// setnp reg // if (PF==0) reg = 1 else reg = 0
// jpe L1 // Jmp if PF==1
// sete reg
// L1:
//
// BNE.UN == cmp, jpe <true label>, jne <true label>
// That is, to materialize the comparison reg needs to be set if either PF=1 or ZF=0;
// setp reg
// jpe L1
// setne reg
// L1:
// reverse the jmpkind condition before setting dstReg if it is to false label.
inst_SET(branchToTrueLabel[0] ? jumpKind[0] : emitter::emitReverseJumpKind(jumpKind[0]), dstReg);
BasicBlock* label = genCreateTempLabel();
inst_JMP(jumpKind[0], label);
// second branch is always to true label
assert(branchToTrueLabel[1]);
inst_SET(jumpKind[1], dstReg);
genDefineTempLabel(label);
}
var_types treeType = tree->TypeGet();
if (treeType == TYP_INT || treeType == TYP_LONG)
{
// Set the higher bytes to 0
inst_RV_RV(ins_Move_Extend(TYP_UBYTE, true), dstReg, dstReg, TYP_UBYTE, emitTypeSize(TYP_UBYTE));
}
else
{
// FP types have been converted to flow
noway_assert(treeType == TYP_BYTE);
}
}
//------------------------------------------------------------------------
// genIntToIntCast: Generate code for an integer cast
// This method handles integer overflow checking casts
// as well as ordinary integer casts.
//
// Arguments:
// treeNode - The GT_CAST node
//
// Return Value:
// None.
//
// Assumptions:
// The treeNode is not a contained node and must have an assigned register.
// For a signed convert from byte, the source must be in a byte-addressable register.
// Neither the source nor target type can be a floating point type.
//
// TODO-XArch-CQ: Allow castOp to be a contained node without an assigned register.
//
void CodeGen::genIntToIntCast(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_CAST);
GenTreePtr castOp = treeNode->gtCast.CastOp();
regNumber targetReg = treeNode->gtRegNum;
regNumber sourceReg = castOp->gtRegNum;
var_types dstType = treeNode->CastToType();
bool isUnsignedDst = varTypeIsUnsigned(dstType);
var_types srcType = genActualType(castOp->TypeGet());
bool isUnsignedSrc = varTypeIsUnsigned(srcType);
// if necessary, force the srcType to unsigned when the GT_UNSIGNED flag is set
if (!isUnsignedSrc && (treeNode->gtFlags & GTF_UNSIGNED) != 0)
{
srcType = genUnsignedType(srcType);
isUnsignedSrc = true;
}
bool requiresOverflowCheck = false;
bool needAndAfter = false;
assert(genIsValidIntReg(targetReg));
assert(genIsValidIntReg(sourceReg));
instruction ins = INS_invalid;
emitAttr size = EA_UNKNOWN;
if (genTypeSize(srcType) < genTypeSize(dstType))
{
// Widening cast
// Is this an Overflow checking cast?
// We only need to handle one case, as the other casts can never overflow.
// cast from TYP_INT to TYP_ULONG
//
if (treeNode->gtOverflow() && (srcType == TYP_INT) && (dstType == TYP_ULONG))
{
requiresOverflowCheck = true;
size = EA_ATTR(genTypeSize(srcType));
ins = INS_mov;
}
else
{
// we need the source size
size = EA_ATTR(genTypeSize(srcType));
noway_assert(size < EA_PTRSIZE);
ins = ins_Move_Extend(srcType, castOp->InReg());
/*
Special case: ins_Move_Extend assumes the destination type is no bigger
than TYP_INT. movsx and movzx can already extend all the way to
64-bit, and a regular 32-bit mov clears the high 32 bits (like the non-existant movzxd),
but for a sign extension from TYP_INT to TYP_LONG, we need to use movsxd opcode.
*/
if (!isUnsignedSrc && !isUnsignedDst && (size == EA_4BYTE) && (genTypeSize(dstType) > EA_4BYTE))
{
#ifdef _TARGET_X86_
NYI_X86("Cast to 64 bit for x86/RyuJIT");
#else // !_TARGET_X86_
ins = INS_movsxd;
#endif // !_TARGET_X86_
}
/*
Special case: for a cast of byte to char we first
have to expand the byte (w/ sign extension), then
mask off the high bits.
Use 'movsx' followed by 'and'
*/
if (!isUnsignedSrc && isUnsignedDst && (genTypeSize(dstType) < EA_4BYTE))
{
noway_assert(genTypeSize(dstType) == EA_2BYTE && size == EA_1BYTE);
needAndAfter = true;
}
}
}
else
{
// Narrowing cast, or sign-changing cast
noway_assert(genTypeSize(srcType) >= genTypeSize(dstType));
// Is this an Overflow checking cast?
if (treeNode->gtOverflow())
{
requiresOverflowCheck = true;
size = EA_ATTR(genTypeSize(srcType));
ins = INS_mov;
}
else
{
size = EA_ATTR(genTypeSize(dstType));
ins = ins_Move_Extend(dstType, castOp->InReg());
}
}
noway_assert(ins != INS_invalid);
genConsumeReg(castOp);
if (requiresOverflowCheck)
{
ssize_t typeMin = 0;
ssize_t typeMax = 0;
ssize_t typeMask = 0;
bool needScratchReg = false;
bool signCheckOnly = false;
/* Do we need to compare the value, or just check masks */
switch (dstType)
{
case TYP_BYTE:
typeMask = ssize_t((int)0xFFFFFF80);
typeMin = SCHAR_MIN;
typeMax = SCHAR_MAX;
break;
case TYP_UBYTE:
typeMask = ssize_t((int)0xFFFFFF00L);
break;
case TYP_SHORT:
typeMask = ssize_t((int)0xFFFF8000);
typeMin = SHRT_MIN;
typeMax = SHRT_MAX;
break;
case TYP_CHAR:
typeMask = ssize_t((int)0xFFFF0000L);
break;
case TYP_INT:
if (srcType == TYP_UINT)
{
signCheckOnly = true;
}
else
{
typeMask = 0xFFFFFFFF80000000LL;
typeMin = INT_MIN;
typeMax = INT_MAX;
}
break;
case TYP_UINT:
if (srcType == TYP_INT)
{
signCheckOnly = true;
}
else
{
needScratchReg = true;
}
break;
case TYP_LONG:
noway_assert(srcType == TYP_ULONG);
signCheckOnly = true;
break;
case TYP_ULONG:
noway_assert((srcType == TYP_LONG) || (srcType == TYP_INT));
signCheckOnly = true;
break;
default:
NO_WAY("Unknown type");
return;
}
if (signCheckOnly)
{
// We only need to check for a negative value in sourceReg
inst_RV_IV(INS_cmp, sourceReg, 0, size);
genJumpToThrowHlpBlk(EJ_jl, Compiler::ACK_OVERFLOW);
if (dstType == TYP_ULONG)
{
// cast from TYP_INT to TYP_ULONG
// The upper bits on sourceReg will already be zero by definition (x64)
srcType = TYP_ULONG;
size = EA_8BYTE;
}
}
else
{
regNumber tmpReg = REG_NA;
if (needScratchReg)
{
// We need an additional temp register
// Make sure we have exactly one allocated.
assert(treeNode->gtRsvdRegs != RBM_NONE);
assert(genCountBits(treeNode->gtRsvdRegs) == 1);
tmpReg = genRegNumFromMask(treeNode->gtRsvdRegs);
}
// When we are converting from unsigned or to unsigned, we
// will only have to check for any bits set using 'typeMask'
if (isUnsignedSrc || isUnsignedDst)
{
if (needScratchReg)
{
inst_RV_RV(INS_mov, tmpReg, sourceReg, TYP_LONG); // Move the 64-bit value to a writeable temp reg
inst_RV_SH(INS_SHIFT_RIGHT_LOGICAL, size, tmpReg, 32); // Shift right by 32 bits
genJumpToThrowHlpBlk(EJ_jne, Compiler::ACK_OVERFLOW); // Thow if result shift is non-zero
}
else
{
noway_assert(typeMask != 0);
inst_RV_IV(INS_TEST, sourceReg, typeMask, size);
genJumpToThrowHlpBlk(EJ_jne, Compiler::ACK_OVERFLOW);
}
}
else
{
// For a narrowing signed cast
//
// We must check the value is in a signed range.
// Compare with the MAX
noway_assert((typeMin != 0) && (typeMax != 0));
inst_RV_IV(INS_cmp, sourceReg, typeMax, size);
genJumpToThrowHlpBlk(EJ_jg, Compiler::ACK_OVERFLOW);
// Compare with the MIN
inst_RV_IV(INS_cmp, sourceReg, typeMin, size);
genJumpToThrowHlpBlk(EJ_jl, Compiler::ACK_OVERFLOW);
}
}
if (targetReg != sourceReg)
inst_RV_RV(ins, targetReg, sourceReg, srcType, size);
}
else // non-overflow checking cast
{
noway_assert(size < EA_PTRSIZE || srcType == dstType);
// We may have code transformations that result in casts where srcType is the same as dstType.
// e.g. Bug 824281, in which a comma is split by the rationalizer, leaving an assignment of a
// long constant to a long lclVar.
if (srcType == dstType)
{
ins = INS_mov;
}
/* Is the value sitting in a non-byte-addressable register? */
else if (castOp->InReg() && (size == EA_1BYTE) && !isByteReg(sourceReg))
{
if (isUnsignedDst)
{
// for unsigned values we can AND, so it need not be a byte register
ins = INS_AND;
}
else
{
// Move the value into a byte register
noway_assert(!"Signed byte convert from non-byte-addressable register");
}
/* Generate "mov targetReg, castOp->gtReg */
if (targetReg != sourceReg)
{
inst_RV_RV(INS_mov, targetReg, sourceReg, srcType);
}
}
else if (treeNode->gtSetFlags() && isUnsignedDst && castOp->InReg() && (targetReg == sourceReg))
{
// if we (might) need to set the flags and the value is in the same register
// and we have an unsigned value then use AND instead of MOVZX
noway_assert(ins == INS_movzx || ins == INS_mov);
ins = INS_AND;
}
if (ins == INS_AND)
{
noway_assert((needAndAfter == false) && isUnsignedDst);
/* Generate "and reg, MASK */
insFlags flags = treeNode->gtSetFlags() ? INS_FLAGS_SET : INS_FLAGS_DONT_CARE;
unsigned fillPattern;
if (size == EA_1BYTE)
fillPattern = 0xff;
else if (size == EA_2BYTE)
fillPattern = 0xffff;
else
fillPattern = 0xffffffff;
inst_RV_IV(INS_AND, targetReg, fillPattern, EA_4BYTE, flags);
}
#ifdef _TARGET_AMD64_
else if (ins == INS_movsxd)
{
noway_assert(!needAndAfter);
inst_RV_RV(ins, targetReg, sourceReg, srcType, size);
}
#endif // _TARGET_AMD64_
else if (ins == INS_mov)
{
noway_assert(!needAndAfter);
if (targetReg != sourceReg)
{
inst_RV_RV(ins, targetReg, sourceReg, srcType, size);
}
}
else
{
noway_assert(ins == INS_movsx || ins == INS_movzx);
/* Generate "mov targetReg, castOp->gtReg */
inst_RV_RV(ins, targetReg, sourceReg, srcType, size);
/* Mask off high bits for cast from byte to char */
if (needAndAfter)
{
noway_assert(genTypeSize(dstType) == 2 && ins == INS_movsx);
insFlags flags = treeNode->gtSetFlags() ? INS_FLAGS_SET : INS_FLAGS_DONT_CARE;
inst_RV_IV(INS_AND, targetReg, 0xFFFF, EA_4BYTE, flags);
}
}
}
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genFloatToFloatCast: Generate code for a cast between float and double
//
// Arguments:
// treeNode - The GT_CAST node
//
// Return Value:
// None.
//
// Assumptions:
// Cast is a non-overflow conversion.
// The treeNode must have an assigned register.
// The cast is between float and double or vice versa.
//
void
CodeGen::genFloatToFloatCast(GenTreePtr treeNode)
{
// float <--> double conversions are always non-overflow ones
assert(treeNode->OperGet() == GT_CAST);
assert(!treeNode->gtOverflow());
regNumber targetReg = treeNode->gtRegNum;
assert(genIsValidFloatReg(targetReg));
GenTreePtr op1 = treeNode->gtOp.gtOp1;
#ifdef DEBUG
// If not contained, must be a valid float reg.
if (!op1->isContained())
{
assert(genIsValidFloatReg(op1->gtRegNum));
}
#endif
var_types dstType = treeNode->CastToType();
var_types srcType = op1->TypeGet();
assert(varTypeIsFloating(srcType) && varTypeIsFloating(dstType));
genConsumeOperands(treeNode->AsOp());
if (srcType == dstType && targetReg == op1->gtRegNum)
{
// source and destinations types are the same and also reside in the same register.
// we just need to consume and produce the reg in this case.
;
}
else
{
instruction ins = ins_FloatConv(dstType, srcType);
getEmitter()->emitInsBinary(ins, emitTypeSize(dstType), treeNode, op1);
}
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genIntToFloatCast: Generate code to cast an int/long to float/double
//
// Arguments:
// treeNode - The GT_CAST node
//
// Return Value:
// None.
//
// Assumptions:
// Cast is a non-overflow conversion.
// The treeNode must have an assigned register.
// SrcType= int32/uint32/int64/uint64 and DstType=float/double.
//
void
CodeGen::genIntToFloatCast(GenTreePtr treeNode)
{
// int type --> float/double conversions are always non-overflow ones
assert(treeNode->OperGet() == GT_CAST);
assert(!treeNode->gtOverflow());
regNumber targetReg = treeNode->gtRegNum;
assert(genIsValidFloatReg(targetReg));
GenTreePtr op1 = treeNode->gtOp.gtOp1;
#ifdef DEBUG
if (!op1->isContained())
{
assert(genIsValidIntReg(op1->gtRegNum));
}
#endif
var_types dstType = treeNode->CastToType();
var_types srcType = op1->TypeGet();
assert(!varTypeIsFloating(srcType) && varTypeIsFloating(dstType));
#if !defined(_TARGET_64BIT_)
NYI_IF(varTypeIsLong(srcType), "Conversion from long to float");
#endif // !defined(_TARGET_64BIT_)
// force the srcType to unsigned if GT_UNSIGNED flag is set
if (treeNode->gtFlags & GTF_UNSIGNED)
{
srcType = genUnsignedType(srcType);
}
// We should never be seeing srcType whose size is not sizeof(int) nor sizeof(long).
// For conversions from byte/sbyte/int16/uint16 to float/double, we would expect
// either the front-end or lowering phase to have generated two levels of cast.
// The first one is for widening smaller int type to int32 and the second one is
// to the float/double.
emitAttr srcSize = EA_ATTR(genTypeSize(srcType));
noway_assert((srcSize == EA_ATTR(genTypeSize(TYP_INT))) ||
(srcSize == EA_ATTR(genTypeSize(TYP_LONG))));
// Also we don't expect to see uint32 -> float/double and uint64 -> float conversions
// here since they should have been lowered apropriately.
noway_assert(srcType != TYP_UINT);
noway_assert((srcType != TYP_ULONG) || (dstType != TYP_FLOAT));
// Note that here we need to specify srcType that will determine
// the size of source reg/mem operand and rex.w prefix.
genConsumeOperands(treeNode->AsOp());
instruction ins = ins_FloatConv(dstType, TYP_INT);
getEmitter()->emitInsBinary(ins, emitTypeSize(srcType), treeNode, op1);
// Handle the case of srcType = TYP_ULONG. SSE2 conversion instruction
// will interpret ULONG value as LONG. Hence we need to adjust the
// result if sign-bit of srcType is set.
if (srcType == TYP_ULONG)
{
assert(dstType == TYP_DOUBLE);
assert(!op1->isContained());
// Set the flags without modifying op1.
// test op1Reg, op1Reg
inst_RV_RV(INS_test, op1->gtRegNum, op1->gtRegNum, srcType);
// No need to adjust result if op1 >= 0 i.e. positive
// Jge label
BasicBlock* label = genCreateTempLabel();
inst_JMP(EJ_jge, label);
// Adjust the result
// result = result + 0x43f00000 00000000
// addsd resultReg, 0x43f00000 00000000
GenTreePtr *cns = &u8ToDblBitmask;
if (*cns == nullptr)
{
double d;
static_assert_no_msg(sizeof(double) == sizeof(__int64));
*((__int64 *)&d) = 0x43f0000000000000LL;
*cns = genMakeConst(&d, dstType, treeNode, true);
}
inst_RV_TT(INS_addsd, treeNode->gtRegNum, *cns);
genDefineTempLabel(label);
}
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genFloatToIntCast: Generate code to cast float/double to int/long
//
// Arguments:
// treeNode - The GT_CAST node
//
// Return Value:
// None.
//
// Assumptions:
// Cast is a non-overflow conversion.
// The treeNode must have an assigned register.
// SrcType=float/double and DstType= int32/uint32/int64/uint64
//
// TODO-XArch-CQ: (Low-pri) - generate in-line code when DstType = uint64
//
void
CodeGen::genFloatToIntCast(GenTreePtr treeNode)
{
// we don't expect to see overflow detecting float/double --> int type conversions here
// as they should have been converted into helper calls by front-end.
assert(treeNode->OperGet() == GT_CAST);
assert(!treeNode->gtOverflow());
regNumber targetReg = treeNode->gtRegNum;
assert(genIsValidIntReg(targetReg));
GenTreePtr op1 = treeNode->gtOp.gtOp1;
#ifdef DEBUG
if (!op1->isContained())
{
assert(genIsValidFloatReg(op1->gtRegNum));
}
#endif
var_types dstType = treeNode->CastToType();
var_types srcType = op1->TypeGet();
assert(varTypeIsFloating(srcType) && !varTypeIsFloating(dstType));
// We should never be seeing dstType whose size is neither sizeof(TYP_INT) nor sizeof(TYP_LONG).
// For conversions to byte/sbyte/int16/uint16 from float/double, we would expect the
// front-end or lowering phase to have generated two levels of cast. The first one is
// for float or double to int32/uint32 and the second one for narrowing int32/uint32 to
// the required smaller int type.
emitAttr dstSize = EA_ATTR(genTypeSize(dstType));
noway_assert((dstSize == EA_ATTR(genTypeSize(TYP_INT))) ||
(dstSize == EA_ATTR(genTypeSize(TYP_LONG))));
// We shouldn't be seeing uint64 here as it should have been converted
// into a helper call by either front-end or lowering phase.
noway_assert(!varTypeIsUnsigned(dstType) || (dstSize != EA_ATTR(genTypeSize(TYP_LONG))));
// If the dstType is TYP_UINT, we have 32-bits to encode the
// float number. Any of 33rd or above bits can be the sign bit.
// To acheive it we pretend as if we are converting it to a long.
if (varTypeIsUnsigned(dstType) && (dstSize == EA_ATTR(genTypeSize(TYP_INT))))
{
dstType = TYP_LONG;
}
// Note that we need to specify dstType here so that it will determine
// the size of destination integer register and also the rex.w prefix.
genConsumeOperands(treeNode->AsOp());
instruction ins = ins_FloatConv(TYP_INT, srcType);
getEmitter()->emitInsBinary(ins, emitTypeSize(dstType), treeNode, op1);
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genCkfinite: Generate code for ckfinite opcode.
//
// Arguments:
// treeNode - The GT_CKFINITE node
//
// Return Value:
// None.
//
// Assumptions:
// GT_CKFINITE node has reserved an internal register.
//
// TODO-XArch-CQ - mark the operand as contained if known to be in
// memory (e.g. field or an array element).
//
void
CodeGen::genCkfinite(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_CKFINITE);
GenTreePtr op1 = treeNode->gtOp.gtOp1;
var_types targetType = treeNode->TypeGet();
int expMask = (targetType == TYP_FLOAT) ? 0x7F800000 : 0x7FF00000; // Bit mask to extract exponent.
// Extract exponent into a register.
assert(treeNode->gtRsvdRegs != RBM_NONE);
assert(genCountBits(treeNode->gtRsvdRegs) == 1);
regNumber tmpReg = genRegNumFromMask(treeNode->gtRsvdRegs);
instruction ins = ins_CopyFloatToInt(targetType, (targetType == TYP_FLOAT) ? TYP_INT : TYP_LONG);
inst_RV_RV(ins, genConsumeReg(op1), tmpReg, targetType);
if (targetType == TYP_DOUBLE)
{
// right shift by 32 bits to get to exponent.
inst_RV_SH(INS_shr, EA_8BYTE, tmpReg, 32);
}
// Mask of exponent with all 1's and check if the exponent is all 1's
inst_RV_IV(INS_and, tmpReg, expMask, EA_4BYTE);
inst_RV_IV(INS_cmp, tmpReg, expMask, EA_4BYTE);
// If exponent is all 1's, throw ArithmeticException
genJumpToThrowHlpBlk(EJ_je, Compiler::ACK_ARITH_EXCPN);
// if it is a finite value copy it to targetReg
if (treeNode->gtRegNum != op1->gtRegNum)
{
inst_RV_RV(ins_Copy(targetType), treeNode->gtRegNum, op1->gtRegNum, targetType);
}
genProduceReg(treeNode);
}
#ifdef _TARGET_AMD64_
int CodeGenInterface::genSPtoFPdelta()
{
int delta;
// As per Amd64 ABI, RBP offset from initial RSP can be between 0 and 240 if
// RBP needs to be reported in unwind codes. This case would arise for methods
// with localloc.
if (compiler->compLocallocUsed)
{
// We cannot base delta computation on compLclFrameSize since it changes from
// tentative to final frame layout and hence there is a possibility of
// under-estimating offset of vars from FP, which in turn results in under-
// estimating instruction size.
//
// To be predictive and so as never to under-estimate offset of vars from FP
// we will always position FP at min(240, outgoing arg area size).
delta = Min(240, (int)compiler->lvaOutgoingArgSpaceSize);
}
else if (compiler->opts.compDbgEnC)
{
// vm assumption on EnC methods is that rsp and rbp are equal
delta = 0;
}
else
{
delta = genTotalFrameSize();
}
return delta;
}
//---------------------------------------------------------------------
// genTotalFrameSize - return the total size of the stack frame, including local size,
// callee-saved register size, etc. For AMD64, this does not include the caller-pushed
// return address.
//
// Return value:
// Total frame size
//
int CodeGenInterface::genTotalFrameSize()
{
assert(!IsUninitialized(compiler->compCalleeRegsPushed));
int totalFrameSize = compiler->compCalleeRegsPushed * REGSIZE_BYTES +
compiler->compLclFrameSize;
assert(totalFrameSize >= 0);
return totalFrameSize;
}
//---------------------------------------------------------------------
// genCallerSPtoFPdelta - return the offset from Caller-SP to the frame pointer.
// This number is going to be negative, since the Caller-SP is at a higher
// address than the frame pointer.
//
// There must be a frame pointer to call this function!
//
// We can't compute this directly from the Caller-SP, since the frame pointer
// is based on a maximum delta from Initial-SP, so first we find SP, then
// compute the FP offset.
int CodeGenInterface::genCallerSPtoFPdelta()
{
assert(isFramePointerUsed());
int callerSPtoFPdelta;
callerSPtoFPdelta = genCallerSPtoInitialSPdelta() + genSPtoFPdelta();
assert(callerSPtoFPdelta <= 0);
return callerSPtoFPdelta;
}
//---------------------------------------------------------------------
// genCallerSPtoInitialSPdelta - return the offset from Caller-SP to Initial SP.
//
// This number will be negative.
int CodeGenInterface::genCallerSPtoInitialSPdelta()
{
int callerSPtoSPdelta = 0;
callerSPtoSPdelta -= genTotalFrameSize();
callerSPtoSPdelta -= REGSIZE_BYTES; // caller-pushed return address
// compCalleeRegsPushed does not account for the frame pointer
// TODO-Cleanup: shouldn't this be part of genTotalFrameSize?
if (isFramePointerUsed())
{
callerSPtoSPdelta -= REGSIZE_BYTES;
}
assert(callerSPtoSPdelta <= 0);
return callerSPtoSPdelta;
}
#endif // _TARGET_AMD64_
//-----------------------------------------------------------------------------------------
// genSSE2BitwiseOp - generate SSE2 code for the given oper as "Operand BitWiseOp BitMask"
//
// Arguments:
// treeNode - tree node
//
// Return value:
// None
//
// Assumptions:
// i) tree oper is one of GT_NEG or GT_MATH Abs()
// ii) tree type is floating point type.
// iii) caller of this routine needs to call genProduceReg()
void
CodeGen::genSSE2BitwiseOp(GenTreePtr treeNode)
{
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
assert(varTypeIsFloating(targetType));
float f;
double d;
GenTreePtr *bitMask = nullptr;
instruction ins = INS_invalid;
void *cnsAddr = nullptr;
bool dblAlign = false;
switch(treeNode->OperGet())
{
case GT_NEG:
// Neg(x) = flip the sign bit.
// Neg(f) = f ^ 0x80000000
// Neg(d) = d ^ 0x8000000000000000
ins = genGetInsForOper(GT_XOR, targetType);
if (targetType == TYP_FLOAT)
{
bitMask = &negBitmaskFlt;
static_assert_no_msg(sizeof(float) == sizeof(int));
*((int *)&f) = 0x80000000;
cnsAddr = &f;
}
else
{
bitMask = &negBitmaskDbl;
static_assert_no_msg(sizeof(double) == sizeof(__int64));
*((__int64*)&d) = 0x8000000000000000LL;
cnsAddr = &d;
dblAlign = true;
}
break;
case GT_MATH:
assert(treeNode->gtMath.gtMathFN == CORINFO_INTRINSIC_Abs);
// Abs(x) = set sign-bit to zero
// Abs(f) = f & 0x7fffffff
// Abs(d) = d & 0x7fffffffffffffff
ins = genGetInsForOper(GT_AND, targetType);
if (targetType == TYP_FLOAT)
{
bitMask = &absBitmaskFlt;
static_assert_no_msg(sizeof(float) == sizeof(int));
*((int *)&f) = 0x7fffffff;
cnsAddr = &f;
}
else
{
bitMask = &absBitmaskDbl;
static_assert_no_msg(sizeof(double) == sizeof(__int64));
*((__int64*)&d) = 0x7fffffffffffffffLL;
cnsAddr = &d;
dblAlign = true;
}
break;
default:
assert(!"genSSE2: unsupported oper");
unreached();
break;
}
if (*bitMask == nullptr)
{
assert(cnsAddr != nullptr);
*bitMask = genMakeConst(cnsAddr, targetType, treeNode, dblAlign);
}
// We need an additional register for bitmask.
// Make sure we have one allocated.
assert(treeNode->gtRsvdRegs != RBM_NONE);
assert(genCountBits(treeNode->gtRsvdRegs) == 1);
regNumber tmpReg = genRegNumFromMask(treeNode->gtRsvdRegs);
// Move operand into targetReg only if the reg reserved for
// internal purpose is not the same as targetReg.
GenTreePtr op1 = treeNode->gtOp.gtOp1;
assert(!op1->isContained());
regNumber operandReg = genConsumeReg(op1);
if (tmpReg != targetReg)
{
if (operandReg != targetReg)
{
inst_RV_RV(ins_Copy(targetType), targetReg, operandReg, targetType);
}
operandReg = tmpReg;
}
inst_RV_TT(ins_Load(targetType, false), tmpReg, *bitMask);
assert(ins != INS_invalid);
inst_RV_RV(ins, targetReg, operandReg, targetType);
}
//---------------------------------------------------------------------
// genMathIntrinsic - generate code for a given math intrinsic
//
// Arguments
// treeNode - the GT_MATH node
//
// Return value:
// None
//
void
CodeGen::genMathIntrinsic(GenTreePtr treeNode)
{
// Right now only Sqrt/Abs are treated as math intrinsics.
switch(treeNode->gtMath.gtMathFN)
{
case CORINFO_INTRINSIC_Sqrt:
noway_assert(treeNode->TypeGet() == TYP_DOUBLE);
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(ins_FloatSqrt(treeNode->TypeGet()), emitTypeSize(treeNode), treeNode, treeNode->gtOp.gtOp1);
break;
case CORINFO_INTRINSIC_Abs:
genSSE2BitwiseOp(treeNode);
break;
default:
assert(!"genMathIntrinsic: Unsupported math intrinsic");
unreached();
}
genProduceReg(treeNode);
}
#ifdef _TARGET_X86_
void
CodeGen::genPutArgStk(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_PUTARG_STK);
var_types targetType = treeNode->TypeGet();
noway_assert(targetType != TYP_STRUCT);
assert(!varTypeIsFloating(targetType) || (targetType == treeNode->gtGetOp1()->TypeGet()));
GenTreePtr data = treeNode->gtOp.gtOp1;
#if !defined(_TARGET_64BIT_)
// On a 64-bit target, all of the long arguments have been decomposed into
// a separate putarg_stk for each of the upper and lower halves.
noway_assert(targetType != TYP_LONG);
#endif // !defined(_TARGET_64BIT_)
// Decrement SP.
int argSize = genTypeSize(genActualType(targetType));
inst_RV_IV(INS_sub, REG_SPBASE, argSize, emitActualTypeSize(TYP_I_IMPL));
genStackLevel += argSize;
// TODO-Cleanup: Handle this in emitInsMov() in emitXArch.cpp?
if (data->isContained())
{
NYI_X86("Contained putarg_stk");
}
else
{
genConsumeReg(data);
getEmitter()->emitIns_AR_R(ins_Store(targetType), emitTypeSize(targetType), data->gtRegNum, REG_SPBASE, 0);
}
}
#endif // _TARGET_X86_
/*****************************************************************************
*
* Create and record GC Info for the function.
*/
#ifdef _TARGET_AMD64_
void
#else // !_TARGET_AMD64_
void*
#endif // !_TARGET_AMD64_
CodeGen::genCreateAndStoreGCInfo(unsigned codeSize, unsigned prologSize, unsigned epilogSize DEBUG_ARG(void* codePtr))
{
#ifdef JIT32_GCENCODER
return genCreateAndStoreGCInfoJIT32(codeSize, prologSize, epilogSize DEBUG_ARG(codePtr));
#else // !JIT32_GCENCODER
genCreateAndStoreGCInfoX64(codeSize, prologSize DEBUG_ARG(codePtr));
#endif // !JIT32_GCENCODER
}
#ifdef JIT32_GCENCODER
void* CodeGen::genCreateAndStoreGCInfoJIT32(unsigned codeSize, unsigned prologSize, unsigned epilogSize DEBUG_ARG(void* codePtr))
{
BYTE headerBuf[64];
InfoHdr header;
int s_cached;
#ifdef DEBUG
size_t headerSize =
#endif
compiler->compInfoBlkSize = gcInfo.gcInfoBlockHdrSave(headerBuf,
0,
codeSize,
prologSize,
epilogSize,
&header,
&s_cached);
size_t argTabOffset = 0;
size_t ptrMapSize = gcInfo.gcPtrTableSize(header, codeSize, &argTabOffset);
#if DISPLAY_SIZES
if (genInterruptible)
{
gcHeaderISize += compiler->compInfoBlkSize;
gcPtrMapISize += ptrMapSize;
}
else
{
gcHeaderNSize += compiler->compInfoBlkSize;
gcPtrMapNSize += ptrMapSize;
}
#endif // DISPLAY_SIZES
compiler->compInfoBlkSize += ptrMapSize;
/* Allocate the info block for the method */
compiler->compInfoBlkAddr = (BYTE *) compiler->info.compCompHnd->allocGCInfo(compiler->compInfoBlkSize);
#if 0 // VERBOSE_SIZES
// TODO-X86-Cleanup: 'dataSize', below, is not defined
// if (compiler->compInfoBlkSize > codeSize && compiler->compInfoBlkSize > 100)
{
printf("[%7u VM, %7u+%7u/%7u x86 %03u/%03u%%] %s.%s\n",
compiler->info.compILCodeSize,
compiler->compInfoBlkSize,
codeSize + dataSize,
codeSize + dataSize - prologSize - epilogSize,
100 * (codeSize + dataSize) / compiler->info.compILCodeSize,
100 * (codeSize + dataSize + compiler->compInfoBlkSize) / compiler->info.compILCodeSize,
compiler->info.compClassName,
compiler->info.compMethodName);
}
#endif
/* Fill in the info block and return it to the caller */
void* infoPtr = compiler->compInfoBlkAddr;
/* Create the method info block: header followed by GC tracking tables */
compiler->compInfoBlkAddr += gcInfo.gcInfoBlockHdrSave(compiler->compInfoBlkAddr, -1,
codeSize,
prologSize,
epilogSize,
&header,
&s_cached);
assert(compiler->compInfoBlkAddr == (BYTE*)infoPtr + headerSize);
compiler->compInfoBlkAddr = gcInfo.gcPtrTableSave(compiler->compInfoBlkAddr, header, codeSize, &argTabOffset);
assert(compiler->compInfoBlkAddr == (BYTE*)infoPtr + headerSize + ptrMapSize);
#ifdef DEBUG
if (0)
{
BYTE * temp = (BYTE *)infoPtr;
unsigned size = compiler->compInfoBlkAddr - temp;
BYTE * ptab = temp + headerSize;
noway_assert(size == headerSize + ptrMapSize);
printf("Method info block - header [%u bytes]:", headerSize);
for (unsigned i = 0; i < size; i++)
{
if (temp == ptab)
{
printf("\nMethod info block - ptrtab [%u bytes]:", ptrMapSize);
printf("\n %04X: %*c", i & ~0xF, 3*(i&0xF), ' ');
}
else
{
if (!(i % 16))
printf("\n %04X: ", i);
}
printf("%02X ", *temp++);
}
printf("\n");
}
#endif // DEBUG
#if DUMP_GC_TABLES
if (compiler->opts.dspGCtbls)
{
const BYTE *base = (BYTE *)infoPtr;
unsigned size;
unsigned methodSize;
InfoHdr dumpHeader;
printf("GC Info for method %s\n", compiler->info.compFullName);
printf("GC info size = %3u\n", compiler->compInfoBlkSize);
size = gcInfo.gcInfoBlockHdrDump(base, &dumpHeader, &methodSize);
// printf("size of header encoding is %3u\n", size);
printf("\n");
if (compiler->opts.dspGCtbls)
{
base += size;
size = gcInfo.gcDumpPtrTable(base, dumpHeader, methodSize);
// printf("size of pointer table is %3u\n", size);
printf("\n");
noway_assert(compiler->compInfoBlkAddr == (base+size));
}
}
#ifdef DEBUG
if (jitOpts.testMask & 128)
{
for (unsigned offs = 0; offs < codeSize; offs++)
{
gcInfo.gcFindPtrsInFrame(infoPtr, codePtr, offs);
}
}
#endif // DEBUG
#endif // DUMP_GC_TABLES
/* Make sure we ended up generating the expected number of bytes */
noway_assert(compiler->compInfoBlkAddr == (BYTE *)infoPtr + compiler->compInfoBlkSize);
return infoPtr;
}
#else // !JIT32_GCENCODER
void
CodeGen::genCreateAndStoreGCInfoX64(unsigned codeSize, unsigned prologSize DEBUG_ARG(void* codePtr))
{
IAllocator* allowZeroAlloc = new (compiler, CMK_GC) AllowZeroAllocator(compiler->getAllocatorGC());
GcInfoEncoder* gcInfoEncoder = new (compiler, CMK_GC) GcInfoEncoder(compiler->info.compCompHnd, compiler->info.compMethodInfo, allowZeroAlloc);
assert(gcInfoEncoder);
// Follow the code pattern of the x86 gc info encoder (genCreateAndStoreGCInfoJIT32).
gcInfo.gcInfoBlockHdrSave(gcInfoEncoder, codeSize, prologSize);
// First we figure out the encoder ID's for the stack slots and registers.
gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::MAKE_REG_PTR_MODE_ASSIGN_SLOTS);
// Now we've requested all the slots we'll need; "finalize" these (make more compact data structures for them).
gcInfoEncoder->FinalizeSlotIds();
// Now we can actually use those slot ID's to declare live ranges.
gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::MAKE_REG_PTR_MODE_DO_WORK);
#if defined(DEBUGGING_SUPPORT)
if (compiler->opts.compDbgEnC)
{
// what we have to preserve is called the "frame header" (see comments in VM\eetwain.cpp)
// which is:
// -return address
// -saved off RBP
// -saved 'this' pointer and bool for synchronized methods
// 4 slots for RBP + return address + RSI + RDI
int preservedAreaSize = 4 * REGSIZE_BYTES;
if (compiler->info.compFlags & CORINFO_FLG_SYNCH)
{
if (!(compiler->info.compFlags & CORINFO_FLG_STATIC))
preservedAreaSize += REGSIZE_BYTES;
// bool in synchronized methods that tracks whether the lock has been taken (takes 4 bytes on stack)
preservedAreaSize += 4;
}
// Used to signal both that the method is compiled for EnC, and also the size of the block at the top of the frame
gcInfoEncoder->SetSizeOfEditAndContinuePreservedArea(preservedAreaSize);
}
#endif
gcInfoEncoder->Build();
//GC Encoder automatically puts the GC info in the right spot using ICorJitInfo::allocGCInfo(size_t)
//let's save the values anyway for debugging purposes
compiler->compInfoBlkAddr = gcInfoEncoder->Emit();
compiler->compInfoBlkSize = 0; //not exposed by the GCEncoder interface
}
#endif // !JIT32_GCENCODER
/*****************************************************************************
* Emit a call to a helper function.
*
*/
void CodeGen::genEmitHelperCall(unsigned helper,
int argSize,
emitAttr retSize
#ifdef _TARGET_AMD64_
,regNumber callTargetReg /*= REG_HELPER_CALL_TARGET*/
#endif // _TARGET_AMD64_
)
{
void * addr = NULL, *pAddr = NULL;
#ifdef _TARGET_X86_
regNumber callTargetReg = REG_EAX;
#endif // _TARGET_X86_
emitter::EmitCallType callType = emitter::EC_FUNC_TOKEN;
addr = compiler->compGetHelperFtn((CorInfoHelpFunc)helper, &pAddr);
regNumber callTarget = REG_NA;
if (!addr)
{
assert(pAddr != nullptr);
if (genAddrShouldUsePCRel((size_t)pAddr))
{
// generate call whose target is specified by PC-relative 32-bit offset.
callType = emitter::EC_FUNC_TOKEN_INDIR;
addr = pAddr;
}
else
{
// If this address cannot be encoded as PC-relative 32-bit offset, load it into REG_HELPER_CALL_TARGET
// and use register indirect addressing mode to make the call.
// mov reg, addr
// call [reg]
callTarget = callTargetReg;
CodeGen::genSetRegToIcon(callTarget, (ssize_t) pAddr, TYP_I_IMPL);
callType = emitter::EC_INDIR_ARD;
}
}
getEmitter()->emitIns_Call(callType,
compiler->eeFindHelper(helper),
INDEBUG_LDISASM_COMMA(nullptr)
addr,
argSize,
retSize,
gcInfo.gcVarPtrSetCur,
gcInfo.gcRegGCrefSetCur,
gcInfo.gcRegByrefSetCur,
BAD_IL_OFFSET, /* IL offset */
callTarget, /* ireg */
REG_NA, 0, 0, /* xreg, xmul, disp */
false, /* isJump */
emitter::emitNoGChelper(helper));
regMaskTP killMask = compiler->compHelperCallKillSet((CorInfoHelpFunc)helper);
regTracker.rsTrashRegSet(killMask);
regTracker.rsTrashRegsForGCInterruptability();
}
#if !defined(_TARGET_64BIT_)
//-----------------------------------------------------------------------------
//
// Code Generation for Long integers
//
//-----------------------------------------------------------------------------
//------------------------------------------------------------------------
// genStoreLongLclVar: Generate code to store a non-enregistered long lclVar
//
// Arguments:
// treeNode - A TYP_LONG lclVar node.
//
// Return Value:
// None.
//
// Assumptions:
// 'treeNode' must be a TYP_LONG lclVar node for a lclVar that has NOT been promoted.
// Its operand must be a GT_LONG node.
//
void CodeGen::genStoreLongLclVar(GenTree* treeNode)
{
emitter* emit = getEmitter();
GenTreeLclVarCommon* lclNode = treeNode->AsLclVarCommon();
unsigned lclNum = lclNode->gtLclNum;
LclVarDsc* varDsc = &(compiler->lvaTable[lclNum]);
assert(varDsc->TypeGet() == TYP_LONG);
assert(!varDsc->lvPromoted);
GenTreePtr op1 = treeNode->gtOp.gtOp1;
noway_assert(op1->OperGet() == GT_LONG);
genConsumeRegs(op1);
// Definitions of register candidates will have been lowered to 2 int lclVars.
assert(!treeNode->InReg());
GenTreePtr loVal = op1->gtGetOp1();
GenTreePtr hiVal = op1->gtGetOp2();
// NYI: Contained immediates.
NYI_IF((loVal->gtRegNum == REG_NA) || (hiVal->gtRegNum == REG_NA), "Store of long lclVar with contained immediate");
emit->emitIns_R_S(ins_Store(TYP_INT), EA_4BYTE, loVal->gtRegNum, lclNum, 0);
emit->emitIns_R_S(ins_Store(TYP_INT), EA_4BYTE, hiVal->gtRegNum, lclNum, genTypeSize(TYP_INT));
}
#endif // !defined(_TARGET_64BIT_)
/*****************************************************************************
* Unit testing of the XArch emitter: generate a bunch of instructions into the prolog
* (it's as good a place as any), then use COMPLUS_JitLateDisasm=* to see if the late
* disassembler thinks the instructions as the same as we do.
*/
// Uncomment "#define ALL_ARM64_EMITTER_UNIT_TESTS" to run all the unit tests here.
// After adding a unit test, and verifying it works, put it under this #ifdef, so we don't see it run every time.
//#define ALL_XARCH_EMITTER_UNIT_TESTS
#if defined(DEBUG) && defined(LATE_DISASM) && defined(_TARGET_AMD64_)
void CodeGen::genAmd64EmitterUnitTests()
{
if (!verbose)
{
return;
}
if (!compiler->opts.altJit)
{
// No point doing this in a "real" JIT.
return;
}
// Mark the "fake" instructions in the output.
printf("*************** In genAmd64EmitterUnitTests()\n");
// We use this:
// genDefineTempLabel(genCreateTempLabel());
// to create artificial labels to help separate groups of tests.
//
// Loads
//
#ifdef ALL_XARCH_EMITTER_UNIT_TESTS
#ifdef FEATURE_AVX_SUPPORT
genDefineTempLabel(genCreateTempLabel());
// vhaddpd ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_haddpd, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vaddss xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_addss, EA_4BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vaddsd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_addsd, EA_8BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vaddps xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_addps, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vaddps ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_addps, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vaddpd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_addpd, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vaddpd ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_addpd, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vsubss xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_subss, EA_4BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vsubsd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_subsd, EA_8BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vsubps ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_subps, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vsubps ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_subps, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vsubpd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_subpd, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vsubpd ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_subpd, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vmulss xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_mulss, EA_4BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vmulsd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_mulsd, EA_8BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vmulps xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_mulps, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vmulpd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_mulpd, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vmulps ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_mulps, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vmulpd ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_mulpd, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vandps xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_andps, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vandpd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_andpd, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vandps ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_andps, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vandpd ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_andpd, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vorps xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_orps, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vorpd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_orpd, EA_16BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vorps ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_orps, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vorpd ymm0,ymm1,ymm2
getEmitter()->emitIns_R_R_R(INS_orpd, EA_32BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vdivss xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_divss, EA_4BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vdivsd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_divsd, EA_8BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vdivss xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_divss, EA_4BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vdivsd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_divsd, EA_8BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vdivss xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_cvtss2sd, EA_4BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
// vdivsd xmm0,xmm1,xmm2
getEmitter()->emitIns_R_R_R(INS_cvtsd2ss, EA_8BYTE, REG_XMM0, REG_XMM1, REG_XMM2);
#endif // FEATURE_AVX_SUPPORT
#endif // ALL_XARCH_EMITTER_UNIT_TESTS
printf("*************** End of genAmd64EmitterUnitTests()\n");
}
#endif // defined(DEBUG) && defined(LATE_DISASM) && defined(_TARGET_AMD64_)
/*****************************************************************************/
#ifdef DEBUGGING_SUPPORT
/*****************************************************************************
* genSetScopeInfo
*
* Called for every scope info piece to record by the main genSetScopeInfo()
*/
void CodeGen::genSetScopeInfo (unsigned which,
UNATIVE_OFFSET startOffs,
UNATIVE_OFFSET length,
unsigned varNum,
unsigned LVnum,
bool avail,
Compiler::siVarLoc& varLoc)
{
/* We need to do some mapping while reporting back these variables */
unsigned ilVarNum = compiler->compMap2ILvarNum(varNum);
noway_assert((int)ilVarNum != ICorDebugInfo::UNKNOWN_ILNUM);
VarName name = nullptr;
#ifdef DEBUG
for (unsigned scopeNum = 0; scopeNum < compiler->info.compVarScopesCount; scopeNum++)
{
if (LVnum == compiler->info.compVarScopes[scopeNum].vsdLVnum)
{
name = compiler->info.compVarScopes[scopeNum].vsdName;
}
}
// Hang on to this compiler->info.
TrnslLocalVarInfo &tlvi = genTrnslLocalVarInfo[which];
tlvi.tlviVarNum = ilVarNum;
tlvi.tlviLVnum = LVnum;
tlvi.tlviName = name;
tlvi.tlviStartPC = startOffs;
tlvi.tlviLength = length;
tlvi.tlviAvailable = avail;
tlvi.tlviVarLoc = varLoc;
#endif // DEBUG
compiler->eeSetLVinfo(which, startOffs, length, ilVarNum, LVnum, name, avail, varLoc);
}
#endif // DEBUGGING_SUPPORT
#endif // _TARGET_AMD64_
#endif // !LEGACY_BACKEND
| mit |
LinogeFly/DistanceTracker | src/DistanceTracker.Web/API/ViewModel/Point.cs | 253 | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DistanceTracker.API.ViewModel
{
public class Point
{
public double Lat { get; set; }
public double Lng { get; set; }
}
}
| mit |
ZKasica/Planet-Generator | html/src/zk/planet_generator/client/HtmlLauncher.java | 662 | package zk.planet_generator.client;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import zk.planet_generator.PlanetGeneratorGame;
public class HtmlLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
GwtApplicationConfiguration config = new GwtApplicationConfiguration(1280, 720);
return config;
}
@Override
public ApplicationListener createApplicationListener () {
return new PlanetGeneratorGame();
}
} | mit |
sd-f/orbi | Orbi-Server/src/main/java/foundation/softwaredesign/orbi/persistence/repo/game/gameobject/GameObjectTypeMappper.java | 2265 | package foundation.softwaredesign.orbi.persistence.repo.game.gameobject;
import foundation.softwaredesign.orbi.model.game.gameobject.GameObjectType;
import foundation.softwaredesign.orbi.persistence.entity.GameObjectTypeEntity;
import org.apache.deltaspike.data.api.mapping.SimpleQueryInOutMapperBase;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
/**
* @author Lucas Reeh <lr86gm@gmail.com>
*/
public class GameObjectTypeMappper extends SimpleQueryInOutMapperBase<GameObjectTypeEntity, GameObjectType> {
@Override
protected Object getPrimaryKey(GameObjectType dto) {
return dto.getId();
}
@Override
public GameObjectType toDto(GameObjectTypeEntity entity) {
GameObjectType dto = toSimpleDto(entity);
if (nonNull(entity.getGameObjectTypeCategoryEntity()))
dto.setCategory(new GameObjectTypeCategoryMappper().toDto(entity.getGameObjectTypeCategoryEntity()));
return dto;
}
public GameObjectType toSimpleDto(GameObjectTypeEntity entity) {
GameObjectType dto = new GameObjectType();
dto.setId(entity.getId());
dto.setPrefab(entity.getPrefab());
dto.setRarity(entity.getRarity());
dto.setCategoryId(entity.getCategoryId());
dto.setOrdering(entity.getOrdering());
dto.setSpawnAmount(entity.getSpawnAmount());
dto.setSupportsUserText(entity.getSupportsUserText());
dto.setGift(entity.getGift());
dto.setAi(entity.getAi());
return dto;
}
@Override
public GameObjectTypeEntity toEntity(GameObjectTypeEntity oldEntity, GameObjectType dto) {
GameObjectTypeEntity newEntity = oldEntity;
if (isNull(oldEntity)) {
newEntity = new GameObjectTypeEntity();
}
newEntity.setId(dto.getId());
newEntity.setPrefab(dto.getPrefab());
newEntity.setRarity(dto.getRarity());
newEntity.setCategoryId(dto.getCategoryId());
newEntity.setSupportsUserText(dto.getSupportsUserText());
newEntity.setSpawnAmount(dto.getSpawnAmount());
newEntity.setOrdering(dto.getOrdering());
newEntity.setGift(dto.getGift());
newEntity.setAi(dto.getAi());
return newEntity;
}
}
| mit |
agungsurya03/SIMPI | application/views/content/kurikulum/v_tambah_detilhari.php | 876 | <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php echo form_open('c_RKH/tambahDetilHari'); ?>
<input type="hidden" name="id_hari" value="<?php echo $id_hari ?>">
<select name="id_jenis_keg">
<?php foreach ($jeniskeg as $row): ?>
<option value="<?php echo $row->id_jenis_keg; ?>"><?php echo $row->jenis_kegiatan ?></option>
<?php endforeach ?>
</select>
<br>
<input type="text" name="urutan" placeholder="Urutan">
<br>
<textarea name="kegiatan" placeholder="Detail Kegiatan"></textarea>
<br>
<input type="text" name="media" placeholder="Media">
<br>
<input type="text" name="durasi" maxlength="3"> Menit
<br>
<?php foreach ($indikator as $row) { ?>
<input type="radio" name="id_indisub" value="<?php echo $row->id_indisub?>"> <?php echo $row->indikator; ?>
<br>
<?php } ?>
<input type="submit" value="Tambah">
<?php echo form_close(); ?>
</body>
</html> | mit |
SunilWang/koa-server-timestamp | index.js | 1616 | /*!
* koa-server-timestamp
* Copyright(c) 2017-2017 Sunil Wang
* MIT Licensed
*/
/**
* Module exports.
* @public
*/
module.exports = serverTimestamp;
/**
* Format timestamp, returns defaults to timestamp
*
* ex:
*
* function format(timestamp) {
* let now = new Date(timestamp);
* let year = now.getFullYear();
* let month = now.getMonth() + 1;
* let date = now.getDate();
* let hour = now.getHours();
* let minute = now.getMinutes();
* let second = now.getSeconds();
*
* //2017-4-27 18:36:56
* return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
* }
*
* @param {Number} timestamp
* @returns {Number|String|*} defaults to timestamp
* @private
*/
function defaultFormat(timestamp) {
return timestamp;
}
/**
* Create a middleware to add a server timestamp header in milliseconds.
* Use for Koa v2
*
* @param {String} [header] The name of the header to set, defaults to X-Server-Timestamp.
* @param {Function} [format] Format timestamp, see below for private function defaultFormat.
* @returns {Function}
* @api public
*/
function serverTimestamp({header = 'X-Server-Timestamp', format = defaultFormat} = {}) {
if (typeof header !== 'string') {
throw new Error('header must be a string');
}
if (header.length < 1) {
throw new Error('header the length must be greater than 0');
}
if (typeof format !== 'function') {
throw new Error('format must be a function');
}
return function responseTime(ctx, next){
ctx.set(header, format(Date.now()));
return next();
};
}
| mit |
fvm/slackey | service/src/main/java/com/github/fvm/slackey/service/api/v1/commands/slash/domain/SlashResponse.java | 302 | package com.github.fvm.slackey.service.api.v1.commands.slash.domain;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.experimental.SuperBuilder;
@SuperBuilder
public abstract class SlashResponse {
@JsonPOJOBuilder
public static abstract class Builder {
}
}
| mit |
cybersonic/org.cfeclipse.cfml | src/org/cfeclipse/cfml/editors/contentassist/DefaultAssistAttributeState.java | 4931 | /*
* Created on Sep 22, 2004
*
* The MIT License
* Copyright (c) 2004 Oliver Tupman
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.cfeclipse.cfml.editors.contentassist;
//import org.eclipse.core.internal.utils.Assert;
/**
* @author Oliver Tupman
*/
public class DefaultAssistAttributeState extends DefaultAssistTagState
implements IAssistTagAttributeState {
/**
* The attribute the user is requesting assist on.
*/
private String attribute = null;
/**
* The attribute value that the user has so far typed in.
*/
private String valueSoFar = null;
/**
* @param baseState
*/
public DefaultAssistAttributeState() {
super();
}
/**
* Constructs this state from a tag assist state.
*
* @param baseState The base assist
*/
public DefaultAssistAttributeState(IAssistTagState baseState)
{
super(baseState);
setTagName(baseState.getTagName());
setAttrText(baseState.getAttributeText());
}
/**
* Constructs this state from a tag assist state plus the name of
* the attribute.
*
* @param baseState The base assist
* @param attributeText The attribute that insight is requested for
*/
public DefaultAssistAttributeState(IAssistTagState baseState, String attributeText)
{
this(baseState);
setAttribute(attributeText);
}
/**
* Constructs this state from a tag assist state plus he name of the attribute
* and the value typed in so far by the user.
*
* @param baseState The base assist
* @param attributeText The attribute that insight is required for
* @param valueSoFar The value typed in so far by the user
*/
public DefaultAssistAttributeState(IAssistTagState baseState, String attributeText, String valueSoFar)
{
this(baseState, attributeText);
setValueSoFar(valueSoFar);
setTextViewer(baseState.getITextView());
}
/**
* Sets the attribute for the state that this represents.
* TODO: Make sure this works with cfset
* @param attributeText The name of the attribute
*/
public void setAttribute(String attributeText)
{
//Assert.isNotNull(attributeText,"DefaultAssistAttributeState::setAttribute()");
if(attributeText == null)
throw new IllegalArgumentException("DefaultAssistAttributeState::setAttribute()");
this.attribute = attributeText;
}
/**
* Sets the attribute value so far.
*
* @param valueSoFar
*/
public void setValueSoFar(String valueSoFar)
{
//Assert.isNotNull(valueSoFar,"DefaultAssistAttributeState::setValueSoFar()");
if(valueSoFar == null)
throw new IllegalArgumentException("DefaultAssistAttributeState::setValueSoFar()");
this.valueSoFar = valueSoFar;
}
/* (non-Javadoc)
* @see org.cfeclipse.cfml.editors.contentassistors.IAssistTagAttributeState#getAttribute()
*/
public String getAttribute() {
//Assert.isNotNull(this.attribute,"DefaultAssistAttributeState::getAttribute()");
if(this.attribute == null)
throw new IllegalArgumentException("DefaultAssistAttributeState::getAttribute()");
return this.attribute;
}
/* (non-Javadoc)
* @see org.cfeclipse.cfml.editors.contentassistors.IAssistTagAttributeState#getValueSoFar()
*/
public String getValueSoFar() {
//Assert.isNotNull(this.valueSoFar,"DefaultAssistAttributeState::getValueSoFar()");
if(this.valueSoFar == null)
throw new IllegalArgumentException("DefaultAssistAttributeState::getValueSoFar()");
return this.valueSoFar;
}
}
| mit |
coltjones/sudoku | sudoku.class.php | 11387 | <?php
class sudoku extends grid {
public function __construct () {
//Initialize our seed state
$this->seeded = FALSE;
//Initialize hidden singles
$this->hiddenSingles = 0;
//Create an array of 9 elements starting at 1 all NULL values
$grids = array_fill(1,9,NULL);
//For each NULL create a new grid object.
$grids = array_map(function ($val) {
$tmp = new grid();
return $tmp;
},$grids);
$this->data = array_combine(range(1,9),$grids);
//Populate the positions we need to place values for
$tmp = range(1,81);
$this->placementArr = array_combine($tmp,$tmp);
//Ensure we are NOT solved
$this->solved = FALSE;
}
public function __clone () {
//Make sure any objects we have in $this->data get cloned too
foreach ($this->data as $i => $o) {
if ($o instanceof grid) {
$this->data[$i] = clone $o;
}
}
}
public function getGrid ($gridNum) {
return $this->data[$gridNum];
}
public function generate () {
if ($this->seeded) {
$this->findHiddenSingles();
}
return $this->solve($this, $this->placementArr);
}
public function findHiddenSingles () {
$found = FALSE;
$possibles = $this->findPossibles();
$gridLines = $this->getGridLineArrs();
foreach ($gridLines as $lineArr) {
//Initialize the lookup array to empty
$checkArr = [];
foreach ($lineArr as $loc) {
if (!isset($possibles[$loc])) {
continue;
}
foreach ($possibles[$loc] as $v) {
@$checkArr[$v]++;
}
}
//Find any keys with a value of 1
$singles = array_filter($checkArr, function ($v) {
return ($v == 1)?TRUE:FALSE;
});
//Do we have singles to handle?
if (count($singles) > 0) {
$singles = array_keys($singles);
foreach ($singles as $sVal) {
//Find the location of the singles
foreach ($lineArr as $loc) {
if (!isset($possibles[$loc])) {
continue;
}
if (in_array($sVal, $possibles[$loc])) {
$this->initCell($loc, $sVal);
$this->hiddenSingles++;
$found = TRUE;
}
}
}
}
}
if ($found) {
$this->findHiddenSingles();
}
return;
}
public function findPossibles ($location = NULL) {
$possible = [];
$single = FALSE;
if (is_array($location)) {
//Do what we were asked to
$range = $location;
} else {
if ($location === NULL) {
//Do them all
$range = array_keys($this->placementArr);
} else {
//Do only the one specified
$range = [$location];
$single = TRUE;
}
}
//Look through each column
foreach ($range as $loc) {
list($gridNum, $cellNum) = $this->lookupCoords($loc);
//Get the grid
$sGrid = $this->getGrid($gridNum);
if ($sGrid->isLockedCell($cellNum)) {
return [$sGrid->getCell($cellNum)];
}
$gRow = $this->gridNumToRow($gridNum);
$gCol = $this->gridNumToCol($gridNum);
//Gather the info we can
$rem = $sGrid->getRemaining();
sort($rem);
$rem = array_combine($rem,$rem);
$row = array_filter($this->getAggRow($gRow, $cellNum));
$row = array_combine($row,$row);
asort($row);
$col = array_filter($this->getAggCol($gCol, $cellNum));
$col = array_combine($col,$col);
asort($col);
//Finally diff it
$possible = array_diff_assoc($rem, $row, $col);
if ($single) {
//Only care about this cell right now.
return $possible;
} else {
$ret[$loc] = $possible;
}
}
return $ret;
}
public function solve ($gArr, $pArr) {
do {
$g = $gArr;
$p = $pArr;
//Place some stuff
if (count($p) > 0) {
$p = $this->sortPlacementArr($p);
$loc = array_shift($p);
list($gridNum, $cellNum) = $this->lookupCoords($loc);
//echo "LOC $loc".PHP_EOL;
//Get the subGrid
$sGrid = $g->getGrid($gridNum);
//If the cell is locked just recurse, nothing to do at this position
if ($sGrid->isLockedCell($cellNum)) {
//echo "Cell is locked. Moving on...".PHP_EOL;
if ($this->solve($g,$p)) {
return TRUE;
} else {
return FALSE;
}
}
if ($this->seeded) {
//Eliminate as many options as we can...
$testVals = $this->findPossibles($loc);
} else {
$testVals = $sGrid->getRemaining();
}
if (!(count($testVals) > 0)) {
//echo "No testVals to use...".PHP_EOL;
return FALSE;
}
//echo "\ttestVals = ".implode(", ",$testVals).PHP_EOL;
do {
$val = array_shift($testVals);
//Set the value
$sGrid->setCell($cellNum, $val);
//Test for validity @ the supergrid
$valid = $g->isValid($gridNum, $cellNum);
if ($valid) {
//echo $this->getPrintableGrid();
//Try this tree
if ($this->solve($g,$p)) {
return TRUE;
} else {
//Reset the cell
$sGrid->clearCell($cellNum);
$valid = FALSE;
}
} else {
//echo "Invalid placement...".PHP_EOL;
$sGrid->clearCell($cellNum);
}
} while (!$valid && count($testVals));
if (!$valid) {
return FALSE;
}
} else {
$this->solved = TRUE;
$this->data = $g->data;
}
} while (!$this->solved);
return TRUE;
}
public function getPrintableGrid () {
$printStr = PHP_EOL;
$printStr .= "-------------------------".PHP_EOL;
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
$printStr .= "| ";
foreach ($this->getRow($i) as $gObj) {
foreach ($gObj->getRow($j) as $cellVal) {
$printStr .= sprintf("%1s ", $cellVal);
}
$printStr .= "| ";
}
$printStr .= PHP_EOL;
}
$printStr .= "-------------------------".PHP_EOL;
}
$printStr .= PHP_EOL;
return $printStr;
}
public function isValid ($gridNum, $cellNum) {
//Get the grid row and column we need
$gRow = $this->gridNumToRow($gridNum);
$gCol = $this->gridNumToCol($gridNum);
//Get the row and column you need
$tmp = $this->getAggRow($gRow, $cellNum);
$rValid = $this->checkDupes($tmp);
$tmp = $this->getAggCol($gCol, $cellNum);
$cValid = $this->checkDupes($tmp);
return ($rValid&&$cValid)?TRUE:FALSE;
}
public function checkDupes ($check) {
$tmp = [];
$check = array_filter($check);
foreach ($check as $v) {
@$tmp[$v]++;
}
arsort($tmp);
$one = array_shift($tmp);
if ($one > 1) {
return FALSE;
}
return TRUE;
}
public function initCell ($loc, $value) {
$this->seeded = TRUE;
list($gridNum, $cellNum) = $this->lookupCoords($loc);
$sGrid = $this->getGrid($gridNum);
$sGrid->setCell($cellNum, $value, TRUE);
//Clear this from the work list
unset($this->placementArr[$loc]);
return TRUE;
}
public function getAggRow ($gRow, $cellNum) {
$tmp = [];
foreach ($gRow as $row) {
$cRow = $row->gridNumToRow($cellNum);
$tmp = array_merge($tmp,$cRow);
}
return $tmp;
}
public function getAggCol ($gCol, $cellNum) {
$tmp = [];
foreach ($gCol as $col) {
$cCol = $col->gridNumToCol($cellNum);
$tmp = array_merge($tmp,$cCol);
}
return $tmp;
}
public function lookupCoords ($num) {
//Find which grid we need
$g = (int) (floor($num/9)+1);
//Find which cell we need
$c = (int) ($num%9);
//Handle overflow
if ($c == 0) {
$g--;
$c = 9;
}
return [$g,$c];
}
public function getGridLineArrs () {
$cellArrs = [
[1, 4, 7, 28,31,34, 55,58,61],
[2, 5, 8, 29,32,35, 56,59,62],
[3, 6, 9, 30,33,36, 57,60,63],
[10,13,16, 37,40,43, 64,67,70],
[11,14,17, 38,41,44, 65,68,71],
[12,15,18, 39,42,45, 66,69,72],
[19,22,25, 46,49,52, 73,76,79],
[20,23,26, 47,50,53, 74,77,80],
[21,24,27, 48,51,54, 75,78,81],
[1, 2, 3, 10,11,12, 19,20,21],
[4, 5, 6, 13,14,15, 22,23,24],
[7, 8, 9, 16,17,18, 25,26,27],
[28,29,30, 37,38,39, 46,47,48],
[31,32,33, 40,41,42, 49,50,51],
[34,35,36, 43,44,45, 52,53,54],
[55,56,57, 64,65,66, 73,74,75],
[58,59,60, 67,68,69, 76,77,78],
[61,62,63, 70,71,72, 79,80,81],
];
return $cellArrs;
}
public function sortPlacementArr ($p = NULL) {
if ($p === NULL) {
$arr = $this->placementArr;
} else {
$arr = $p;
}
//echo "I'm sorting...".PHP_EOL;
//var_dump(array_slice($p,0,5));
$possibles = $this->findPossibles($arr);
//Sort our position array so the easiest items are first
uasort($possibles, function ($a, $b) {
$nA = count($a);
$nB = count($b);
if ($nA == $nB) {
return 0;
}
return ($nA < $nB)? -1 : 1;
});
$tmp = array_keys($possibles);
$arr = array_combine($tmp,$tmp);
if ($p === NULL) {
$this->placementArr = $arr;
}
return $arr;
}
}
| mit |
fymfym/SharpTask | src/Framework/SharpTaskExecuterService/Program.cs | 425 | using System.ServiceProcess;
namespace SharpTaskExecuterService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main()
{
var servicesToRun = new ServiceBase[]
{
new SharpTaskService()
};
ServiceBase.Run(servicesToRun);
}
}
}
| mit |
georgikostadinov/find-your-university | FindYourUniversity/Data/FindYourUniversity.Data.Models/ImageDocument.cs | 481 | namespace FindYourUniversity.Data.Models
{
using FindYourUniversity.Data.Common.Models;
public class ImageDocument : DeletableEntity
{
public int Id { get; set; }
public byte[] Image { get; set; }
public int ApplicationDocumentTypeId { get; set; }
public virtual ApplicationDocumentType ApplicationDocumentType { get; set; }
public string StudentId { get; set; }
public virtual Student Student { get; set; }
}
}
| mit |
surli/spinefm | spinefm-restfuncDSL-root/restfuncDSL/src/fr/unice/spinefm/scoping/RestfuncDSLScopeProvider.java | 340 | /*
* generated by Xtext
*/
package fr.unice.spinefm.scoping;
/**
* This class contains custom scoping description.
*
* see : http://www.eclipse.org/Xtext/documentation.html#scoping
* on how and when to use it
*
*/
public class RestfuncDSLScopeProvider extends org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider {
}
| mit |
adjohnson916/verb | verbfile.js | 132 | 'use strict';
var verb = require('./');
verb.task('default', function() {
verb.src('.verb*.md')
.pipe(verb.dest('./'));
});
| mit |
tectronics/paradice9 | test/telnet_server_option_fixture.cpp | 52537 | #include "telnet_server_option_fixture.hpp"
#include "odin/telnet/server_option.hpp"
#include "odin/telnet/input_visitor.hpp"
#include "odin/telnet/protocol.hpp"
#include "odin/telnet/stream.hpp"
#include "odin/telnet/negotiation_router.hpp"
#include "odin/telnet/subnegotiation_router.hpp"
#include "fake_datastream.hpp"
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/algorithm.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/typeof/typeof.hpp>
#include <vector>
CPPUNIT_TEST_SUITE_REGISTRATION(telnet_server_option_fixture);
using namespace std;
using namespace boost;
using namespace boost::assign;
namespace bll = boost::lambda;
typedef fake_datastream<odin::u8, odin::u8> fake_byte_stream;
class fake_server_option : public odin::telnet::server_option
{
public :
fake_server_option(
shared_ptr<odin::telnet::stream> const &stream
, shared_ptr<odin::telnet::negotiation_router> const &negotiation_router
, shared_ptr<odin::telnet::subnegotiation_router> const &subnegotiation_router)
: odin::telnet::server_option(
stream
, negotiation_router
, subnegotiation_router
, odin::telnet::KERMIT)
{
}
std::vector<odin::telnet::subnegotiation_type> subnegotiations_;
void send_subnegotiation(
odin::telnet::subnegotiation_content_type const &content)
{
odin::telnet::server_option::send_subnegotiation(content);
}
private :
virtual void on_subnegotiation(
odin::telnet::subnegotiation_type const &subnegotiation)
{
subnegotiations_.push_back(subnegotiation);
}
};
void telnet_server_option_fixture::test_constructor()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(odin::telnet::KERMIT, option.get_option_id());
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
}
void telnet_server_option_fixture::test_inactive_activate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
}
void telnet_server_option_fixture::test_inactive_activate_deny()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DONT)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
}
void telnet_server_option_fixture::test_inactive_activate_allow()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
}
void telnet_server_option_fixture::test_inactive_deactivate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (++bll::var(request_completed));
option.on_request_complete(request_complete_handler);
option.deactivate();
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
fake_byte_stream::input_storage_type expected_data;
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
}
void telnet_server_option_fixture::test_active_deactivate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
// Option is active HERE.
option.deactivate();
expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
}
void telnet_server_option_fixture::test_active_deactivate_deny()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
// Option is active HERE.
option.deactivate();
expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(2), request_completed);
}
void telnet_server_option_fixture::test_active_deactivate_allow()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
// Option is active HERE.
option.deactivate();
expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DONT)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(2), request_completed);
}
void telnet_server_option_fixture::test_non_activatable_inactive_activate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
}
void telnet_server_option_fixture::test_non_activatable_active_activate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
}
void telnet_server_option_fixture::test_non_activatable_inactive_deactivate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DONT)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
}
void telnet_server_option_fixture::test_non_activatable_active_deactivate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DONT)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
CPPUNIT_ASSERT_EQUAL(odin::u32(2), request_completed);
}
void telnet_server_option_fixture::test_activatable_inactive_activate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.set_activatable(true);
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
}
void telnet_server_option_fixture::test_activatable_active_activate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.set_activatable(true);
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
option.activate();
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
}
void telnet_server_option_fixture::test_activatable_inactive_deactivate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.set_activatable(true);
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DONT)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
}
void telnet_server_option_fixture::test_activatable_active_deactivate()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(false, option.is_activatable());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.set_activatable(true);
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
option.activate();
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(0), request_completed);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DONT)(odin::telnet::KERMIT));
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WONT)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
CPPUNIT_ASSERT_EQUAL(odin::u32(2), request_completed);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(true, option.is_activatable());
}
void telnet_server_option_fixture::test_inactive_subnegotiation()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
fake_byte_stream::input_storage_type subnegotiation =
list_of(odin::telnet::IAC)(odin::telnet::SB)(odin::telnet::KERMIT)
('a')('b')
(odin::telnet::IAC)(odin::telnet::SE);
fake_stream->write_data_to_read(subnegotiation);
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.subnegotiations_.empty());
}
void telnet_server_option_fixture::test_active_subnegotiation()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
fake_byte_stream::input_storage_type subnegotiation =
list_of(odin::telnet::IAC)(odin::telnet::SB)(odin::telnet::KERMIT)
('a')('b')
(odin::telnet::IAC)(odin::telnet::SE);
fake_stream->write_data_to_read(subnegotiation);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
odin::telnet::subnegotiation_type expected_subnegotiation;
expected_subnegotiation.option_id_ = odin::telnet::KERMIT;
expected_subnegotiation.content_ = list_of('a')('b');
CPPUNIT_ASSERT_EQUAL(std::size_t(1), option.subnegotiations_.size());
CPPUNIT_ASSERT_EQUAL(
expected_subnegotiation.option_id_
, option.subnegotiations_[0].option_id_);
CPPUNIT_ASSERT(
expected_subnegotiation.content_
== option.subnegotiations_[0].content_);
}
void telnet_server_option_fixture::test_send_subnegotiation()
{
boost::asio::io_service io_service;
shared_ptr<fake_byte_stream> fake_stream(
new fake_datastream<odin::u8, odin::u8>(io_service));
shared_ptr<odin::telnet::stream> telnet_stream(
new odin::telnet::stream(fake_stream, io_service));
shared_ptr<odin::telnet::negotiation_router> telnet_negotiation_router(
new odin::telnet::negotiation_router);
shared_ptr<odin::telnet::subnegotiation_router> telnet_subnegotiation_router(
new odin::telnet::subnegotiation_router);
odin::telnet::input_visitor visitor(
shared_ptr<odin::telnet::command_router>()
, telnet_negotiation_router
, telnet_subnegotiation_router
, NULL);
fake_server_option option(
telnet_stream, telnet_negotiation_router, telnet_subnegotiation_router);
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
odin::u32 request_completed = 0;
function<void ()> request_complete_handler = (
++bll::var(request_completed)
);
option.on_request_complete(request_complete_handler);
option.activate();
CPPUNIT_ASSERT_EQUAL(false, option.is_active());
CPPUNIT_ASSERT_EQUAL(true, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
fake_byte_stream::output_storage_type expected_data =
list_of(odin::telnet::IAC)(odin::telnet::WILL)(odin::telnet::KERMIT);
CPPUNIT_ASSERT(expected_data == fake_stream->read_data_written());
fake_stream->write_data_to_read(
list_of(odin::telnet::IAC)(odin::telnet::DO)(odin::telnet::KERMIT));
odin::telnet::stream::input_callback_type callback =
(
bll::bind(&odin::telnet::apply_input_range, ref(visitor), bll::_1)
);
telnet_stream->async_read(1, callback);
io_service.reset();
io_service.run();
CPPUNIT_ASSERT_EQUAL(true, option.is_active());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_activation());
CPPUNIT_ASSERT_EQUAL(false, option.is_negotiating_deactivation());
CPPUNIT_ASSERT_EQUAL(odin::u32(1), request_completed);
// Now test that sending the subnegotiation actually works.
odin::telnet::subnegotiation_content_type content = list_of('a')('b')('c');
option.send_subnegotiation(content);
io_service.reset();
io_service.run();
fake_byte_stream::output_storage_type expected_subnegotiation_data =
list_of(odin::telnet::IAC)(odin::telnet::SB)(odin::telnet::KERMIT)
('a')('b')('c')
(odin::telnet::IAC)(odin::telnet::SE);
CPPUNIT_ASSERT(
expected_subnegotiation_data == fake_stream->read_data_written());
}
| mit |
markovandooren/chameleon | src/org/aikodi/chameleon/core/namespace/NamespaceElement.java | 245 | package org.aikodi.chameleon.core.namespace;
//package be.kuleuven.cs.distrinet.chameleon.core.namespace;
//
//import be.kuleuven.cs.distrinet.chameleon.core.element.Element;
//
//public interface NamespaceElement extends Element {
//
//
//}
| mit |
arkbriar/nju_ds_lab2 | cli/utils/hash_file_md5.go | 468 | package utils
import (
"crypto/md5"
"encoding/hex"
"io"
"os"
)
func HashFileMD5(filePath string) (string, error) {
var returnMD5String string
file, err := os.Open(filePath)
if err != nil {
return returnMD5String, err
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return returnMD5String, err
}
hashInBytes := hash.Sum(nil)[:16]
returnMD5String = hex.EncodeToString(hashInBytes)
return returnMD5String, nil
}
| mit |
zdrjson/DDKit | Algorithm/UniqueMorseCodeWords.java | 661 | // Solution: HashTable
// Time complexity: O(n)
// Space complexity: O(n)
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] m = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
Set<String> s = new HashSet<>();
for (final String word : words) {
String code = ""; // JavaS的tring一定要初始化后才能添加字符串。
for (char c : word.toCharArray())
code += m[c - 'a'];
s.add(code);
}
return s.size();
}
}
| mit |
haikentcode/haios | haios/distance/__init__.py | 32 | def msg():
print "distance"
| mit |
extendssoftware/ExtendsFramework | tests/unit/Application/Router/Route/Constraint/Validator/String/UuidValidatorTest.php | 1190 | <?php
namespace ExtendsFramework\Application\Router\Route\Constraint\Validator\String;
class UuidValidatorTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \ExtendsFramework\Application\Router\Route\Constraint\Validator\String\UuidValidator::validate()
*/
public function testCanValidateUuidValue()
{
$validator = new UuidValidator();
$value = $validator->validate('1fbb8015-4e0d-44c0-ad0d-33b9bc520010');
$this->assertSame('1fbb8015-4e0d-44c0-ad0d-33b9bc520010', $value);
}
/**
* @covers \ExtendsFramework\Application\Router\Route\Constraint\Validator\String\UuidValidator::validate()
* @covers \ExtendsFramework\Application\Router\Route\Constraint\Validator\String\Exception\InvalidStringParameter::forUuid()
* @expectedException \ExtendsFramework\Application\Router\Route\Constraint\Validator\String\Exception\InvalidStringParameter
* @expectedExceptionMessage Value MUST be an valid UUID, got "foo".
*/
public function testCanNotValidateInvalidUuidValue()
{
$validator = new UuidValidator();
$validator->validate('foo');
}
}
| mit |
rabchev/output-panel | nls/root/strings.js | 647 | // English - root strings
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define({
"LBL_OK" : "OK",
"LBL_CANCEL" : "Cancel",
"LBL_TITLE" : "Output Panel Options",
"LBL_BUFF_SIZE" : "Buffer Size: ",
"LBL_BUFF_SIZE_HELP" : "(number of messages / lines).",
"LBL_TIMESTAMP" : "Timestamp: ",
"LBL_NONE" : "don't show",
"LBL_TIME" : "show time only",
"LBL_DATE" : "show date and time"
}); | mit |
DiscipleD/blog | src/client/components/post/post-header/index.ts | 558 | /**
* Created by jack on 16-4-27.
*/
import Vue from 'vue';
import Component from 'vue-class-component';
import './style.scss';
import template from './post-header.html';
import _defaultImg from '@/assets/img/tags-bg.jpg';
@Component({
props: {
boardImg: {
type: String,
default: _defaultImg,
},
title: {
type: String,
},
subtitle: {
type: String,
},
tags: {
type: Array,
},
createdTime: {
type: String,
},
},
template,
})
class PostHeader extends Vue {}
export default Vue.component('postHeader', PostHeader);
| mit |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_05_01/operations/_web_categories_operations.py | 7844 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class WebCategoriesOperations(object):
"""WebCategoriesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2021_05_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
name, # type: str
expand=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> "_models.AzureWebCategory"
"""Gets the specified Azure Web Category.
:param name: The name of the azureWebCategory.
:type name: str
:param expand: Expands resourceIds back referenced by the azureWebCategory resource.
:type expand: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: AzureWebCategory, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2021_05_01.models.AzureWebCategory
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.AzureWebCategory"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-05-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'name': self._serialize.url("name", name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('AzureWebCategory', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureWebCategories/{name}'} # type: ignore
def list_by_subscription(
self,
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.AzureWebCategoryListResult"]
"""Gets all the Azure Web Categories in a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AzureWebCategoryListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2021_05_01.models.AzureWebCategoryListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.AzureWebCategoryListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-05-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_subscription.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('AzureWebCategoryListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureWebCategories'} # type: ignore
| mit |
awesome1888/horns.template | tests/js/tests.js | 8054 | 'use strict';
window.Tests = {
getHelpers: function()
{
return {
quote: function(arg){
return '«'+arg+'»';
},
implodeArgs: function(){
return Array.prototype.slice.call(arguments).join(', ');
},
implode: function(arg){
return arg.join(', ');
},
ucFirst: function(arg){
arg = arg.toString();
return arg.substr(0, 1).toUpperCase()+arg.substr(1);
},
totalPrice: function(arg){
var sum = 0;
for(var k = 0; k < arg.length; k++)
{
sum += parseInt(arg[k].price) * parseInt(arg[k].quantity) * (arg[k].discount ? arg[k].discount : 1);
}
return sum;
},
isNotEmpty: function(arg){
return arg.length > 0;
},
getCost: function(arg1, arg2){
return this.price * this.quantity;
},
getCostAlt: function(arg1, arg2){
return (arg1.price * arg1.quantity) + ' of ' + arg2.payment[1].title;
},
getDiscountCost: function(){
var cost = this.price * this.quantity;
if(this.discount)
{
cost = Math.floor(cost * this.discount);
}
return cost;
},
isPistol: function(){
return this.type == 'P';
},
isRifle: function(){
return this.type == 'R';
},
isArmor: function(){
return this.type == 'A';
},
getFactionName: function()
{
return this == 'CT' ? 'CT Forces' : 'Terrorists';
}
};
},
getAll: function()
{
return [
{
data: {
personA: 'brown fox',
personB: 'dog'
},
template: 'The quick {{{quote personA}}} jumps over the lazy {{{quote personB}}}',
name: 'jumping',
result: 'The quick «brown fox» jumps over the lazy «dog»'
},
{
data: {
guestName: 'Steve',
meal: [
{
title: 'breakfast',
time: '9:00 am',
menu: ['Cup of coffee', 'Sandwich', 'Cigarette']
},
{
title: 'dinner',
time: '1:00 pm',
menu: ['Vegetable salad', 'Mushroom soup', 'Cherry compote', 'Bread']
},
{
title: 'supper',
time: '6:00 pm',
menu: ['Sausages with roasted potatoes', 'Cup of tea', 'Apple pie', 'Good movie to watch']
}
],
},
template: "<h3>Dear {{guestName}}, your menu for today is:</h3>" +
"<ul>" +
"{{#meal}}" +
"<li>" +
"<b>{{ucFirst title}}</b><br />" +
"Time: {{time}}<br />" +
"Dishes: {{implode menu}}" +
"</li>" +
"{{/meal}}" +
"</ul>",
name: 'menu',
result: '<h3>Dear Steve, your menu for today is:</h3><ul><li><b>Breakfast</b><br />Time: 9:00 am<br />Dishes: Cup of coffee, Sandwich, Cigarette</li><li><b>Dinner</b><br />Time: 1:00 pm<br />Dishes: Vegetable salad, Mushroom soup, Cherry compote, Bread</li><li><b>Supper</b><br />Time: 6:00 pm<br />Dishes: Sausages with roasted potatoes, Cup of tea, Apple pie, Good movie to watch</li></ul>'
},
{
data: {
basket: {
length: 4,
0: {
name: 'Fish&Chips',
quantity: 3,
price: 10
},
1: {
name: 'Pair of socks',
quantity: 5,
price: 700
},
2: {
name: 'Microwave owen',
quantity: 1,
price: 1500
},
3: {
name: 'Mercedes 600',
quantity: 1,
price: 900000000,
discount: 0.03
}
},
payment: [
{title: 'Visa/Master Card', value: 'card'},
{title: 'Cash', value: 'cash', default: true}
]
},
template:
"<form>" +
"<h3>Your order is:</h3>" +
"<div class=\"container\">" +
"{{#if isNotEmpty basket}}" +
"<table cellpadding=\"0\" cellspacing=\"0\">" +
"<thead><tr><th>Name</th><th>Price</th><th>Quantity</th><th>Cost</th></tr></thead>" +
"<tbody>" +
"{{#basket}}" +
"<tr>" +
"<td>{{name}}</td>" +
"<td>${{price}}</td>" +
"<td>{{quantity}}</td>" +
"<td>{{#if discount}}<s>{{/if}}${{getCost this this}}{{#if discount}}</s> (with discount: ${{getDiscountCost this}}){{/if}}</td>" +
"</tr>" +
"{{/basket}}" +
"</tbody>" +
"</table>" +
"{{else}}<span class=\"red\">Your basket is empty</span>{{/if}}" +
"</div>" +
"Total price: <span class=\"green\">${{totalPrice basket}}</span><br /><br />" +
"Pay with: " +
"<select>" +
"{{#payment}}" +
"<option value=\"{{value}}\" {{#if default}} selected=\"selected\"{{/if}}>{{title}}</option>"+
"{{/payment}}" +
"</select>" +
"</form>",
name: 'cart',
result: '<form><h3>Your order is:</h3><div class=\"container\"><table cellpadding=\"0\" cellspacing=\"0\"><thead><tr><th>Name</th><th>Price</th><th>Quantity</th><th>Cost</th></tr></thead><tbody><tr><td>Fish&Chips</td><td>$10</td><td>3</td><td>$30</td></tr><tr><td>Pair of socks</td><td>$700</td><td>5</td><td>$3500</td></tr><tr><td>Microwave owen</td><td>$1500</td><td>1</td><td>$1500</td></tr><tr><td>Mercedes 600</td><td>$900000000</td><td>1</td><td><s>$900000000</s> (with discount: $27000000)</td></tr></tbody></table></div>Total price: <span class=\"green\">$27005030</span><br /><br />Pay with: <select><option value=\"card\" >Visa/Master Card</option><option value=\"cash\" selected=\"selected\">Cash</option></select></form>'
},
{
data: {
basket: {
length: 4,
0: {
name: 'Fish&Chips',
quantity: 3,
price: 10
},
1: {
name: 'Pair of socks',
quantity: 5,
price: 700
},
},
payment: [
{title: 'Visa/Master Card', value: 'card'},
{title: 'Cash', value: 'cash', default: true}
]
},
template: '<la>{{getCostAlt basket.0 this}}</la>',
name: 'basket_sum',
result: '<la>30 of Cash</la>'
},
{
data: {
weapon: [
{
name: 'Glock-17',
type: 'P',
sides: ['CT'],
inManual: false
},
{
name: 'MP-5',
type: 'R',
sides: ['CT', 'T'],
inManual: true
},
{
name: 'AK-47',
type: 'R',
sides: ['T']
},
{
name: 'Kevlar',
type: 'A',
sides: ['CT', 'T'],
inManual: true
}
]
},
template:
"<h3>Counter-Strike 1.6 weapons:</h3>" +
"<ul>" +
"{{#weapon}}" +
"<li>{{name}}, type: {{#if isPistol this}}Pistol{{elseif isRifle this}}Rifle{{elseif isArmor this}}Armor{{else}}Unknown{{/if}}<br />" +
"Who can buy:<ul>" +
"{{#sides}}" +
"<li>{{getFactionName this}}{{#../../inManual}} <a href=\"#{{../../name}}\">See game manual</a>{{/../../inManual}}</li>" +
"{{/sides}}" +
"</ul>" +
"</li>" +
"{{/weapon}}" +
"</ul>",
name: 'cs',
result: '<h3>Counter-Strike 1.6 weapons:</h3><ul><li>Glock-17, type: Pistol<br />Who can buy:<ul><li>CT Forces</li></ul></li><li>MP-5, type: Rifle<br />Who can buy:<ul><li>CT Forces <a href=\"#MP-5\">See game manual</a></li><li>Terrorists <a href=\"#MP-5\">See game manual</a></li></ul></li><li>AK-47, type: Rifle<br />Who can buy:<ul><li>Terrorists</li></ul></li><li>Kevlar, type: Armor<br />Who can buy:<ul><li>CT Forces <a href=\"#Kevlar\">See game manual</a></li><li>Terrorists <a href=\"#Kevlar\">See game manual</a></li></ul></li></ul>'
},
{
data: {
jumps: [
{
personA: 'brown fox',
personB: 'dog'
},
{
personA: 'crazy elk',
personB: 'brutal crocodile'
},
{
personA: 'smelly squirrel',
personB: 'gorgeous giraffe'
}
]
},
template: "<h3>Jumping around:</h3> {{#jumps}} {{> jumping}} <br /> {{/jumps}}",
name: 'jumpingPairs',
result: '<h3>Jumping around:</h3> The quick «brown fox» jumps over the lazy «dog» <br /> The quick «crazy elk» jumps over the lazy «brutal crocodile» <br /> The quick «smelly squirrel» jumps over the lazy «gorgeous giraffe» <br /> '
}
];
}
};
| mit |